Skip to navigation

Rust guide

This page walks through the whole Rust SDK in the order you would use it. Each step starts with the shortest code that works, then shows the other ways to write it.

Download the Rust SDK if you have not done so yet.

Requirements

SupportedRecommended
Rust1.75 and newerThe current stable release
RuntimeTokio 1.x
WindowsAny Windows your Rust version supports

On Linux and macOS, AuthlyX::new returns an error because there is no Windows user ID to read. Use AuthlyX::withOptions with your own systemId and storage, as shown in Options.

Add the SDK to your project

Unzip the download into a folder in your project, for example authlyx, and add it to Cargo.toml together with Tokio and serde_json:

[dependencies]
authlyx-sdk-v3 = { path = "authlyx" }
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
serde_json = "1"
chrono = "0.4"

chrono is only needed for the date helpers further down. With Rust older than 1.84, copy the Cargo.lock from the download into your project so Cargo picks dependency versions that work with your compiler.

use authlyx_sdk_v3::{AuthlyX, Error, Event};

Create the client

let app = AuthlyX::new("YOUR_APP_KEY", "1.0.0").await?;

The first value is your app’s AppKey. Find it in the dashboard under your application’s credentials. The second is the version of the program you are building. AuthlyX compares it with the versions you allow in the dashboard, so raise it each time you ship a new build. See Allowed Versions.

Create one client for the whole program. It is cheap to clone, and every clone shares the same session, so pass clones to the tasks and functions that need it. Client is another name for the same type. Creating the client does not connect; nothing is sent until you call init.

To change settings, start from the defaults:

async fn create() -> Result<AuthlyX, Error> {
let mut options = AuthlyX::defaults("YOUR_APP_KEY", "1.0.0")?;
options.update_prompt = false;
options.request_budget = std::time::Duration::from_secs(15);
AuthlyX::withOptions(options).await
}

All the options are listed in Options.

Three ways to call the SDK

Calls that talk to AuthlyX are async and return Result<Response, Error>. You can use them in three ways:

StyleLooks likeUse it when
.awaitlet started = app.init().await?;Your program runs on Tokio
Callbackapp.initWith(|result| { ... });You want to start a call and carry on
Blockingruntime.block_on(app.init())Your program is not async

.await

use authlyx_sdk_v3::{AuthlyX, Error};
#[tokio::main]
async fn main() -> Result<(), Error> {
let app = AuthlyX::new("YOUR_APP_KEY", "1.0.0").await?;
let started = app.init().await?;
println!("{}", started.message);
app.close().await;
Ok(())
}

Callback

let handle = app.initWith(|result| match result {
Ok(started) => println!("{}", started.message),
Err(error) => println!("{}", error.message),
});

This starts the call on a Tokio task and returns a JoinHandle straight away. The callback receives the full Result on that task. Callback forms exist for initWith, initializeWith, licenseLoginWith, getVariableWith and getScriptWith. They must be called from inside a Tokio runtime.

Blocking

If the rest of your program is not async, make a runtime once and wait on each call:

fn main() -> Result<(), Box<dyn std::error::Error>> {
let runtime = tokio::runtime::Runtime::new()?;
let app = runtime.block_on(AuthlyX::new("YOUR_APP_KEY", "1.0.0"))?;
let started = runtime.block_on(app.init())?;
println!("{}", started.message);
Ok(())
}

Keep the runtime alive for as long as you use the client, because the heartbeat runs on it. Every .await example below works the same with runtime.block_on(...) around the call.

Start the SDK

Call init once, before signing in. initialize is the same method with a longer name.

let started = app.init().await?;
if !started.ok() {
println!("{}", started.message);
return Ok(());
}

For the usual problems init returns Ok with success false, so ? only stops on unusual failures such as a reply that failed verification:

Codeok()What happened
APP_INITIALIZEDtrueConnected. Continue to sign-in.
OFFLINE_MODEtrueNo internet, but this PC has saved offline access. See Offline access.
NETWORK_...falseNo internet and nothing saved. Ask the user to try again.
UPDATE_REQUIREDfalseThis version is older than the one in your dashboard. The SDK has already shown an update box.
VERSION_MISMATCHfalseThis version is newer than the dashboard version and is not allowed.
APP_DISABLEDfalseYou paused the app in the dashboard.

