HomeDocumentation

SDK Reference

Everything you need to integrate keystroke biometrics into your application — from a single npm install to a full native C++ embedding.

Overview

TrueStroke SDK Reference

TrueStroke is a cross-platform C++17 behavioral biometric SDK that identifies users by their unconscious keystroke rhythm. It runs entirely on-device with sub-millisecond inference, detects account takeover the moment it happens, and never sends raw biometric data anywhere.

~140 KB
Library Size
< 1µs
Inference P50
Zero
Dependencies

The SDK provides three API surfaces: a C++ API for native integrations, a stable C ABI for cross-language FFI, and a TypeScript wrapper for browser usage via WASM.

Quick Start

Get up and running in minutes

Prerequisites

  • C++17 compiler (Clang 14+, GCC 10+, MSVC 2019+)
  • CMake 3.16+
  • Optional: Emscripten SDK for WASM builds
  • Optional: Node.js 18+ for TypeScript

Build the SDK

bash
cd sdk
mkdir build && cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
cmake --build . -j$(nproc)

Run Tests

bash
cd sdk/build
ctest --output-on-failure

# All 10 test suites pass:
# test_ring_buffer ......... Passed
# test_feature_extractor ... Passed
# test_isolation_forest .... Passed
# test_mahalanobis ......... Passed
# test_crypto .............. Passed
# test_liveness ............ Passed
# test_engine .............. Passed
# test_federated ........... Passed
# test_c_api ............... Passed
# test_differentiation ..... Passed

Build for WASM

bash
cd wasm
chmod +x build.sh
./build.sh
# Produces dist/truestroke.js and dist/truestroke.wasm

TypeScript / Browser API

@truestroke/core npm package

Installation

bash
npm install @truestroke/core
NoteThe WASM binary is bundled with the npm package. No additional setup required.

Basic Usage

typescript
import { TrueStroke } from '@truestroke/core';

const ts = await TrueStroke.init({ userId: 'user_123' });

// Attach to any input element (auto-captures keystrokes)
ts.attachTo(document.querySelector('#my-input'));

// Or feed events manually
document.addEventListener('keydown', (e) => ts.feedKeyDown(e.code, e.timeStamp));
document.addEventListener('keyup', (e) => ts.feedKeyUp(e.code, e.timeStamp));

// Listen for anomalies
ts.onAnomaly((event) => {
  console.log(`Imposter detected: confidence=${event.confidence}`);
  showReauthPrompt();
});

// Reactive listeners
ts.onConfidenceChange((c) => updateConfidenceUI(c));
ts.onStatusChange((s) => updateStatusBadge(s));

// Liveness detection
const liveness = ts.checkLiveness();
// { isLive, isReplay, entropy, jitterPower, wpm, dwellCV, score }

// Federated learning
const gradients = ts.exportGradients();
await fetch('/api/v1/gradients', { method: 'POST', body: gradients });

// Profile
ts.saveProfile();
ts.wipeProfile();  // GDPR-compliant erasure

ts.destroy();  // Cleanup

TrueStrokeConfig

PropertyTypeDescriptionDefault
userIdstringUnique user identifierrequired
windowSizenumberKeystrokes per feature window30
windowStridenumberStride between windows15
lockThresholdnumberConfidence below this triggers lock0.35
enrollMinKeystrokesnumberMin keystrokes for early scoring50
enrollFullKeystrokesnumberKeystrokes for full enrollment200
encryptProfilesbooleanEncrypt profiles with XChaCha20true
wasmUrlstringCustom path to .wasm fileauto

AnomalyEvent

PropertyTypeDescriptionDefault
confidencenumberCurrent confidence score [0.0, 1.0]
windowSizenumberNumber of keystrokes in scoring window
timestampnumberEvent timestamp in microseconds

LivenessResult

PropertyTypeDescriptionDefault
isLivebooleanWhether human typing is detected
isReplaybooleanWhether a replay attack is detected
entropynumberShannon entropy of timing distribution
jitterPowernumberGoertzel DFT jitter power
wpmnumberTyping speed in words per minute
dwellCVnumberCoefficient of variation of dwell times
scorenumberCombined liveness score

C++ API

Native integration via ts::Engine

cpp
#include <truestroke/truestroke.h>

// Create and initialise engine
ts::Engine engine;
ts::Config cfg;
cfg.lockThreshold = 0.35f;
cfg.enrollFullKeystrokes = 200;
engine.init(cfg);

// Begin enrollment
engine.enroll("user_123");

