This plugin helps you implement timed licensing (with trial) and feature-base licensing for your Tauri desktop app using the Keygen Licensing API.
It handles license validation requests, verifies response signatures, caches valid responses, and manages the machine file for offline licensing.
Licensed state is managed in the Tauri App State (Rust back-end), and can be accessed via JavaSript Guest bindings in the front-end.
š¦ Add the following line to src-tauri/cargo.toml
to install the core plugin:
[dependencies]
tauri-plugin-keygen = { git = "https://github.com/bagindo/tauri-plugin-keygen", branch = "v2" }
š¾ Install the JavaScript Guest bindings:
npm add https://github.com/bagindo/tauri-plugin-keygen#v2
First, sign-up for a free account and get your Keygen Account ID and Keygen Verify Key.
Then, add them to the plugin builder in src-tauri/src/main.rs
fn main() {
tauri::Builder::default()
// register plugin
.plugin(
tauri_plugin_keygen::Builder::new(
"17905469-e476-49c1-eeee-3d60e99dc590", // š Keygen Account ID
"1e1e411ee29eee8e85ee460ee268921ee6283ee625eee20f5e6e6113e4ee2739", // š Keygen (Public) Verify Key
)
.build(),
)
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
Optionally, you can specify custom configs to the plugin builder.
fn main() {
tauri::Builder::default()
// register plugin
.plugin(
tauri_plugin_keygen::Builder::new(
"17905469-e476-49c1-eeee-3d60e99dc590", // š Keygen Account ID
"1e1e411ee29eee8e85ee460ee268921ee6283ee625eee20f5e6e6113e4ee2739", // š Keygen (Public) Verify Key
)
// chain custom config as needed
.api_url("https:://licensing.myapp.com") // š Self-hosted Keygen API url
.version_header("1.7") // š add Keygen-Version on request header
.cache_lifetime(1440) // š Response cache lifetime in minutes
.build(),
)
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
Config | Default | Description |
---|---|---|
api_url | https://api.keygen.sh |
Keygen API base URL. This config is useful if you're using Keygen Self Hosting.
Trailing
|
version_header | None |
Keygen pinned the API version you're using to your account.
This config is useful to test that everything still works, before you change your account's API version (e.g. from 1.3 to 1.7) on the Keygen Dashboard. Don't prefix the version string:
|
cache_lifetime | 240 |
The allowed lifetime, in minutes, for the cached validation response. Min 60 mins. Max 1440 mins (24h). ā¹ļø The cache is keyed with a hash of the today's date ( So, the maximum lifetime won't actually be the full 1440 mins, as the today's cache won't be loaded on midnight (the next day). For a longer offline licensing capability, you should use |
with_custom_domain
You don't need to specify your Keygen Account ID if you're using Keygen Custom Domain.
fn main() {
tauri::Builder::default()
// register plugin
.plugin(
tauri_plugin_keygen::Builder::with_custom_domain(
"https://licensing.myapp.com", // š Your Keygen Custom Domain
"1e1e411ee29eee8e85ee460ee268921ee6283ee625eee20f5e6e6113e4ee2739", // š Keygen (Public) Verify Key
)
// chain custom config as needed
.version_header("1.7") // š add Keygen-Version on request header
.cache_lifetime(1440) // š Response cache lifetime in minutes
.build(),
)
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
[!NOTE] Chaining the
api_url
config won't matter here.
In this example, the app's main page is guarded by a layout route _licensed.tsx
, that will re-direct users to the validation page if they don't have a valid license.
Watch the video tutorial for the step-by-step implementation.
The main code snippets:
In this example, users can access the app without having a license, except when they want to add an image to an ESP item.
Watch the video tutorial for the step-by-step implementation.
The main code snippets:
Available JavaScript APIs:
getLicense()
Get the current license from the LicensedState
in the Tauri App State.
Returns KeygenLicense
or null
.
import { getLicense } from "tauri-plugin-keygen-api";
const beforeLoad = async function () => {
let license = await getLicense();
if (license !== null) {
// {
// key: "55D303-EEA5CA-C59792-65D3BF-54836E-V3",
// entitlements: [],
// valid: true,
// expiry: "2024-06-22T02:04:09.028Z",
// code: "VALID",
// detail: "is valid",
// metadata: {},
// policyId: "9d930fd2-c1ef-4fdc-a55c-5cb8c571fc34",
// }
...
}
}
How does this plugin manages LicensedState
?
When your Tauri app loads, this plugin will look for any offline licenses in the [APP_DATA]/keygen/
directory.
If a machine file (š machine.lic
) is found, it will verify and decrypt the machine file, parse it into a License
object, and load it into the Tauri App State.
If there's no machine file, it'll look for the cache in š validation_cache
, verify its signature, parse the cache into a License
object, and load it into the Tauri App State.
If no offline license is found, or if any of the offline license found is invalid due to any of the following reasons:
ttl
has expiredcache_lifetime
the LicensedState
in the Tauri App State will be set to None
(serialized to null
in the front-end).
You can't update the LicensedState
directly.
Aside than initiating the state from the offline licenses on app loads, this plugin will update the licensed state with the verified response from validateKey()
or validateCheckoutKey()
, and reset it back to None
when you call resetLicense()
.
getLicenseKey()
Get the cached license key.
Returns string
or null
.
The license key is cached separately from the offline licenses, so that when the offline licenses expired and getLicense()
returns null
, you can re-validate without asking the user to re-enter their key.
import { getLicense, getLicenseKey } from "tauri-plugin-keygen-api";
const beforeLoad = async function () => {
let license = await getLicense();
let licenseKey = await getLicenseKey();
if (license === null) {
throw redirect({
to: "/validate", // the equivalent of a Login page in an Auth based system
search: {
cachedKey: licenseKey || "", // pass the cached licenseKey
},
});
}
}
[!TIP] Instead of re-directing to the
validate
page, you can re-validate the cachedlicenseKey
in the background. Checkout the video tutorial to see how you can do this.
validateKey()
Send license validation and machine activation requests.
Params | Type | Required | Default | Description |
---|---|---|---|---|
key | string |
ā | - | The license key to be validated |
entitlements | string[] |
[] |
The list of entitlement code to be validated | |
cacheValidResponse | boolean |
true |
Whether or not to cache valid response |
Returns KeygenLicense
. Throws KeygenError
.
import {
type KeygenLicense,
type KeygenError,
validateKey,
} from "tauri-plugin-keygen-api";
const validate = async (key: string, entitlements: string[] = []) => {
let license: KeygenLicense;
try {
license = await validateKey({
key,
entitlements,
});
} catch (e) {
const { code, detail } = e as KeygenError;
console.log(`Err: ${code}: ${detail}`);
return;
}
if (license.valid) {
...
} else {
const { code, detail } = license;
console.log(`Invalid: ${code}: ${detail}`);
}
};
What happens under the hood when you call validateKey()
?
This plugin parses the user's machine fingerprint
and includes it in both license validation and machine activation requests.
[!TIP] You can utilize machine fingerprints to prevent users from using multiple trial licenses (instead of buying one). To do this, set the
machineUniquenessStrategy
attribute toUNIQUE_PER_POLICY
on your trial policy.See the video tutorial for more details.
A bad actor could redirect requests to a local licensing server under their control, which, by default, sends "valid" responses. This is known as a spoofing attack.
To ensure that the response received actually originates from Keygen's servers and has not been altered, this plugin checks the response's signature and verifies it using the Verify Key you provided in the plugin builder.
A bad actor could also "record" web traffic between Keygen and your desktop app, then "replay" valid responses. For example, they might replay responses that occurred before their trial license expired, in an attempt to use your software with an expired license. This is known as a replay attack.
To prevent that, this plugin will reject any response that's older than 5 minutes, even if the signature is valid.
Once the response is verified, this plugin will update the LicensedState
in the Tauri App State with a License
object parsed from the response.
If the License
is valid and cacheValidResponse
is true, the verified response will be cached for later use as an offline license.
validateCheckoutKey()
Call validateKey()
, then download the machine file for offline licensing.
Params | Type | Required | Default | Descriptionn |
---|---|---|---|---|
key | string |
ā | - | The license key to be validated |
entitlements | string[] |
[] |
The list of entitlement code to be validated | |
ttlSeconds | number |
86400 |
The machine file's time-to-live in seconds. Min The |
|
ttlForever | boolean |
false |
If set to true, this plugin will download a machine file that never expires. ā ļø This will only work if the current license is in If set to true, but the current license is not in a maintain access state, this plugin will download a machine file with the defined You might find this useful when you're implementing a perpetual with fallback license. |
Returns KeygenLicense
. Throws KeygenError
.
import {
type KeygenLicense,
type KeygenError,
validateCheckoutKey,
} from "tauri-plugin-keygen-api";
const validate = async (key: string, entitlements: string[] = []) => {
let license: KeygenLicense;
try {
license = await validateCheckoutKey({
key,
entitlements,
ttlSeconds: 604800 /* 1 week*/,
});
} catch (e) {
const { code, detail } = e as KeygenError;
console.log(`Err: ${code}: ${detail}`);
return;
}
if (license.valid) {
...
} else {
const { code, detail } = license;
console.log(`Invalid: ${code}: ${detail}`);
}
};
As with validateKey()
, it will also parse the machine fingerprint, verify the response signature, and update the Tauri App State.
The only different is that when it received a valid license, instead of caching the response, this plugin will download the machine.lic
file for offline licensing.
resetLicense()
Delete all the offline licenses (validation cache and machine file) in [APP_DATA/keygen/]
and set the LicensedState
in the Tauri App State to None
.
resetLicenseKey()
Delete the cached license key on [APP_DATA]/keygen/
.