Sign in

app.licenseLogin("YOUR_LICENSE_KEY").await?;
app.login("YOUR_USERNAME", "YOUR_PASSWORD").await?;
app.deviceLogin().await?;

licenseLogin takes a license key, login takes a username and password, and deviceLogin signs in the current Windows user with no form. Device login only works for devices you approved first; see Device login.

When AuthlyX refuses a sign-in, the call returns Err(Error). Using ? passes it up; to show it instead, match on it:

match app.licenseLogin(&license_key).await {
Ok(_) => println!("Welcome"),
Err(error) => println!("{}", error.message),
}

error.message is text you can show to the user; printing the error with {} puts the code in front of it. error.code is a fixed code for your own checks, such as INVALID_CREDENTIALS, LICENSE_NOT_FOUND, LICENSE_EXPIRED, LICENSE_BANNED, DEVICE_NOT_ALLOWED or DEVICE_LIMIT_REACHED. error.kind says what sort of problem it was:

error.kindMeaningWhat to do
serverAuthlyX answered and said noShow the message
networkNo answer: no internet, firewall, timeoutAsk the user to retry. Do not treat it as a ban.
securityA reply failed verificationDo not unlock anything
storageThe SDK could not read or save its protected filesUsually a permissions problem
cancelledThe client was closedNothing

All codes are on the Errors page.

With a callback:

app.licenseLoginWith(license_key.clone(), |result| match result {
Ok(_) => println!("Welcome"),
Err(error) => println!("{}", error.message),
});

A sign-in function you can reuse:

async fn sign_in(app: &AuthlyX, license_key: &str) -> Result<(), String> {
app.licenseLogin(license_key)
.await
.map(|_| ())
.map_err(|error| error.message)
}

Create an account, change the password, add time

app.registerUser("YOUR_USERNAME", "YOUR_PASSWORD", "YOUR_LICENSE_KEY").await?;
app.changePassword("CURRENT_PASSWORD", "NEW_PASSWORD").await?;
app.redeemLicense("ANOTHER_LICENSE_KEY").await?;

registerUser creates a user account and signs it in. The other two need a signed-in user.

Read the account

After sign-in, userData() returns a copy of the account details as a serde_json::Value:

let user = app.userData();
let username = user["Username"].as_str().unwrap_or("");
let plan = user["Plan"].as_str().unwrap_or("");
let device_limit = user["DeviceLimit"].as_u64().unwrap_or(0);
println!("{username} {plan} {device_limit}");

Indexing a missing key gives Value::Null instead of panicking, so unwrap_or covers fields that are not there.

KeyExampleRead with
Usernamemayaas_str(), only set for username and password accounts
LicenseKeyMAYA-4R8P-2N6K-9Q3Was_str()
Emailmaya@example.comas_str()
PlanPlusas_str()
ExpiryDate2027-04-30T23:59:59.000Zas_str(), None for lifetime access
SIDS-1-5-21-...as_str()
DeviceLimit3as_u64()
Country, IpAddressNGas_str()
typelicenseas_str(): user, license or device
registeredAt, lastLogin2026-08-12T14:22:10.000Zas_str()
features["aim", "esp"]as_array()
featureValues, metadata{"fov": 90}as_object() or ["name"]

Before sign-in and after sign-out it is an empty object. Because it is a copy, call userData() again when you want the latest values.

Functions that return text, numbers and yes/no

fn expiry_text(app: &AuthlyX) -> String {
match app.userData()["ExpiryDate"].as_str() {
Some(expiry) if expiry.len() >= 10 => expiry[..10].replace('-', "/"),
_ => "Lifetime".to_string(),
}
}
fn days_left(app: &AuthlyX) -> i64 {
let user = app.userData();
let Some(expiry) = user["ExpiryDate"].as_str() else { return 0 };
let Ok(ends) = chrono::DateTime::parse_from_rfc3339(expiry) else { return 0 };
let seconds = (ends.with_timezone(&chrono::Utc) - chrono::Utc::now()).num_seconds();
if seconds <= 0 { 0 } else { (seconds + 86399) / 86400 }
}
fn build_top_line(app: &AuthlyX) -> String {
let user = app.userData();
let license = user["LicenseKey"].as_str().unwrap_or("");
if license.is_empty() {
return " License: Null".to_string();
}
format!(" License: {license} | Expiry: {}", expiry_text(app))
}
fn remaining_days(app: &AuthlyX) -> String {
let user = app.userData();
if user["Plan"].as_str().unwrap_or("").is_empty() {
return "N/A".to_string();
}
if user["ExpiryDate"].is_null() {
return "Lifetime".to_string();
}
format!("{}D", days_left(app))
}
fn is_premium(app: &AuthlyX) -> bool {
app.userData()["Plan"] == "Premium"
}

