KeyWarden.Sdk 1.5.2

dotnet add package KeyWarden.Sdk --version 1.5.2
                    
NuGet\Install-Package KeyWarden.Sdk -Version 1.5.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="KeyWarden.Sdk" Version="1.5.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="KeyWarden.Sdk" Version="1.5.2" />
                    
Directory.Packages.props
<PackageReference Include="KeyWarden.Sdk" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add KeyWarden.Sdk --version 1.5.2
                    
#r "nuget: KeyWarden.Sdk, 1.5.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package KeyWarden.Sdk@1.5.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=KeyWarden.Sdk&version=1.5.2
                    
Install as a Cake Addin
#tool nuget:?package=KeyWarden.Sdk&version=1.5.2
                    
Install as a Cake Tool

KeyWarden.Sdk

The official .NET client for Key-Warden. Validate a software licence online — seat-aware, revocation-aware — or verify a signed token offline against your embedded public key, with no network round-trip.

Targets net8.0 and netstandard2.0 (so it runs on .NET Framework 4.6.1+, .NET Core, .NET 5–8, Xamarin, Unity). Ed25519 verification is provided by BouncyCastle.Cryptography.

dotnet add package KeyWarden.Sdk

Validate online

The authoritative check. Ask the platform whether a licence is good right now.

using KeyWarden;

var res = await KeyWardenClient.ValidateAsync(customerLicenceKey, new ValidateOptions
{
    ApimKey   = Environment.GetEnvironmentVariable("KW_APIM_KEY"),   // your APIM subscription key
    ClientKey = Environment.GetEnvironmentVariable("KW_CLIENT_KEY"), // your validation key
    MachineId = KeyWardenClient.MachineIdFrom(Environment.MachineName, userId), // stable, hashed your side
});

if (!res.Valid) throw new Exception($"licence not valid: {res.Reason}");
// res.Token is a freshly signed proof - cache it for the offline path below.

A Valid == false (e.g. revoked, expired, seat_limit_exceeded) is data, not an exception. A wrong ClientKey throws a KeyWardenError with Code == "unauthorized_client" — that's your auth failing, and your customer should never see it as a licence problem.

Verify offline

No connection? Verify a token you already hold against your public key — the 32-byte raw key from your vendor console. Pure and synchronous.

var check = KeyWardenClient.VerifyToken(cachedToken, publicKeyBase64);
if (!check.Valid) LockFeatures(check.Reason); // "bad_signature" | "expired" | ...

The token is header.body.signature (compact JWT style) and the Ed25519 signature covers the exact bytes header.body. This client verifies over those bytes — it never decodes-then-reverifies, which is the one mistake that silently breaks offline checks. Expiry is honoured within the offline grace window you set at mint time.

Online, with an offline fallback

The pattern most desktop apps want: online is authoritative; if the network is down, keep working within grace.

var res = await KeyWardenClient.ValidateOrVerifyAsync(customerLicenceKey, new ValidateOrVerifyOptions
{
    ApimKey = apimKey, ClientKey = clientKey, MachineId = machineId,
    CachedToken = lastGoodToken,   // from a previous ValidateAsync
    PublicKey   = publicKeyBase64,
});
// res.Source == "online" | "offline"

A rejected ClientKey (401) is never masked by the offline path — only a genuine reachability failure falls back.

Activation keys and grants

A Key-Warden key is opaque — KW-XXXX-XXXX-XXXX-XXXX. It carries no plan, no seat count and no term. Those live on the licence record, so a renewal, an upgrade, a seat top-up or a revocation lands at the customer's next check with nothing for them to paste.

Every check returns a signed grant bound to that key, that machine and that request. Verify it against the key set from your vendor console — a set, not a single key, so a signing-key rotation never breaks installs that have not updated yet:

var keys = new List<GrantKey>
{
    new GrantKey { Kid = "mitaa-k1", Pub = "BASE64_32_BYTE_KEY" },
    new GrantKey { Kid = "mitaa-k2", Pub = "BASE64_32_BYTE_KEY" },   // the incoming one
};