// Feed keystroke events (from platform hooks)
ts::KeyEvent ev;
ev.keyCode = 65;          // 'A'
ev.pressTime = 1709000000;  // microseconds
ev.releaseTime = 1709050000;
ev.pressure = 0.0f;
engine.feed(ev);

// Query state
float confidence = engine.getConfidence();  // 0.0 to 1.0
ts::Status status = engine.getStatus();     // ENROLLING | MONITORING | LOCKED

// Set anomaly callback
engine.onAnomaly([](const ts::AnomalyEvent& ae) {
    std::cerr << "Anomaly: confidence=" << ae.confidence << "\n";
});

// Liveness check
auto lr = engine.checkLiveness();
// lr.isLive, lr.entropy, lr.jitterPower, lr.wpm, lr.isReplay

// Profile management
engine.saveProfile();       // encrypted binary to disk
engine.wipeProfile();       // GDPR-compliant erasure

// Federated learning (optional)
auto gradients = engine.exportGradients();
engine.importGlobalUpdate(serverResponse.data(), serverResponse.size());

C API (FFI)

Stable ABI for cross-language integration

The C API enables integration from any language with C FFI support: Python, Go, Java JNI, Kotlin NDK, Swift, Rust, etc.

c
#include <truestroke/c_api.h>

ts_engine_t* engine = ts_engine_create();
ts_engine_init(engine);
ts_engine_enroll(engine, "user_123");

ts_key_event_t ev = {
  .key_code = 65,
  .press_time = t0,
  .release_time = t1,
  .pressure = 0.0f
};
ts_engine_feed(engine, &ev);

float confidence = ts_engine_get_confidence(engine);

// Anomaly callback
void on_anomaly(const ts_anomaly_event_t* event, void* userdata) {
  // Handle anomaly
}
ts_engine_on_anomaly(engine, on_anomaly, NULL);

// Cleanup
ts_engine_destroy(engine);

Federated Server API

Gradient aggregation with differential privacy

Endpoints

EndpointMethodDescription
/api/v1/gradientsPOSTSubmit gradient data (binary or base64 JSON)
/api/v1/modelGETDownload current global model (binary)
/api/v1/statusGETServer status, round info, privacy budget
/api/v1/healthGETHealth check

Build & Run

bash
cd server
mkdir build && cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
cmake --build . -j$(nproc)

# Run the server
./federated_server --port 8080 --min-clients 5 --epsilon 8.0

CLI Options

PropertyTypeDescriptionDefault
--portintHTTP port8080
--min-clientsintMinimum clients per round5
--max-roundsintMaximum training rounds100
--epsilonfloatDP epsilon budget8.0
--deltafloatDP delta parameter1e-5
--clip-normfloatL2 gradient clip norm1.0

Configuration

Engine tuning parameters

cpp
ts::Config cfg;
cfg.windowSize = 30;       // keystrokes per feature window
cfg.windowStride = 15;     // stride (50% overlap)
cfg.eifTrees = 100;        // forest size
cfg.eifSubsampleSize = 256; // sub-sample per tree
cfg.eifMaxDepth = 10;      // max tree depth
cfg.mahShrinkage = -1.0f;  // <0 = auto Ledoit-Wolf
cfg.mahDecay = 0.01f;      // exponential decay for drift
cfg.lockThreshold = 0.35f; // confidence below this = lock
cfg.hysteresisWindows = 3; // consecutive anomalous windows
cfg.enrollMinKeystrokes = 50;  // minimum keystrokes for early scoring
cfg.enrollFullKeystrokes = 200; // keystrokes for full enrollment
cfg.encryptProfiles = true; // XChaCha20-Poly1305 at rest
NoteConfiguration is set via engine.init(cfg) before enrollment begins. Re-initialising resets the engine state.

Privacy Architecture

Privacy-first by design

01
Zero data exfiltration

All inference runs on-device. No keystroke timing, feature vectors, or profile data leaves the device during normal operation.

02
Encrypted at rest

User profiles are encrypted with XChaCha20-Poly1305 before storage. ~800 MB/s throughput.

03
GDPR wipe() API

Complete erasure of all biometric data with a single API call.

04
Federated learning

Only differentially-private gradient updates (clipped + noised) are transmitted, never raw data.

05
Privacy budget tracking

Cumulative privacy loss (ε) tracked via Rényi DP composition across rounds.

Platform Support

PlatformBuild MethodStatus
macOS (ARM64)CMake nativeTested
macOS (x86_64)CMake nativeTested
Linux (x86_64/ARM)CMake nativeTested
WindowsCMake + MSVCTested
Browser (WASM)EmscriptenTested
AndroidNDK + CMakePlanned
iOSXcode + CMakePlanned