Skip to content

SDK Integration

The AuthNexus SDK is a C++ static library that provides a synchronous API for authenticating users, managing sessions, invoking cloud functions, and receiving push notifications over a secure mTLS TCP connection.

Overview

Key Characteristics

  • Static library -- links directly into your application binary.
  • Synchronous API -- all public methods block until completion.
  • Thread-safe -- all public methods are internally locked; safe to call from multiple threads.
  • Internal threads -- after connect(), the SDK manages 2--3 background threads:
    • Reader thread -- receives packets, routes to pending RPCs or push queue.
    • Notify thread -- dispatches push callbacks (user callbacks execute here).
    • Heartbeat thread (optional) -- sends periodic keepalives.

The single public header has no internal dependencies -- it requires only the C++ standard library:

cpp
#include <authnexus_sdk.h>

Configuration

File-Based Certificates

cpp
auth_nexus::sdk::SDKConfig config;
config.server_host = "node.example.com";
config.server_port = 8443;
config.app_id = 1;
config.app_secret = "your_app_secret";
config.device_id = "unique_device_identifier";

// mTLS certificates (file paths)
config.client_cert_path = "certs/client.crt";
config.client_key_path  = "certs/client.key";
config.ca_cert_path     = "certs/server_ca.pem";

// Trust policy (loaded from JSON or configured manually)
config.trust_policy.trust_config_path = "authnexus_trust.json";

Memory-Based Certificates

For applications that manage certificates in memory (e.g., embedded systems or encrypted storage), use CertificateLoader:

cpp
auto cert = auth_nexus::sdk::CertificateLoader::load_cert_from_file("client.crt");
auto key  = auth_nexus::sdk::CertificateLoader::load_cert_from_file("client.key");
auto ca   = auth_nexus::sdk::CertificateLoader::load_cert_from_file("server_ca.pem");

auto config = auth_nexus::sdk::CertificateLoader::create_memory_config(
    "node.example.com", 8443, 1, "app_secret",
    cert.value(), key.value(), ca.value()
);

Trust Policy

The trust policy adds defense-in-depth verification beyond CA chain validation. Configure SPKI pins (RFC 7469 style), required URI SANs on the server cert, and the OCSP signer CA bundle for staple verification. See TLS & PKI for details.

Connection Lifecycle

Connect

cpp
auth_nexus::sdk::Client client(config);

if (!client.connect()) {
    auto code = client.last_error_code();
    auto msg  = client.last_error();
    // Handle connection failure
}

connect() performs DNS resolution, TCP connection, TLS 1.3 handshake with mTLS, trust policy validation (pins, SANs, OCSP), and the application-level handshake.

Disconnect

cpp
client.disconnect();

Shuts down the socket, wakes all internal threads, and joins them. After disconnect, the client can reconnect by calling connect() again.

Authentication

Three login methods are available, all returning AuthResult with success, token, user_id, username, and expire_time:

cpp
// Password login
auto result = client.login("username", "password");

// Card key login (activates on first use)
auto result = client.card_key_login("ABCD-1234-EFGH-5678");

// Token resume (session recovery across restarts)
auto token = auth_nexus::sdk::token_from_hex(saved_hex);
auto result = client.token_login(token.value());

// Registration (creates account + session)
auto result = client.register_user("newuser", "password", "user@example.com");

Use token_to_hex() / token_from_hex() to persist and restore 32-byte session tokens.

Queries

cpp
auto info = client.get_user_info();
// info.user_info.username, .balance, .expire_at, .login_count, ...

auto status = client.get_account_status();
// status.account_status.balance, .service_plan, .features, ...

auto vars = client.get_variables({"key1", "key2"});
// vars.variables[0].key, .value, .description, ...

auto news = client.get_announcements();
// news.announcements[0].title, .content, .priority, ...

auto ver = client.get_version("stable");
// ver.version.version, .force_update, .update_url, .changelog, ...

Cloud Functions

Invoke server-side Lua cloud functions:

cpp
auto result = client.call_cloud_function(
    "calculate_discount",
    {{"item_id", "123"}, {"quantity", "5"}}
);

if (result.success) {
    // result.result           -- function return value (string)
    // result.execution_time_ms -- execution duration
    // result.server_time       -- server timestamp
}

Cloud functions execute in a sandboxed Lua 5.4 environment on the server. See Cloud Functions.

Heartbeat