days_left rounds up, so one hour left counts as 1 day.

Features and metadata

Features come from the plan and the account. Some are on/off, some carry a value such as "high" or 90. Metadata is extra information attached to accounts. See Features and metadata.

Read them from the account

These do not contact AuthlyX:

use serde_json::Value;
fn has_feature(user: &Value, name: &str) -> bool {
user["features"]
.as_array()
.map_or(false, |list| list.iter().any(|item| item == name))
}
fn feature(user: &Value, name: &str, fallback: &str) -> String {
match &user["featureValues"][name] {
Value::Null => fallback.to_string(),
Value::String(text) => text.clone(),
other => other.to_string(),
}
}
fn feature_int(user: &Value, name: &str, fallback: i64) -> i64 {
feature(user, name, "")
.parse::<f64>()
.map(|number| number as i64)
.unwrap_or(fallback)
}
fn feature_bool(user: &Value, name: &str, fallback: bool) -> bool {
match feature(user, name, "").to_lowercase().as_str() {
"true" | "1" | "yes" | "on" => true,
"false" | "0" | "no" | "off" => false,
_ => fallback,
}
}
let user = app.userData();
let aim = has_feature(&user, "aim");
let fov = feature_int(&user, "fov", 90);
let rainbow = feature_bool(&user, "rainbow", false);
let discord = user["metadata"]["discord"].as_str().unwrap_or("");

The values refresh on every heartbeat, so dashboard changes show up without signing in again. For metadata helpers, copy the feature ones with "metadata" in place of "featureValues".

Ask AuthlyX directly

let all = app.getFeatures().await?;
println!("{}", all.data["features"]);
let quality = app.getFeature("quality").await?;
println!("{}", quality.data["value"]);
let aim = app.checkFeature("aim").await?;
let enabled = aim.data["enabled"].as_bool().unwrap_or(false);
let everything = app.getAllMetadata().await?;
let discord = app.getMetadataValue("discord").await?;
let vip = app.checkMetadata("vip").await?;
println!("{enabled} {} {} {}", everything.data["metadata"], discord.data["value"], vip.data["enabled"]);

In Rust, getMetadata() returns all metadata and getMetadataValue(key) returns one key. To turn data into your own struct, derive Deserialize and call response.decode::<YourType>().

Save metadata

use serde_json::json;
app.setMetadata("discord", json!("maya#1234")).await?;
app.setMetadata("level", json!(5)).await?;
app.setMetadata("vip", json!(true)).await?;

Only keys you allowed for SDK writes in the dashboard can be changed.

Cloud variables

let motd = app.getVariable("motd").await?;
println!("{}", motd.data["value"].as_str().unwrap_or(""));
app.getVariableWith("motd".to_string(), |result| {
if let Ok(motd) = result {
println!("{}", motd.data["value"]);
}
});
app.updateVariable("last_build", "1.4.2").await?;

See Cloud variables.

Scripts

let script = app.getScript("startup", None).await?;
let content = script.data["content"].as_str().unwrap_or("");
let older = app.getScript("startup", Some(3)).await?;

The second value is a revision number, or None for the newest. getScriptWith(name, revision, callback) is the callback form. The SDK checks the script’s signature before returning it. It does not run the script. See Scripts.

Logs and webhooks

app.log("Opened the settings page").await?;
app.sendWebhook("purchase.clicked", serde_json::json!({"item": "skin_42", "price": 4.99})).await?;

log writes a line to your app’s logs in the dashboard. sendWebhook sends an event to a webhook you set up in the dashboard; the second value is any JSON value.

Staying signed in

After sign-in the SDK checks in with AuthlyX in the background (a heartbeat), by default about every 10 minutes, and refreshes features and metadata each time. If you ban, pause or expire the account, the next heartbeat ends the session.

