ziti-sdk-c-nodejs
Version:
Node.js wrapper for OpenZiti C SDK
518 lines (379 loc) • 13.9 kB
Markdown
# 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)
```bash
npm install ziti-sdk-c-nodejs
```
The package includes all necessary SDK libraries and will automatically copy the required DLLs during installation.
### From Source
#### Windows
```bash
# 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 build
```
**Note**: The `ziti.dll` file is automatically copied to the project root during installation.
#### Linux
```bash
# 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 build
```
**Note**: The `libziti.so` and `libziti.a` files are automatically copied to the project root during installation.
#### macOS
```bash
# 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 build
```
**Note**: The `libziti.dylib` and `libziti.a` files are automatically copied to the project root during installation.
## Usage
### Basic Client Example
```javascript
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
```javascript
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:
```javascript
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:
```javascript
// 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](docs/LOAD_FROM_DATA.md) for more details.
### Advanced Usage with Direct SDK Access
```javascript
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
```javascript
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
```javascript
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
```javascript
// 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:
```bash
export ZITI_LOG=DEBUG
node your-app.js
```
## Native Logging Callbacks
For applications like Electron where you need to capture OpenZiti logs in JavaScript, you can use custom logging callbacks.
### Basic Usage
```javascript
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`:
```javascript
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
```javascript
const sdk = new ZitiSDK();
sdk.init();
// Set up file logging
sdk.setLogFile('./ziti-logs.txt');
sdk.enableNativeLogs(true);
```
### Electron Integration
```javascript
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 SDK
- `loadContext(identityFile)` - Load a Ziti identity from file
- `loadContextFromData(identityData)` - Load a Ziti identity from JSON data
- `socket()` - Create a new socket
- `connect(socket, service, terminator)` - Connect to a service
- `bind(socket, service, terminator)` - Bind to a service
- `listen(socket, backlog)` - Listen for connections
- `accept(socket)` - Accept a connection
- `write(socket, data)` - Write data to socket
- `read(socket, size)` - Read data from socket
- `close(socket)` - Close a socket
- `shutdown()` - Shutdown the SDK
- `setLogLevel(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 label
- `setLogCallback(callback)` - Set a custom log callback function
- `setLogFile(logFile)` - Set a log file for writing logs
- `enableNativeLogs(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 service
- `send(service, data, terminator)` - Send data and get response
- `close()` - 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 server
- `accept()` - Accept a connection
- `stop()` - Stop the server
- `close()` - 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
```bash
npm run test:cross-platform
```
For detailed cross-platform setup instructions, see [Cross-Platform Support](docs/CROSS_PLATFORM.md).
## Building from Source
### Windows
1. Install Visual Studio Build Tools
2. Install Python 3.x
3. Copy `ziti.dll` to project directory
4. Run:
```bash
npm run build
```
### Linux
1. Install build essentials: `sudo apt-get install build-essential`
2. The `ziti-sdk-1.7.8-Linux-x86_64` directory is already included
3. Run:
```bash
npm run build
```
### macOS
1. Install Xcode Command Line Tools
2. The `ziti-sdk-1.7.8-Darwin-arm64` directory is already included
3. Run:
```bash
npm run build
```
### Troubleshooting
If you encounter build issues:
1. **Windows**: Make sure `ziti.dll` is in the current directory
2. **Linux**: Check `LD_LIBRARY_PATH` or copy `libziti.so` to current directory
3. **macOS**: Check `DYLD_LIBRARY_PATH` or copy `libziti.dylib` to current directory
4. Ensure you have the required build tools installed for your platform
## Testing
Run the test suite:
```bash
npm test
```
## Examples
See the `examples/` directory for more detailed examples:
- `examples/client.js` - Client usage examples
- `examples/server.js` - Server usage examples
- `examples/logging-example.js` - Logging configuration and usage examples
## Contributing
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request
## License
Apache 2.0 - See LICENSE file for details.
## Support
For issues and questions:
- Check the [OpenZiti documentation](https://openziti.io/docs)
- Open an issue on GitHub
- Join the OpenZiti community
## Related Links
- [OpenZiti C SDK](https://github.com/openziti/ziti-sdk-c)
- [OpenZiti Documentation](https://openziti.io/docs)
- [OpenZiti Community](https://openziti.io/community)