cpp
// Enable automatic heartbeat (spawns a background thread)
client.enable_heartbeat(std::chrono::seconds(30));

// Or send manual heartbeats
auto hb = client.send_heartbeat();
// hb.session_expire_time, hb.service_expire_time

// Disable automatic heartbeat
client.disable_heartbeat();

Heartbeats maintain session liveness and provide the server with client presence data.

Push Notifications

The SDK receives server-initiated push notifications. Register callbacks before connecting:

cpp
// Catch-all callback (fires for any PushKind without a dedicated handler)
client.on_push([](const auth_nexus::sdk::PushNotification& notif) {
    // notif.kind, .title, .body, .payload_json
});

// Semantic callbacks (take priority over the catch-all)
client.on_force_logout([](const auth_nexus::sdk::PushNotification& notif) {
    // Server is forcing this session to log out
});

client.on_kill_process([](const auth_nexus::sdk::PushNotification& notif) {
    // Server requests process termination
});

client.on_announcement([](const auth_nexus::sdk::PushNotification& notif) {
    // New announcement from admin
});

client.on_config_updated([](const auth_nexus::sdk::PushNotification& notif) {
    // Application config has changed
});

WARNING

Push callbacks execute on the notify thread. Do not call client.disconnect() from within a callback -- it will deadlock. If you need to disconnect, post the action to another thread.

Push Kinds

KindValueDescription
Custom0Application-defined push
Announcement1System announcement
ForceLogout2Force session termination
KillProcess3Request process exit
ServiceExpiring4Service about to expire
BalanceChanged5Account balance update
ConfigUpdated6Configuration change
SecurityAlert7Security-related notification
Maintenance8Scheduled maintenance notice

Error Handling

Connection Errors

cpp
enum class ErrorCode : int32_t {
    None                          = 0,
    TrustPolicyFileNotFound       = 1101,
    TrustPolicyParseFailed        = 1102,
    TrustPolicyInvalid            = 1103,
    CaBundleMissing               = 1201,
    CaBundleLoadFailed            = 1202,
    ClientCertificateMissing      = 1301,
    ClientCertificateInvalid      = 1302,
    ClientPrivateKeyInvalid       = 1303,
    ClientCertificateKeyMismatch  = 1304,
    ResolveFailed                 = 1401,
    TcpConnectFailed              = 1402,
    TlsHandshakeFailed            = 1403,
    ServerTrustVerificationFailed = 1404,
    HandshakeFailed               = 1501,
    IoFailure                     = 1601,
    InternalError                 = 9001,
};

Result Pattern

Every operation returns a typed result with success, code, and message fields:

cpp
auto result = client.login("user", "pass");
if (!result.success) {
    std::cerr << "Login failed: " << result.message
              << " (code " << result.code << ")" << std::endl;
}

Complete Example

cpp
#include <authnexus_sdk.h>
#include <iostream>

int main() {
    auth_nexus::sdk::SDKConfig config;
    config.server_host     = "node.example.com";
    config.server_port     = 8443;
    config.app_id          = 1;
    config.app_secret      = "secret";
    config.device_id       = "my-device-001";
    config.client_cert_path = "certs/client.crt";
    config.client_key_path  = "certs/client.key";
    config.ca_cert_path     = "certs/server_ca.pem";

    auth_nexus::sdk::Client client(config);

    client.on_force_logout([](const auto& n) {
        std::cout << "Force logout: " << n.body << std::endl;
    });

    if (!client.connect()) {
        std::cerr << "Connect failed: " << client.last_error() << std::endl;
        return 1;
    }

    auto login = client.login("testuser", "testpass");
    if (!login.success) {
        std::cerr << "Login failed: " << login.message << std::endl;
        return 1;
    }

    std::cout << "Logged in as " << login.username
              << " (ID: " << login.user_id << ")" << std::endl;

    client.enable_heartbeat(std::chrono::seconds(30));

    auto cf = client.call_cloud_function("greet", {{"name", "World"}});
    if (cf.success) {
        std::cout << "Cloud function: " << cf.result << std::endl;
    }

    // ... application logic ...

    client.disconnect();
    return 0;
}

Build Integration

Link against the authnexus_sdk static library in your CMakeLists.txt:

cmake
target_link_libraries(your_app PRIVATE authnexus_sdk)

The SDK requires OpenSSL 3.x at link time for TLS operations.

Next Steps