if !app.hasAccess().await {
println!("Please sign in");
}

To be told when the session ends or the connection changes, subscribe to events:

let mut events = app.subscribe();
tokio::spawn(async move {
while let Ok(event) = events.recv().await {
match event {
Event::SessionInvalidated(error) => {
println!("Signed out: {}", error.message);
std::process::exit(0);
}
Event::Connection(state) => println!("Connection: {state}"),
}
}
});

Event::Connection carries online, disconnected or untrusted. To check right away, call app.checkSession().await; app.onResume().await does the same and is meant for when your app wakes from sleep. To run the heartbeat yourself, build the options with .withHeartbeat("manual")? and call checkSession from your own tokio::time::interval. More in Sessions and heartbeats.

Offline access

app.licenseLogin(&license_key).await?;
app.saveOfflineAccess().await?;

Later, without internet, init returns OFFLINE_MODE with ok() true, and the user signs in with the same license key or username and password. The SDK checks them against the saved permit and the sign-in succeeds with the code OFFLINE_ACCESS. app.hasOfflineAccess().await tells you whether this PC has a valid saved permit. Signing out deletes it. See Offline access.

Updates

When this version is not allowed, init fails with UPDATE_REQUIRED or VERSION_MISMATCH and the SDK shows a message box with the new version, release notes and a button to open your download page. To show your own window, set options.update_prompt = false and read the details:

let started = app.init().await?;
if started.code == "UPDATE_REQUIRED" || started.code == "VERSION_MISMATCH" {
let update = &started.data["update"];
println!("{} {} {} {}", started.message, update["version"], update["url"], update["notes"]);
}

See Automatic updates.

Sign out and shut down

app.logout().await?;
app.close().await;

logout ends the session, clears the account details and deletes saved offline access on this PC. close stops the heartbeat. A closed client cannot be used again.

Tasks and threads

AuthlyX is Clone, Send and Sync. To use it in another task, clone it first:

let worker = app.clone();
let task = tokio::spawn(async move {
worker.log("Background job finished").await
});
task.await.ok();

Calls on one client run one at a time, so starting many at once is safe but they wait for each other. In a GUI built with egui, iced or similar, run SDK calls on a Tokio task and send the result back to the UI with a channel, rather than calling block_on inside the UI loop.

Results and errors

Response has success, code, message, request_id and data (a serde_json::Value), plus ok(), failed() and decode::<T>().

Error has code, message, kind, status, request_id and data. It implements std::error::Error, so ? works in functions that return Box<dyn std::error::Error>.

Options

Start from AuthlyX::defaults(app_key, version)? and change what you need:

FieldDefaultWhat it does
update_prompttrueShow the built-in update boxes
request_budget8 secondsHow long one call may take, including retries
.withHeartbeat("manual")"server"Run session checks yourself
build_hash""This build’s hash, if you use Application hashes
storageProtected files in %LOCALAPPDATA%\AuthlyX\v3Any Arc<dyn ProtectedStore>
systemIdThe Windows user SIDRequired on Linux and macOS

Events are not options in Rust; use subscribe() as shown in Staying signed in.

A complete program

use authlyx_sdk_v3::{AuthlyX, Error};
use std::io::Write;
fn ask(label: &str) -> String {
print!("{label}: ");
std::io::stdout().flush().ok();
let mut line = String::new();
std::io::stdin().read_line(&mut line).ok();
line.trim().to_string()
}
#[tokio::main]
async fn main() -> Result<(), Error> {
let app = AuthlyX::new("YOUR_APP_KEY", "1.0.0").await?;
let started = app.init().await?;
if !started.ok() {
println!("{}", started.message);
return Ok(());
}
let license_key = ask("License key");
if let Err(error) = app.licenseLogin(&license_key).await {
println!("{}", error.message);
return Ok(());
}
let user = app.userData();
println!("Plan: {}", user["Plan"].as_str().unwrap_or(""));
println!("Expires: {}", user["ExpiryDate"].as_str().unwrap_or("Lifetime"));
ask("Press Enter to sign out");
app.logout().await.ok();
app.close().await;
Ok(())
}

Each method also has its own page with every language side by side under SDK methods.