ziti-sdk-c-nodejs
v1.3.7
Published
Node.js wrapper for OpenZiti C SDK
Maintainers
Readme
Ziti SDK C - Node.js Wrapper
Node.js wrapper for the OpenZiti C SDK, allowing you to use OpenZiti's zero-trust networking capabilities in Node.js applications.
Features
- Full access to OpenZiti C SDK functionality
- High-level JavaScript API for easy integration
- Support for both client and server operations
- Socket-based communication over Ziti services
- Automatic resource management
- NEW: Load context from JSON data (not just files)
- NEW: Automatic detection of file vs JSON data
- NEW: Support for environment variables, secrets managers, databases
Prerequisites
- Node.js 14+
- Windows: Windows 10/11 with Visual Studio Build Tools
- Linux: GCC/Clang with build essentials
- macOS: Xcode Command Line Tools
- Compiled ziti-sdk-c library for your platform
Installation
From npm (Recommended)
npm install ziti-sdk-c-nodejsThe package includes all necessary SDK libraries and will automatically copy the required DLLs during installation.
From Source
Windows
# Clone this repository
git clone <your-repo-url>
cd ziti-sdk-c-nodejs
# Install dependencies and build (DLL will be copied automatically)
npm install
npm run buildNote: The ziti.dll file is automatically copied to the project root during installation.
Linux
# Clone this repository
git clone <your-repo-url>
cd ziti-sdk-c-nodejs
# Install dependencies and build (libraries will be copied automatically)
npm install
npm run buildNote: The libziti.so and libziti.a files are automatically copied to the project root during installation.
macOS
# Clone this repository
git clone <your-repo-url>
cd ziti-sdk-c-nodejs
# Install dependencies and build (libraries will be copied automatically)
npm install
npm run buildNote: The libziti.dylib and libziti.a files are automatically copied to the project root during installation.
Usage
Basic Client Example
const { ZitiClient } = require('ziti-sdk-c-nodejs');
async function main() {
// Opcja A: Z pliku
const client = new ZitiClient('./identity.json');
// Opcja B: Z danych JSON (nowa funkcjonalność!)
const client2 = new ZitiClient('{"ztAPI": "https://controller:8441", "id": {...}}');
try {
// Send data to a service
const response = client.send('my-secure-service', 'Hello World!');
console.log('Response:', response.toString());
} catch (error) {
console.error('Error:', error.message);
} finally {
client.close();
}
}
main();Basic Server Example
const { ZitiServer } = require('ziti-sdk-c-nodejs');
async function main() {
// Opcja A: Z pliku
const server = new ZitiServer('./identity.json', 'my-secure-service');
// Opcja B: Z danych JSON
const server2 = new ZitiServer('{"ztAPI": "https://controller:8441", "id": {...}}', 'my-secure-service');
try {
server.start();
console.log('Server started');
while (true) {
const { socket, caller } = server.accept();
console.log(`Connection from: ${caller}`);
// Handle the connection
const data = server.sdk.read(socket, 1024);
server.sdk.write(socket, 'Hello from server!');
server.sdk.close(socket);
}
} catch (error) {
console.error('Server error:', error.message);
} finally {
server.close();
}
}
main();Load Context from Data (NEW!)
You can now load Ziti context directly from JSON data instead of files:
const { ZitiSDK } = require('ziti-sdk-c-nodejs');
async function main() {
const sdk = new ZitiSDK();
await sdk.init();
// Load from JSON data
const identityData = '{"ztAPI": "https://controller:8441", "id": {...}}';
await sdk.loadContextFromData(identityData);
// Or from environment variable
const identityFromEnv = process.env.ZITI_IDENTITY_DATA;
await sdk.loadContextFromData(identityFromEnv);
// Or from secrets manager
const identityFromSecrets = await fetchFromSecretsManager();
await sdk.loadContextFromData(identityFromSecrets);
}
main();Automatic Detection
Classes automatically detect whether you're passing a file path or JSON data:
// Automatically detected as file
const client1 = new ZitiClient('./identity.json');
// Automatically detected as JSON
const client2 = new ZitiClient('{"ztAPI": "https://controller:8441", "id": {...}}');See Load from Data Guide for more details.
Advanced Usage with Direct SDK Access
const { ZitiSDK, LOG_LEVELS } = require('ziti-sdk-c-nodejs');
async function advancedExample() {
const sdk = new ZitiSDK();
try {
// Initialize the SDK
sdk.init();
// Enable detailed logging for debugging
sdk.setLogLevel(LOG_LEVELS.DEBUG);
// Load identity context
sdk.loadContext('./identity.json');
// Create a socket
const socket = sdk.socket();
// Connect to a service
const error = sdk.connect(socket, 'my-service', 'terminator1');
if (error !== 0) {
throw new Error(`Connection failed: ${error}`);
}
// Send data
const data = Buffer.from('Hello from Node.js!');
const bytesWritten = sdk.write(socket, data);
console.log(`Sent ${bytesWritten} bytes`);
// Read response
const response = sdk.read(socket, 1024);
console.log('Response:', response.toString());
// Clean up
sdk.close(socket);
} catch (error) {
console.error('Error:', error.message);
} finally {
sdk.shutdown();
}
}
advancedExample();Logging
The wrapper provides access to OpenZiti's built-in logging system for debugging and monitoring.
Log Levels
const { LOG_LEVELS } = require('ziti-sdk-c-nodejs');
// Available log levels:
LOG_LEVELS.NONE // 0 - No logging
LOG_LEVELS.ERROR // 1 - Error messages only
LOG_LEVELS.WARN // 2 - Warning and error messages
LOG_LEVELS.INFO // 3 - Info, warning, and error messages
LOG_LEVELS.DEBUG // 4 - Debug, info, warning, and error messages
LOG_LEVELS.VERBOSE // 5 - Verbose debug information
LOG_LEVELS.TRACE // 6 - Maximum verbosity (all messages)Setting Log Levels
const { ZitiSDK, LOG_LEVELS } = require('ziti-sdk-c-nodejs');
const sdk = new ZitiSDK();
sdk.init();
// Set log level by number
sdk.setLogLevel(LOG_LEVELS.DEBUG);
// Set log level by label
sdk.setLogLevelByLabel('DEBUG');
// Get current log level
const currentLevel = sdk.getLogLevelLabel();
console.log(`Current log level: ${currentLevel}`);Logging Examples
// Enable maximum verbosity for debugging
sdk.setLogLevel(LOG_LEVELS.TRACE);
// Enable debug logging for development
sdk.setLogLevel(LOG_LEVELS.DEBUG);
// Normal operation with info logging
sdk.setLogLevel(LOG_LEVELS.INFO);
// Only show errors
sdk.setLogLevel(LOG_LEVELS.ERROR);Environment Variable
You can also set the log level using the ZITI_LOG environment variable:
export ZITI_LOG=DEBUG
node your-app.jsNative Logging Callbacks
For applications like Electron where you need to capture OpenZiti logs in JavaScript, you can use custom logging callbacks.
Basic Usage
const { ZitiSDK, LOG_LEVELS } = require('ziti-sdk-c-nodejs');
const sdk = new ZitiSDK();
sdk.init();
// Set up logging callback
sdk.setLogCallback((level, message) => {
const levelNames = ['NONE', 'ERROR', 'WARN', 'INFO', 'DEBUG', 'VERBOSE', 'TRACE'];
const levelName = levelNames[level] || 'UNKNOWN';
console.log(`[Ziti ${levelName}] ${message}`);
});
// Enable native logs
sdk.enableNativeLogs(true);
sdk.setLogLevel(LOG_LEVELS.DEBUG);Configuration Object
You can also pass a configuration object to ZitiClient and ZitiServer:
const { ZitiClient } = require('ziti-sdk-c-nodejs');
const client = new ZitiClient({
identity: './identity.json',
logCallback: (level, message) => {
console.log(`[Ziti ${level}] ${message}`);
},
enableNativeLogs: true
});File Logging
const sdk = new ZitiSDK();
sdk.init();
// Set up file logging
sdk.setLogFile('./ziti-logs.txt');
sdk.enableNativeLogs(true);Electron Integration
const { ZitiClient } = require('ziti-sdk-c-nodejs');
const client = new ZitiClient({
identity: './identity.json',
logCallback: (level, message) => {
// Route to Electron's logging system
switch (level) {
case 1: // ERROR
console.error(`[Ziti] ${message}`);
break;
case 2: // WARN
console.warn(`[Ziti] ${message}`);
break;
case 3: // INFO
console.log(`[Ziti] ${message}`);
break;
default:
console.log(`[Ziti] ${message}`);
}
},
enableNativeLogs: true
});API Reference
ZitiSDK
The main SDK class providing direct access to OpenZiti functionality.
Methods
init()- Initialize the Ziti SDKloadContext(identityFile)- Load a Ziti identity from fileloadContextFromData(identityData)- Load a Ziti identity from JSON datasocket()- Create a new socketconnect(socket, service, terminator)- Connect to a servicebind(socket, service, terminator)- Bind to a servicelisten(socket, backlog)- Listen for connectionsaccept(socket)- Accept a connectionwrite(socket, data)- Write data to socketread(socket, size)- Read data from socketclose(socket)- Close a socketshutdown()- Shutdown the SDKsetLogLevel(level, marker)- Set the log level (0-6)setLogLevelByLabel(level)- Set the log level by label ('NONE', 'ERROR', 'WARN', 'INFO', 'DEBUG', 'VERBOSE', 'TRACE')getLogLevelLabel()- Get the current log level labelsetLogCallback(callback)- Set a custom log callback functionsetLogFile(logFile)- Set a log file for writing logsenableNativeLogs(enable)- Enable or disable native OpenZiti logging
ZitiClient
High-level client class for easy service communication.
Constructor
new ZitiClient(identityFileOrConfig)- Create a client with identity file or configuration object
Methods
connect(service, terminator)- Connect to a servicesend(service, data, terminator)- Send data and get responseclose()- Close the client
ZitiServer
High-level server class for hosting services.
Constructor
new ZitiServer(identityFileOrConfig, service, terminator)- Create a server with identity file or configuration object
Methods
start(backlog)- Start the serveraccept()- Accept a connectionstop()- Stop the serverclose()- Close the server
Cross-Platform Support
This wrapper supports Windows, Linux, and macOS. The JavaScript API is identical across all platforms.
Supported Platforms
| Platform | Status | Libraries | Auto-Install |
|----------|--------|-----------|--------------|
| Windows | ✅ Working | ziti.dll | ✅ Yes |
| Linux | ✅ Working | libziti.so, libziti.a | ✅ Yes |
| macOS | ✅ Working | libziti.dylib, libziti.a | ✅ Yes |
Testing Cross-Platform
npm run test:cross-platformFor detailed cross-platform setup instructions, see Cross-Platform Support.
Building from Source
Windows
- Install Visual Studio Build Tools
- Install Python 3.x
- Copy
ziti.dllto project directory - Run:
npm run buildLinux
- Install build essentials:
sudo apt-get install build-essential - The
ziti-sdk-1.7.8-Linux-x86_64directory is already included - Run:
npm run buildmacOS
- Install Xcode Command Line Tools
- The
ziti-sdk-1.7.8-Darwin-arm64directory is already included - Run:
npm run buildTroubleshooting
If you encounter build issues:
- Windows: Make sure
ziti.dllis in the current directory - Linux: Check
LD_LIBRARY_PATHor copylibziti.soto current directory - macOS: Check
DYLD_LIBRARY_PATHor copylibziti.dylibto current directory - Ensure you have the required build tools installed for your platform
Testing
Run the test suite:
npm testExamples
See the examples/ directory for more detailed examples:
examples/client.js- Client usage examplesexamples/server.js- Server usage examplesexamples/logging-example.js- Logging configuration and usage examples
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
License
Apache 2.0 - See LICENSE file for details.
Support
For issues and questions:
- Check the OpenZiti documentation
- Open an issue on GitHub
- Join the OpenZiti community