var res = await KeyWardenClient.ValidateAsync(licenceKey, new ValidateOptions
{
    ApimKey = apimKey, ClientKey = clientKey, MachineId = machineId,
    Keys      = keys,
    Product   = "acme-maps",
    UserCount = activeUsers,      // for banded plans
    EnvType   = "production",     // or let KW_ENV_TYPE / DOTNET_ENVIRONMENT decide
});

// res.GrantVerdict : Accept | Deny | Fallback (null when you baked no keys)
// res.ExpiresAt    : the licence term (NOT claims["exp"])

Offline, the same check without a network:

var g = Grant.Verify(cachedToken, keys, licenceKey, machineId, nonce);
switch (g.Verdict)
{
    case GrantVerdict.Accept:   RunApp();              break;
    case GrantVerdict.Deny:     Lock(g.Reason);        break;
    case GrantVerdict.Fallback: KeepLastKnownGood();   break;   // re-check online
}

offline_allowed is opt-in and omitted when you have not enabled it in the vendor console, so a cached grant returns Deny / offline_not_allowed until you do. That is the offline path only — a verdict that just came back live from ValidateAsync is applied as-is.

Three verdicts, and why Fallback is not a denial

Verdict When What you do
Accept good for this key and this machine licence the product
Deny wrong key, wrong machine, forged, expired past grace lock it
Fallback unknown kid, no keys baked in, unparseable keep your previous state and re-check online

GrantResult.Valid is true only on Accept — Fallback is deliberately neither valid nor a denial. Treating it as a denial turns a routine signing-key rotation into an outage. A known kid whose signature fails is a different thing entirely — that is forgery, and it denies.

expires_at is the term; exp is the refresh window

The single most misread pair in the model.

  • Grant.ExpiresAt(claims) / claims["expires_at"] — when the licence ends. Gate on this.
  • claims["exp"] — when the grant goes stale and should be refreshed. It is max(base TTL, grace + offline buffer), so an offline-enabled licence gets a grant that deliberately outlives its own grace window. Gating access on exp locks out paying customers.

Grant.NeedsRefresh(claims) and Grant.InGrace(claims) answer those two questions directly.

What ValidateAsync now sends

Three headers you get for free, and should not strip:

  • X-Kw-Nonce — a fresh nonce per call, echoed inside the signed grant. Without it a captured answer replays.
  • X-Kw-Env-Type — production unless you say otherwise (or KW_ENV_TYPE / DOTNET_ENVIRONMENT / ASPNETCORE_ENVIRONMENT says so). An undeclared staging box burns a paid production seat. Anything unrecognised reads as production — never the cheaper pool by accident.
  • X-Site-Url — the site label, for the vendor console.

A grant that fails verification sets GrantVerdict / GrantReason and Trustworthy = false. It does not flip Valid to false — a verification fault is ours, not the customer's, and must never downgrade a paying licence.

Free trials

A trial licence is an ordinary Key-Warden key — validate it exactly like any other. It just carries two extra claims: trial: true and an exp (unix seconds). Once the trial ends, VerifyToken/ValidateAsync refuse it as expired on their own. The trial helpers are for display — showing "N days left" and switching to an expired state:

var res = KeyWardenClient.VerifyToken(cachedToken, publicKeyBase64);

if (res.Valid)
{
    var t = KeyWardenClient.TrialInfo(res);   // TrialStatus { IsTrial, Expired, ExpiresAt, SecondsRemaining, DaysRemaining }
    if (t.IsTrial)
        ShowBanner($"Trial — {t.DaysRemaining} day(s) left");
    RunApp();
}
else if (res.Reason == "expired")
{
    ShowPaywall("Your trial has ended. Enter a licence key to continue.");
}

TrialInfo takes a VerifyResult (or a raw claims dictionary). IsTrial(x) and DaysRemaining(x) are shortcuts. DaysRemaining is rounded up (the last partial day still reads "1 day left") and is 0 once expired, null for a key with no exp. These helpers never grant access — always gate on VerifyToken/ValidateAsync first. Trial keys are node-locked to one device, so pass the same MachineId you use for ValidateAsync.

