DEV Community

Argoness Vane
Argoness Vane

Posted on

How We Built a Zero-Pro-Bytes Split-Binary Desktop App in Python (Ed25519 + Cloudflare Workers KV + Native Cython .pyd)

When you ship a commercial Python desktop developer tool, standard single-file packaging (PyInstaller / Nuitka / cx_Freeze) has a well-known problem: anyone can unpack your installer in thirty seconds with pyinstxtractor and read every if is_pro: check in plain bytecode.

While building Token Czar v2.0 (our local PreToolUse context-window and prompt-cache hygiene guard for Claude Code, Cursor, and Antigravity), we wanted two things that usually fight each other:

  1. A 100% free, clean, zero-telemetry Lite desktop app any developer can download and verify immediately.
  2. Literally zero Pro code bytes inside the free binary—so there is nothing to crack, patch, or decompile out of the free download.

Here is the exact split-binary architecture we ended up shipping, and the real production edge cases we hit along the way.


1. Why Context-Window Hygiene Matters First

Before touching packaging, the core engineering problem we were solving was runaway token burn in agentic coding IDEs:

  • Unbounded file reads: Asking an agent to inspect one function in a 1,400-line file frequently dumps 800 lines into active context, then re-bills those tokens on every subsequent turn.
  • Full-file overwrites: Emitting an entire 600-line file via write_file(Overwrite=true) instead of a surgical diff hunk wastes output tokens and inflates history.
  • Cold prompt-cache cliffs: Letting a long thread cross a 5-minute TTL boundary or accumulate >165K tokens triggers expensive cache misses on the very next tool call.

Our <5 ms local PreToolUse hook intercepts unwindowed reads over 350 lines and returns a compact Python AST symbol map (Lstart-Lend) (or 80-line [CHUNK] anchors for JSON/shaders/configs) plus a 50-line header, so the agent jumps straight to the exact function window on its first read.

Note: Token Czar is a local context-hygiene tool, not a provider billing cap—always configure hard monthly spend limits directly in your model provider dashboard. Context-reduction percentages vary by repo and workflow.


2. The Zero-Pro-Bytes Split-Binary Architecture

Instead of hiding paid features behind a boolean flag, the Free Lite build (TokenCzar-Setup-v2.0.0.exe) ships only:

  • The Lite GUI/CLI host (WebView2 + local hook installer)
  • A 32-byte Ed25519 public verification key (VERISTRUX_ED25519_PUB_B64)
  • Zero Pro modules, zero Pro strings, zero Pro symbols—enforced by an automated zlib-decompression audit stage during build.

When a user activates a paid Pro license key, the app performs a single HTTPS handshake (~400 ms end-to-end):

[Lite Host (0 Pro bytes)]
   |  POST /v1/activate
   |  { key, machine_hwid (salted SHA-256), py_abi, app_version, eula_version }
   v
[Cloudflare Worker Edge]
   |-- 1. Validates seat + conditions:{hwid} against Polar.sh Merchant of Record API
   |-- 2. Verifies benefit_id matches ONLY Token Czar Pro SKUs
   |-- 3. Fetches compiled native `tokenczar_pro.cp312-win_amd64.pyd.gz` (143 KB)
   |      + `.sha256` from Cloudflare Workers KV
   |-- 4. Signs a 72-hour HWID-bound lease with WebCrypto Ed25519 (private seed in Worker Secrets only)
   '-- 5. Writes minimal 24-month auto-TTL seat ledger entry to KV
   v
[Lite Host]
   |-- Verifies Ed25519 signature over canonical sorted JSON payload
   |-- Confirms `payload.hwid == get_machine_hwid()` and `expires_at > now`
   |-- Verifies SHA-256 of decompressed native Cython/MSVC `.pyd`
   '-- Hot-loads the native x64 `.pyd` in-process via `importlib.machinery.ExtensionFileLoader` (zero restart!)
Enter fullscreen mode Exit fullscreen mode

Canonical Ed25519 Verification on Both Sides

One subtle pitfall when signing JSON in Cloudflare Workers (JavaScript) and verifying in Python (cryptography) is key-order drift. Both sides must serialize identical canonical bytes:

// Cloudflare Worker (WebCrypto Ed25519)
function canonicalJson(obj) {
  const sorted = {};
  for (const k of Object.keys(obj).sort()) sorted[k] = obj[k];
  return JSON.stringify(sorted);
}
Enter fullscreen mode Exit fullscreen mode
# Python Desktop Host (cryptography Ed25519PublicKey)
def canonical_lease_bytes(lease_payload: dict) -> bytes:
    return json.dumps(
        lease_payload, sort_keys=True, separators=(",", ":"), ensure_ascii=True
    ).encode("utf-8")
Enter fullscreen mode Exit fullscreen mode

Because JSON.stringify in V8 uses no whitespace and json.dumps(..., sort_keys=True, separators=(",", ":")) matches it byte-for-byte for flat ASCII payloads, signature verification succeeds deterministically every time.


3. Two Real Production Gotchas We Caught During Live E2E Testing

  1. Pydantic min_length=1 on Upstream Metadata Fields: When calling Polar's /v1/customer-portal/license-keys/activate, sending an empty string inside meta (e.g. eula: "" when a client omits an optional field) returns a 422 RequestValidationError array of Pydantic error objects. Always strip empty keys before forwarding metadata, and explicitly format array detail payloads instead of coercing them with String(detail) (which produces "[object Object]").
  2. Workers KV vs. R2 for Sub-1 MiB Native Payloads: For a 143 KB gzipped .pyd artifact, Cloudflare Workers KV handles up to 25 MiB per value, serves globally at the edge, requires no separate object-storage billing setup, and supports native expirationTtl on activation-ledger keys for clean data retention.

Try the Free Lite Build or Inspect the Stack

If you're building local developer tools or MCP hooks in Python, happy to answer questions about Cython .pyd hot-loading, WebCrypto Ed25519 PKCS#8 wrapping, or PreToolUse AST windowing in the comments!

Top comments (0)