Clavem

Validate a license key in a Blender add-on

Blender's API docs say Python threads are not supported, so call POST /v1/licenses/validate with urllib from a bpy.app.timers callback with a short timeout, or hand the call to a second Python process. Check bpy.app.online_access first, and fall back to the stored token when there is no answer.

What Blender decides for you

  • No threads. The API docs say Python threads cause Blender to crash “in hard to diagnose ways”, with a download in a background thread as one example. They only work when the thread finishes before the script does. The usual Python answer to a slow HTTP call is not available.
  • Online access is the user’s choice. An add-on that uses the internet must read bpy.app.online_access. It is read-only, follows Preferences (and the --offline-mode and --online-mode command-line flags), and Blender cannot stop an add-on that ignores it.
  • A manifest permission. An extension that calls the network lists it in blender_manifest.toml, with a reason of up to 64 characters and no full stop.
  • A user folder per extension. bpy.utils.extension_path_user(__package__, create=True) returns a writable folder that survives upgrades. The extension’s own folder does not: upgrades clear it.
[permissions]
network = "Check the license with the license server"
files = "Keep the license in the user folder"

Blender’s Python API has no credential store that I could find. The key goes in a file in that folder, with mode 0600 where the platform supports it. That is plain text on disk, as it would be in the add-on preferences.

The check, without threads

This runs on Blender 4.2 or later. is_licensed and verify_token come from the offline verification guide. Each network step waits at most five seconds, and the call blocks the main thread while it does, so it runs from a timer two seconds after start-up instead of inside register().

import json, os, platform, urllib.error, urllib.request
import bpy
from .token import is_licensed, verify_token

BASE = "https://clavem.io"


def _state_file() -> str:
    # __package__ is the extension's own id.
    return os.path.join(bpy.utils.extension_path_user(__package__, create=True), "license.json")


def load() -> dict | None:
    try:
        with open(_state_file(), encoding="utf-8") as f:
            return json.load(f)
    except (OSError, ValueError):
        return None


def save(state: dict | None) -> None:
    path = _state_file()
    if state is None:
        if os.path.exists(path):
            os.remove(path)
        return
    tmp = path + ".tmp"
    with open(tmp, "w", encoding="utf-8") as f:
        json.dump(state, f)
    os.replace(tmp, path)  # a crash never leaves half a file
    try:
        os.chmod(path, 0o600)
    except OSError:
        pass  # Windows


def post(action: str, body: dict) -> tuple[int, dict]:
    """Blocks while it waits, with 5 seconds per network step. Returns (0, {}) when there is no answer."""
    request = urllib.request.Request(
        f"{BASE}/v1/licenses/{action}",
        data=json.dumps(body).encode(),
        headers={"Content-Type": "application/json", "User-Agent": "Inkwell/3.2"},
    )
    try:
        with urllib.request.urlopen(request, timeout=5) as response:
            return response.status, json.load(response)
    except urllib.error.HTTPError as error:  # 4xx and 5xx still carry a JSON body
        try:
            return error.code, json.load(error)
        except ValueError:
            return error.code, {}
    except (OSError, ValueError):  # no network, DNS failure, timeout, a reply that is not JSON
        return 0, {}


def decide(state: dict, status: int, reply: dict) -> str:
    """Turns an answer (status 0 means none) into 'licensed', 'invalid' or 'needs-network'."""
    if status == 200:
        # Keep the new token even when the license is not valid: offline, it then says so.
        save({**state, "token": reply["token"]})
        return "licensed" if reply["valid"] else "invalid"
    if status == 404:
        save(None)  # unknown key, or this computer was removed: ask for the key again
        return "invalid"
    # Offline, rate limited (429) or the service is down (5xx): trust the token while it is fresh.
    return "licensed" if is_licensed(verify_token(state["token"])) else "needs-network"


def check() -> str:
    """Returns 'licensed', 'invalid', 'needs-network' or 'unlicensed'."""
    state = load()
    if state is None:
        return "unlicensed"
    status, reply = (0, {})
    if bpy.app.online_access:  # Preferences > System > Network > Allow Online Access
        status, reply = post("validate", {"license_key": state["key"], "instance_id": state["instance_id"]})
    return decide(state, status, reply)


licensed = False


def _first_check():
    global licensed
    licensed = check() == "licensed"
    return None  # run once