API

Member Purpose
ValidateAsync(key, ValidateOptions) Online check. Returns ValidateResult { Valid, Reason?, ActiveSeats?, Token? }.
VerifyToken(token, rawPubB64, now?) Offline check. Returns VerifyResult { Valid, Reason?, Claims? }.
ValidateOrVerifyAsync(key, ValidateOrVerifyOptions) Online, falling back to a cached token when unreachable.
MachineIdFrom(params string[]) A stable SHA-256 machine id; raw parts never leave the machine.
Grant.Verify(token, keys, activationKey?, machineId?, nonce?, now?) Offline grant check. Returns GrantResult { Verdict, Reason, Claims?, Valid }.
Grant.ExpiresAt(claims) The licence term as a DateTimeOffset? — expires_at, never exp. null for perpetual.
Grant.NeedsRefresh(claims, now?) true once the grant's exp has passed and it should be re-fetched.
Grant.InGrace(claims, now?) true when the licence has lapsed but is still inside its offline grace window.
TrialInfo(x, now?) Trial facts for display: TrialStatus { IsTrial, Expired, ExpiresAt, SecondsRemaining, DaysRemaining }.
IsTrial(x) true when the licence carries trial: true.
DaysRemaining(x, now?) Whole days left (rounded up); 0 once expired; null if no exp.

Any real failure (bad credentials, unreachable gateway, server error) throws KeyWardenError, which carries .Code and .Status.

Verify the build yourself

The repository ships a console self-test that mints tokens exactly the way the platform signs them, then runs the same checks used to certify the Node and Python clients:

dotnet run --project selftest/KeyWarden.Sdk.SelfTest -- ../../grant-vectors.json
#   20 passed, 0 failed   (legacy surface)
#   19 passed, 0 failed   (grant conformance - vectors signed by the platform itself)
#   21 passed, 0 failed   (client contract - what ValidateAsync puts on the wire)

grant-vectors.json is minted by the platform's own signer, not a lookalike, and all four SDKs run the same vectors — so they cannot drift apart. Omit the path and the self-test looks for the repo copy; if it cannot find it, it says so and fails rather than quietly skipping.

Security notes

  • Your private signing key never leaves Key-Warden's Key Vault. You embed only the 32-byte public half.
  • MachineId is hashed by the platform, but send an opaque, stable id — not a raw MAC address or a hostname you wouldn't want logged. MachineIdFrom() hashes on your side too.
  • Two independent credentials gate every online call: the APIM subscription key gets you to the gateway, the validation key authenticates you as the vendor. A leaked validation key can be rotated without reissuing a single customer licence.

Code protection (Seal / Unlock / Unseal)

Lock part of your product so it only runs for a valid, activated licence. Get your content key (base64) from the vendor console → Protect your code.

// Build time — seal a file once:
var blob = KeyWardenClient.Seal(File.ReadAllBytes("secret.dll"), MyContentKeyBase64);
File.WriteAllText("secret.sealed", blob);   // ship this instead

// Runtime — the key rides in the validate token as `ck`, machine-bound:
var res  = await KeyWardenClient.ValidateAsync(licence,
             new ValidateOptions { ApimKey = apim, ClientKey = ck, MachineId = mid });
byte[] key  = KeyWardenClient.UnlockFromToken(res.Token, mid);   // content key
byte[] code = KeyWardenClient.Unseal(sealedBlob, key);           // decrypted bytes

// Or a live check every time (real-time revocation):
byte[] key2 = await KeyWardenClient.UnsealOnlineAsync(licence,
                new UnsealOptions { ApimKey = apim, MachineId = mid });

All AES-256-GCM. Unlock needs the SAME MachineId you validate with. A revoked licence stops getting the key.

Licence

MIT.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.5.2 87 9/14/2026
1.5.1 87 9/14/2026
1.3.0 118 8/23/2026
1.2.2 112 8/22/2026
1.2.1 112 8/22/2026
1.0.6 103 8/12/2026
1.0.0 105 8/12/2026