Clavem

Validate a license key in a JUCE audio plugin or standalone app

juce::URL blocks until the server answers, so run the validate call on a juce::Thread, never in processBlock, a constructor or the message thread. Share one client across all plugin instances in the process and read its state from an atomic.

One check per process, on its own thread

A DAW session can hold dozens of instances of your plugin in one process, and host scanners create instances without ever playing audio. Two rules follow. The network call runs on a background thread, and one client serves the whole process. In a plugin, hold the client in a juce::SharedResourcePointer<LicenseClient>: the first instance creates it, the last one destroys it.

Without sharing, a project with 80 instances sends 80 validate calls in seconds. The License API allows 60 per minute per key, so 20 of them get a 429. With sharing there is one request.

The code was compiled and run against JUCE 9.0.6’s juce_core on macOS, using a local mock of the documented responses and the live demo key. It needs verifyToken and isLicensed from the offline verification guide.

The client

class LicenseClient final : private juce::Thread
{
public:
    enum class State { checking, unlicensed, licensed, invalid, needsNetwork };

    juce::String base      { "https://clavem.io" };
    juce::String publicKey { "YOUR_PUBLIC_KEY" };   // from your product page
    juce::int64  productId = 75;                    // from your product page

    LicenseClient() : juce::Thread ("Clavem license check") {}
    ~LicenseClient() override { stopThread (6000); } // longer than the 4 s connection timeout below

    void startOnce()                      // any thread, any number of times
    {
        if (! started.exchange (true))
            startThread (juce::Thread::Priority::background);
    }

    State getState() const noexcept { return state.load(); }   // lock-free: processBlock() may call it
    juce::String getMessage() const { const juce::ScopedLock sl (lock); return message; }

    struct Reply { int status = 0; juce::var body; int retryAfter = 0; };

    /** Form-encoded POST. status stays 0 when there was no answer at all. */
    Reply post (const juce::String& action, const std::vector<std::pair<juce::String, juce::String>>& fields) const
    {
        auto url = juce::URL (base + "/v1/licenses/" + action);
        for (auto& [name, value] : fields)
            url = url.withParameter (name, value);

        Reply reply;
        juce::StringPairArray headers;
        auto stream = url.createInputStream (juce::URL::InputStreamOptions (juce::URL::ParameterHandling::inPostData)
                                                 .withConnectionTimeoutMs (4000)
                                                 .withStatusCode (&reply.status)
                                                 .withResponseHeaders (&headers));
        if (stream == nullptr) { reply.status = 0; return reply; }   // DNS, TLS or connection failure

        reply.body = juce::JSON::parse (stream->readEntireStreamAsString());   // void var when not JSON
        reply.retryAfter = headers["Retry-After"].getIntValue();
        return reply;
    }

    juce::File licenseFile() const
    {
        auto dir = juce::File::getSpecialLocation (juce::File::userApplicationDataDirectory)
                  #if JUCE_MAC
                   .getChildFile ("Application Support")
                  #endif
                   .getChildFile ("Inkwell");   // your product name
        dir.createDirectory();
        return dir.getChildFile ("license.json");
    }

    juce::var loadSaved() const { return juce::JSON::parse (licenseFile()); }   // void var when missing
    void save (const juce::var& v) const { licenseFile().replaceWithText (juce::JSON::toString (v)); }

private:
    void run() override
    {
        auto saved = loadSaved();
        if (! saved.isObject())
            return set (State::unlicensed);

        const auto now = juce::Time::currentTimeMillis() / 1000;
        const auto claims = verifyToken (saved["token"].toString(), publicKey);

        // Another instance, format or host process validated recently: skip the network.
        if (isLicensed (claims, productId, now) && now - (juce::int64) saved["last_checked"] < 24 * 3600)
            return set (State::licensed);

        const auto reply = post ("validate", { { "license_key", saved["key"].toString() },
                                               { "instance_id", saved["instance_id"].toString() } });
        if (reply.status == 200)
        {
            // Keep the new token even when the license is not valid: offline, it then says so.
            saved.getDynamicObject()->setProperty ("token", reply.body["token"]);
            saved.getDynamicObject()->setProperty ("last_checked", now);
            save (saved);
            return (bool) reply.body["valid"] ? set (State::licensed)
                                              : set (State::invalid, reply.body["error"].toString());
        }
        if (reply.status == 404)          // unknown key, or this device was removed: ask for the key again
        {
            licenseFile().deleteFile();
            return set (State::invalid, reply.body["error"].toString());
        }
        // No answer, 400, 429 or 503: trust the stored token while it is fresh.
        set (isLicensed (claims, productId, now) ? State::licensed : State::needsNetwork);
    }

    void set (State s, juce::String m = {})
    {
        { const juce::ScopedLock sl (lock); message = std::move (m); }
        state = s;
    }

    std::atomic<State> state { State::checking };
    std::atomic<bool> started { false };
    juce::CriticalSection lock;
    juce::String message;
};

Call startOnce() from the first prepareToPlay or from createEditor, not from the processor constructor. In the editor, a juce::Timer that reads getState() twice a second avoids callbacks that could outlive the client. If you push results with MessageManager::callAsync, capture a Component::SafePointer, not this.

What came back in the test

Against the live demo key, validate only, with no instance id:

status 200 valid=1 license status=active limit=3 token prefix=sgt1.eyJ2Ijo
unknown key: status 404 error=license_key not found.
missing key: status 400 error=license_key: Invalid input: expected string, received undefined

Against the mock, with the client started on a fresh state each time:

Scenario State Network requests
Valid, last check 0 licensed, token and last_checked saved 1
Checked a moment ago licensed 0
200, valid: false invalid, message “This license key has expired.” 1
404 invalid, license file deleted 1
429 or 503, fresh token licensed 1
429, stale token needs-network 1
Server never answers licensed from the token after 4,019 ms 1
Connection refused licensed from the token none reach the server

On macOS a 404 still returns a non-null stream with the status set. I read the Windows backend source in JUCE 9.0.6 and it behaves the same for 4xx.

JUCE and host specifics

  • Audio thread. processBlock reads getState() and decides to pass audio, mute or add a tone. It never waits, locks or allocates.
  • Shutdown. stopThread waits for an in-flight request, up to the 4 second connection timeout. If a host closes a project while a check is running, a longer wait would stall the host.
  • Sandboxed hosts. An app extension or sandboxed standalone needs the outgoing-network entitlement. Without it every request fails and the stored token is all you have.
  • Several processes. Hosts that sandbox plugins in separate processes get one check per process. The last_checked timestamp in the shared file keeps them to one request a day.
  • Shared file. replaceWithText writes a hidden temporary file and then replaces the target, so two hosts saving together do not leave half a file. Every plugin format reads the same file.

Doing this with Clavem

The three License API calls need no authentication and answer on the same paths as the Lemon Squeezy License API. Fields and limits are in the API reference.

Questions

Can I call juce::URL from processBlock?

No. createInputStream is synchronous and can wait for seconds on a bad network. The audio thread must only read a flag that a background thread sets.

Does JUCE come with license checks?

JUCE includes classes for online product authentication, where the app holds an RSA public key to authenticate the server's responses, with an implementation for the Tracktion Marketplace. This guide covers the other route, calling an HTTP license API yourself.

Sources

  1. JUCE documentation, juce::URL and InputStreamOptions (checked November 2026)
  2. JUCE documentation, juce::TracktionMarketplaceStatus (checked November 2026)
  3. Apple documentation, App Sandbox outgoing network entitlement (checked November 2026)