class INKWELL_OT_activate(bpy.types.Operator):
    bl_idname = "inkwell.activate_license"
    bl_label = "Activate License"
    key: bpy.props.StringProperty(name="License key")

    def invoke(self, context, event):
        return context.window_manager.invoke_props_dialog(self)

    def execute(self, context):
        global licensed
        key = self.key.strip()
        _, reply = post("activate", {"license_key": key, "instance_name": platform.node() or "Blender"})
        if not reply.get("activated"):
            self.report({"ERROR"}, reply.get("error") or "Could not reach the license server.")
            return {"CANCELLED"}
        save({"key": key, "instance_id": reply["instance"]["id"], "token": reply["token"]})
        licensed = True
        return {"FINISHED"}


def register():
    bpy.utils.register_class(INKWELL_OT_activate)
    bpy.app.timers.register(_first_check, first_interval=2.0)


def unregister():
    if bpy.app.timers.is_registered(_first_check):
        bpy.app.timers.unregister(_first_check)
    bpy.utils.unregister_class(INKWELL_OT_activate)

When a frozen second is too much

On a network that drops packets silently, the call waits out its timeout. The way around it is a second Python process. The threading page recommends the multiprocessing module for code that should run independently of Blender, and a plain subprocess is the simpler form of the same idea. The child never imports bpy, and a timer polls for its answer. bpy.app.python_args holds the leading arguments for calling Python through sys.executable.

import subprocess, sys

_CHILD = """
import json, sys, urllib.request, urllib.error
req = urllib.request.Request(sys.argv[1] + "/v1/licenses/validate", data=sys.stdin.read().encode(),
                             headers={"Content-Type": "application/json", "User-Agent": "Inkwell/3.2"})
try:
    with urllib.request.urlopen(req, timeout=8) as r:
        status, text = r.status, r.read()
except urllib.error.HTTPError as e:
    status, text = e.code, e.read()
except OSError:
    status, text = 0, b"{}"
try:
    reply = json.loads(text)
except ValueError:
    reply = {}
print(json.dumps({"status": status, "reply": reply}))
"""


def check_in_background(on_done) -> None:
    state = load()
    if state is None or not bpy.app.online_access:
        on_done(check())  # nothing to wait for
        return
    proc = subprocess.Popen(
        [sys.executable, *bpy.app.python_args, "-c", _CHILD, BASE],
        stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True,
    )
    proc.stdin.write(json.dumps({"license_key": state["key"], "instance_id": state["instance_id"]}))
    proc.stdin.close()  # the key goes through stdin, not the command line

    def poll():
        if proc.poll() is None:
            return 0.25  # still running: look again in a quarter of a second
        try:
            out = json.loads(proc.stdout.read())
        except ValueError:
            out = {"status": 0, "reply": {}}
        on_done(decide(state, out["status"], out["reply"]))
        return None

    bpy.app.timers.register(poll, first_interval=0.25)

Outcomes

Answer decide() returns Stored state
200, valid: true licensed token replaced
200, valid: false invalid token replaced, key kept
404 invalid file deleted
429 or 5xx stored token decides unchanged
no answer, or online access off stored token decides unchanged

A Blender session can last for days. To re-validate during one, return 24 * 3600 from the timer function instead of None. A 429 carries Retry-After: 60, and a daily interval clears it.

Tested how

The bpy calls (extension_path_user, timers, online_access, python_args) are used as the Blender docs describe them. As with any add-on, try the finished build in the Blender versions you support before you ship.

Doing this with Clavem

Clavem’s License API needs no secret, so the add-on ships nothing sensitive. The code is open to anyone who installs the add-on, which makes the check a way to keep honest users honest. The API reference describes every status the code above handles.

Questions

Can I validate in a background thread?

Blender's API docs say Python threads are not supported and can crash Blender in hard-to-diagnose ways, and they give a background download as an example. Use a timer with a short timeout, or a subprocess that never imports bpy.

Can I sell a licensed add-on on the Blender Extensions platform?

The manual says the platform only supports free and open-source extensions, and add-ons there need GPL-3.0-or-later. A paid add-on is distributed from your own site or another store, and that distribution is where a license key matters. Ask a lawyer how the GPL applies to your add-on.

Sources

  1. Blender Python API, Python Threads are Not Supported (checked November 2026)
  2. Blender manual, add-ons (internet access, local storage; checked November 2026)
  3. Blender manual, getting started with extensions (manifest permissions; checked November 2026)
  4. Blender manual, extension licenses (checked November 2026)
  5. Blender Python API, bpy.app (online_access, python_args; checked November 2026)