Python
Add licensing to a Python app with the pwfauth package from PyPI
The pwfauth package from PyPI handles the encryption, the heartbeat and the kill switch for you. It needs Python 3.9 or newer, works on Windows, Linux and macOS, and has one dependency, cryptography, because Python has no AES of its own
Install
pip install pwfauthThe package talks only to https://pwfauth.com, and since 1.4.0 to the same server as https://pwfauth.net when pwfauth.com gives no reply at all (some networks block the name). Any other server address is refused
Keep the secret out of your code
Read the 64-character app secret of your application (see Applications) at start-up instead of writing it in the source, for example from an environment variable, as the code below does with PWFAUTH_SECRET. Never commit a real secret
Sign in and start the heartbeat
import os
import sys
from pwfauth import PwfClient
client = PwfClient(os.environ["PWFAUTH_SECRET"])
def on_session_ended(error_code, message):
# runs on the heartbeat thread, where sys.exit would end only that thread
print(f"Signed out ({error_code}): {message}", file=sys.stderr)
os._exit(1)
client.on_session_ended = on_session_ended
login = client.login(key.strip())
if not login.success:
print(login.message, file=sys.stderr) # written for the customer
sys.exit(1)
client.start_heartbeat() # the kill switch: never skip iton_session_ended gets the code and the message when the key is banned, paused, expired, deleted or reset, when you end the session from the panel, when the app goes into maintenance, when an account's password changes, and when three heartbeats in a row get no encrypted answer (NETWORK_LOST, or CLOCK_SKEW when the PC's clock is the reason). How often it checks is in How protection works
The callback runs on the heartbeat's own thread. In a GUI, hand the work to your toolkit's thread, for example with Tkinter:
client.on_session_ended = lambda code, msg: root.after(0, sign_out, code, msg)A console tool or a service can call client.run_heartbeat() instead, which blocks until the session ends
Show the license
The sign-in reply carries everything about the key, and login.license reads the license part:
lic = login.license
if lic.is_lifetime:
status = "Lifetime license" # expires_at is None for lifetime keys
else:
status = f"Expires {lic.expires_at:%Y-%m-%d}, {lic.days_remaining} day(s) left"It also has license_key, key_type, duration, hwid, activated_at and status. The rest is in login.data: app (name, version, and your welcome message in message), features, texts and slides. login.get_boolean("pro_export") reads a feature flag
Remote texts come as a map of names to texts, with the key's own values applied (see Texts & slides). get_texts() fetches them again for the signed-in key while the program runs:
texts = client.get_texts().data.get("texts") or {}
title = texts.get("welcome", "Welcome")Move the license to a new PC
When the key belongs to another PC, offer to move it. This works when self-service is on for the app (see HWID resets):
from pwfauth import PwfErrorCodes
login = client.login(key)
if login.error_code in (PwfErrorCodes.HWID_MISMATCH, PwfErrorCodes.DEVICE_LIMIT):
if ask_user(login.message + "\nMove your license to this PC?"):
moved = client.reset_hardware_id(key, "Moved to a new PC")
show(moved.message)
if moved.success:
login = client.login(key)The move unbinds the key from every PC and ends its sessions. A refusal names the reason in moved.error_code: SELF_RESET_DISABLED, RATE_LIMITED (the message says how long to wait), KEY_NOT_ACTIVE or NO_HWID
Customer accounts
Instead of a key, a customer can sign in with a username and password (see Users). The session and the heartbeat work exactly as with a key:
login = client.account_login(username, password)
if not login.success:
show(login.message) # INVALID_CREDENTIALS, BANNED, PAUSED, EXPIRED, HWID_MISMATCH …
else:
client.start_heartbeat()Sign-up, keys and password changes, when sign-up is on for the app:
r = client.register_account(username, password, email=email) # REGISTRATION_DISABLED when sign-up is off
if r.error_code == PwfErrorCodes.KEY_REQUIRED: # "Sign-up needs a license key" is on
r = client.register_account_with_key(username, password, key, email=email)
more = client.redeem_key(key) # signed in: adds the key's time
back = client.redeem_key(key, username, password) # signed out, works after expiry too
c = client.change_account_password(username, current_password, new_password)A changed password signs out every copy using the account, the one that changed it too: sign in again with the new password. An account is bound to one PC; when it moves, you reset its machine in Users. A key spent on an account cannot sign in on its own any more: login answers KEY_REDEEMED
Sign out
client.logout() # ends the session; the key stays bound to this PCErrors and what the customer sees
A refusal is a normal reply: success is False, error_code is for your code and message is written for the customer, in your own words if you set them in Applications → Messages. Show the message; branch on the code (each one is on PwfErrorCodes, see Error codes). An exception means the reply never came or cannot be trusted:
| Exception | Means |
|---|---|
PwfHttpError | No usable reply: e.status is 401 for a wrong app secret, 0 for no connection |
PwfSecurityError | No valid PWF Auth signature (a proxy's error page counts too), or a plain "success" where an encrypted reply was due. Never unlock the program on it |
PwfCryptoError | The encrypted reply could not be opened, usually because of a wrong app secret |
PwfRefusedError | A refusal from the calls that return a value (user variables, add-ons, protected files); e.error_code holds the code |
All four derive from PwfError
Signed replies
Every request carries a fresh random nonce, and every reply, errors included, must carry PWF Auth's RSA signature over that exact request and reply. The package checks it with the public key it carries before it reads anything, so knowing your app secret is not enough to fake an answer. That stops a fake server, not someone who patches the program on their own PC: keep the part that matters on the server, for example as a protected file (see App settings → Files)
More calls
| Call | Does |
|---|---|
check_key(key) | Reads a key's status without signing in or using a machine seat |
create_trial() | A trial key for this PC, when trials are on for the app |
get_app_info() / get_slides() | App name, version, download link and maintenance state; announcement slides |
set_variable(name, value) / get_variable(name) / get_variables() / delete_variable(name) | Values kept on the server for this customer, see User variables. Version 1.5.0 or newer |
redeem_addon(key) / addons / has_addon(code) / on_addons_changed | Add-ons unlocked with an add-on key, see App settings → Add-ons. Version 1.6.0 or newer |
get_resource(name) | A protected file, as bytes checked against the SHA-256 the server sends. Version 1.6.0 or newer |
check_update(version, channel) | Is there a newer build? See Updates |
get_hardware_id() | This PC's ID, made the same way as in the other official clients, so one PC counts as one device |
PwfClient also takes keyword options, such as timeout (15 seconds), max_heartbeat_failures (3), heartbeat_seconds and auto_correct_clock, which corrects a wrong PC clock from the server's time and is on by default
Step by step
For a walk-through from a new application to a protected script, with a video, read How to add license keys with an HWID lock to a Python app. The source of the package is on GitHub
Something missing or unclear? Tell us on Telegram