![tauri-plugin-keygen](assets/banner.webp)
# Tauri Plugin keygen
This plugin helps you implement timed licensing (with trial) and feature-base licensing for your Tauri desktop app using the [Keygen Licensing API](https://keygen.sh/docs/api/?via=tauri-plugin).
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.
## :tv: Video Tutorial
![How to License Your React/Tauri Desktop App](assets/tutorial_thumb.webp)
## :arrow_down: Install
> This plugin is made for Tauri v1. But, it'll be updated on Tauri v2 stable release.
đĻ Add the following line to `src-tauri/cargo.toml` to install the core plugin:
```toml
[dependencies]
tauri-plugin-keygen = { git = "https://github.com/bagindo/tauri-plugin-keygen", branch = "main" }
```
đž Install the JavaScript Guest bindings:
```sh
npm add https://github.com/bagindo/tauri-plugin-keygen#main
```
## :electric_plug: Setup
First, [sign-up for a free account](https://keygen.sh/?=tauri-plugin) and get your Keygen Account ID and Keygen Verify Key.
![Keygen Account Settings](assets/settings.webp)
Then, add them to the plugin builder in `src-tauri/src/main.rs`
```rust
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");
}
```
### :gear: Custom Configs
Optionally, you can specify custom configs to the plugin builder.
```rust
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 / matters for dir paths:
https://www.my-app.com/api/ :white_check_mark:
https://www.my-app.com/api :x:
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.
âšī¸ The cache is keyed with a hash of the today's date ("YYYY-MM-DD") and the license key.
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 validateCheckoutKey(), instead of relying on the validation response cache.
### :globe_with_meridians: `with_custom_domain`
You don't need to specify your Keygen Account ID if you're using Keygen [Custom Domain](https://keygen.sh/docs/custom-domains/?via=tauri-plugin).
```rust
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.
## :zap: Usage
### :stopwatch: Timed License - with trial
![Timed Licensing with trial](assets/esp-trial-license.gif)
In this [example](https://github.com/bagindo/tauri-plugin-keygen/tree/main/examples/esp-trial-license), 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](#tv-video-tutorial) for the step-by-step implementation.
The main code snippets:
đī¸ Routes Guard
#### `_licensed.tsx`
```javascript
// Tauri
import { getLicense, getLicenseKey } from "tauri-plugin-keygen-api";
// React
import { createFileRoute, redirect, Outlet } from "@tanstack/react-router";
export const Route = createFileRoute("/_licensed")({
// Before this layout route loads
beforeLoad: async ({ location }) => {
const license = await getLicense();
const licenseKey = await getLicenseKey();
// no valid licenses
if (license === null) {
// re-direct to license validation page
throw redirect({
to: "/validate", // the equivalent of a Login page in an Auth based system
search: {
redirect: location.href,
cachedKey: licenseKey || "",
},
});
}
},
component: () => ,
});
```
đī¸ Validation Page
#### `validate.tsx`
```javascript
// Tauri
import {
type KeygenError,
type KeygenLicense,
validateKey,
} from "tauri-plugin-keygen-api";
// React
import { useState } from "react";
import { createFileRoute, useRouter } from "@tanstack/react-router";
import { z } from "zod";
// Route Definition
export const Route = createFileRoute("/validate")({
validateSearch: z.object({
redirect: z.string().optional().catch(""),
cachedKey: z.string(),
}),
component: () => ,
});
// License Validation Page
function Validate() {
// routes
const router = useRouter();
const navigate = Route.useNavigate();
const { redirect, cachedKey } = Route.useSearch();
// local states
const [key, setKey] = useState(cachedKey);
const [loading, setLoading] = useState(false);
const [err, setErr] = useState("");
const validate = async () => {
setErr("");
setLoading(true);
let license: KeygenLicense;
// validate license key
try {
license = await validateKey({ key });
} catch (e) {
const { code, detail } = e as KeygenError;
setErr(`${code}: ${detail}`);
setLoading(false);
return;
}
// check license
if (license.valid) {
await router.invalidate();
await navigate({ to: redirect || "/" });
} else {
setErr(`${license.code}: ${license.detail}`);
}
setLoading(false);
};
return (
...
{/* License Key Input */}
setKey(e.target.value)}
/>
{/* Validate Button */}
{/* Help Text */}
{loading &&
validating license...
}
{err !== "" &&
{err}
}
);
}
```
### :medal_military: Feature Base License
![Feature Base Licensing](assets/esp-feature-license.gif)
In this [example](https://github.com/bagindo/tauri-plugin-keygen/tree/main/examples/esp-feature-license), 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](#tv-video-tutorial) for the step-by-step implementation.
The main code snippets:
đī¸ Main Page
#### `esp.tsx`
```javascript
// Tauri
import { getLicense } from "tauri-plugin-keygen-api";
// React
...
import { useAtom } from "jotai";
// App
import { proLicenseModalAtom } from "../atoms";
import ProLicenseModal from "../components/ProLicenseModal";
// Main Page
function ESP() {
return (
...
...
);
}
// PRO Feature Component
function ChooseImageButton({
onImageChosen,
}: {
onImageChosen: (file: string) => void;
}) {
// there's always a delay when opening the native file dialog with Tauri
// this lets the users know that "dialogOpen" is in progress by showing a Spinner
const [isOpeningFile, setIsOpeningFile] = useState(false);
const [_, setProModalOpened] = useAtom(proLicenseModalAtom);
const chooseImage = async () => {
setIsOpeningFile(true);
// get license
const license = await getLicense();
// check license and its entitlements
if (license === null || !license.valid || !license.entitlements.includes("ADD_IMAGE")) {
setProModalOpened(true); // Show Modal: "This feature requires a PRO License"
setIsOpeningFile(false);
return;
}
const file = await openFileDialog({
multiple: false,
title: "Choose Image",
filters: [
{
name: "Image",
extensions: ["png", "webp", "avif", "jpg", "jpeg"],
},
],
});
if (!Array.isArray(file) && file !== null) {
onImageChosen(file);
}
setIsOpeningFile(false);
};
return (
);
}
```
đ Pro License Modal
#### `ProLicenseModal.tsx`
```javascript
// Tauri
import { open as openLink } from "@tauri-apps/api/shell";
// React
import * as Dialog from "@radix-ui/react-dialog";
import { Link, useLocation } from "@tanstack/react-router";
import { useAtom } from "jotai";
// App
import { proLicenseModalAtom } from "../atoms";
export default function ProLicenseModal() {
const location = useLocation();
const [modalOpened, setModalOpened] = useAtom(proLicenseModalAtom);
return (
Pro Feature
This is a pro feature
{/* Go to License Validation Page */}
Enter License
{/* Buy License */}
{/* Validate Button */}
{/* Help Text */}
{loading &&
validating license...
}
{err !== "" &&
{err}
}
);
}
```
## :space_invader: JavaScript Guest Bindings
Available JavaScript APIs:
- [getLicense](#ticket-getlicense)
- [getLicenseKey](#old_key-getlicensekey)
- [validateKey](#rocket-validatekey)
- [validateCheckoutKey](#rocket-computer-validatecheckoutkey)
- [resetLicense](#-resetlicense)
- [resetLicenseKey](#-resetlicensekey)
### :ticket: `getLicense()`
Get the current license from the `LicensedState` in the Tauri App State.
Returns `KeygenLicense` or `null`.
```javascript
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",
// }
...
}
}
```
![getLicense() diagram](assets/get_license.webp)
How does this plugin manages `LicensedState`?
#### đ On App Loads: Look for offline license
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](https://keygen.sh/docs/api/cryptography/?via=tauri-plugin#cryptographic-lic) 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](https://keygen.sh/docs/api/signatures/?via=tauri-plugin#verifying-response-signatures) its signature, parse the cache into a `License` object, and load it into the Tauri App State.
#### đĢ No valid license
If no offline license is found, or if any of the offline license found is invalid due to any of the following reasons:
- Failed to decrypt the machine file
- The machine file `ttl` has expired
- Failed to verify the response cache signature
- The cache's age has exceed the allowed [`cache_lifetime`](#cache-lifetime-config)
- The parsed license object has expired
the `LicensedState` in the Tauri App State will be set to `None` (serialized to `null` in the front-end).
#### đ State Update
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()`.
### :old_key: `getLicenseKey()`
Get the cached license key.
Returns `string` or `null`.
![getLicenseKey() diagram](assets/get_license_key.webp)
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.
```javascript
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 cached `licenseKey` in the background. Checkout the [video tutorial](#tv-video-tutorial) to see how you can do this.
### :rocket: `validateKey()`
Send [license validation](https://keygen.sh/docs/api/licenses/?via=tauri-plugin#licenses-actions-validate-key) and [machine activation](https://keygen.sh/docs/api/machines/?via=tauri-plugin#machines-create) 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`.
```javascript
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}`);
}
};
```
![validateKey() diagram](assets/validate_key.webp)
What happens under the hood when you call `validateKey()`?
#### đ Parsing Machine Fingerprint
This plugin parses the user's machine `fingerprint` and includes it in both [license validation](https://keygen.sh/docs/api/licenses/?via=tauri-plugin#licenses-actions-validate-key) and [machine activation](https://keygen.sh/docs/api/machines/?via=tauri-plugin#machines-create) 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 to `UNIQUE_PER_POLICY` on your trial policy.
>
> See the [video tutorial](#tv-video-tutorial) for more details.
#### đ Verifying [Response Signature](https://keygen.sh/docs/api/signatures/?via=tauri-plugin)
> 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](#electric_plug-setup) 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.
#### đ Updating State and Cache
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`](#rocket-validatekey) is true, the verified response will be cached for later use as an offline license.
### :rocket: :computer: `validateCheckoutKey()`
Call `validateKey()`, then [download](https://keygen.sh/docs/api/machines/?via=tauri-plugin#machines-actions-check-out) 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 3600 Max 31_556_952 (1 year).
The ttl parameter sent to the machine checkout request will be the minimum of the defined ttlSeconds and the calculated secondsToExpiry of the current license.
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 MAINTAIN_ACCESS state (expired but still valid).
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 ttlSeconds (default to 86400).
Returns `KeygenLicense`. Throws `KeygenError`.
```javascript
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}`);
}
};
```
![validateCheckoutKey() diagram](assets/validate_checkout_key.webp)
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/`.