zero-trust-sdk
v0.1.2
Published
JavaScript/TypeScript SDK for Zero Trust Blockchain Database - Secure, programmable access to zero-trust data storage
Maintainers
Readme
Zero Trust JavaScript/TypeScript SDK
JavaScript/TypeScript SDK for Zero Trust Blockchain Database - Secure, programmable access to zero-trust data storage.
A powerful client library for the Zero Trust Blockchain Database System, where user authentication/management is handled by traditional PostgreSQL, while application data lives entirely on-chain. Provides immutable, auditable, and verifiable data storage with familiar SQL interfaces.
Installation
npm install zero-trust-sdkQuick Start
Basic Usage
import { ZeroTrustClient, Config } from 'zero-trust-sdk';
// Initialize client
const client = await ZeroTrustClient.create({
apiUrl: 'http://localhost:3000',
apiKey: 'your-api-key'
});
// Authenticate
await client.auth().login('username', 'password');
// Create a database
const db = await client.databases().create('my-app-db');
// Execute a query
const results = await client.databases()
.query('my-app-db')
.execute('SELECT * FROM users');
console.log('Query results:', results.data);Configuration
You can configure the client in several ways:
Environment Variables
ZERO_TRUST_API_URL=http://localhost:3000
ZERO_TRUST_API_KEY=your-api-keyConfiguration Object
const config = new Config({
apiUrl: 'http://localhost:3000',
apiKey: 'your-api-key',
timeout: 30000,
retryAttempts: 3
});
const client = await ZeroTrustClient.create(config);Configuration File
Create a zero-trust.config.json file:
{
"apiUrl": "http://localhost:3000",
"apiKey": "your-api-key",
"timeout": 30000,
"retryAttempts": 3
}Authentication
Traditional Login
await client.auth().login('username', 'password');Web3 Wallet Authentication
await client.auth().walletAuth('0x...', 'signature');API Key Authentication
// API key is automatically used if provided in config
const client = await ZeroTrustClient.create({
apiUrl: 'http://localhost:3000',
apiKey: 'your-api-key'
});Database Operations
Creating Databases
const database = await client.databases().create('my-database');
console.log('Database created:', database.name);Listing Databases
const databases = await client.databases().list();
console.log('Available databases:', databases);Deleting Databases
await client.databases().delete('my-database');Table Operations
Creating Tables
await client.databases().createTable('my-database', 'users', [
{ name: 'id', type: 'SERIAL PRIMARY KEY' },
{ name: 'name', type: 'VARCHAR(100)' },
{ name: 'email', type: 'VARCHAR(255) UNIQUE' },
{ name: 'created_at', type: 'TIMESTAMP DEFAULT CURRENT_TIMESTAMP' }
]);Listing Tables
const tables = await client.databases().listTables('my-database');
console.log('Tables:', tables);Getting Table Schema
const schema = await client.databases().getTableSchema('my-database', 'users');
console.log('Table schema:', schema);Query Operations
Simple Queries
// Select data
const users = await client.databases()
.query('my-database')
.execute('SELECT * FROM users WHERE active = true');
// Insert data
await client.databases()
.query('my-database')
.execute('INSERT INTO users (name, email) VALUES ($1, $2)', ['John Doe', '[email protected]']);
// Update data
await client.databases()
.query('my-database')
.execute('UPDATE users SET name = $1 WHERE id = $2', ['Jane Doe', 1]);
// Delete data
await client.databases()
.query('my-database')
.execute('DELETE FROM users WHERE id = $1', [1]);Query Builder
const queryBuilder = client.databases().query('my-database');
// Chaining methods
const results = await queryBuilder
.select(['name', 'email'])
.from('users')
.where('active = true')
.orderBy('created_at DESC')
.limit(10)
.execute();Transactions
const transaction = await client.databases().beginTransaction('my-database');
try {
await transaction.execute('INSERT INTO users (name, email) VALUES ($1, $2)', ['User 1', '[email protected]']);
await transaction.execute('INSERT INTO users (name, email) VALUES ($1, $2)', ['User 2', '[email protected]']);
await transaction.commit();
console.log('Transaction committed successfully');
} catch (error) {
await transaction.rollback();
console.error('Transaction rolled back:', error);
}Data Migration
CSV Import
// Import from file
const file = new File([csvContent], 'users.csv', { type: 'text/csv' });
const migration = await client.migration()
.importCsv(file)
.toDatabase('my-database')
.toTable('users')
.withDelimiter(',')
.withHeaders(true)
.setBatchSize(1000)
.execute();
console.log('Migration status:', migration);JSON Import
const jsonFile = new File([jsonContent], 'users.json', { type: 'application/json' });
const migration = await client.migration()
.importJson(jsonFile)
.toDatabase('my-database')
.toTable('users')
.setBatchSize(500)
.execute();Data Export
// Export to CSV
const csvData = await client.migration()
.exportCsv()
.fromDatabase('my-database')
.fromTable('users')
.withHeaders(true)
.execute();
// Export to JSON
const jsonData = await client.migration()
.exportJson()
.fromDatabase('my-database')
.fromQuery('SELECT * FROM users WHERE created_at > $1')
.setPretty(true)
.execute();Data Synchronization
Sync from External Database
const syncConfig = await client.sync()
.fromDatabase({
host: 'external-db.example.com',
port: 5432,
database: 'source_db',
username: 'user',
password: 'password'
})
.toDatabase('my-database')
.mapTable('external_users', 'users')
.schedule('0 2 * * *') // Daily at 2 AM
.execute();Sync from API
const apiSync = await client.sync()
.fromApi('https://api.example.com/users')
.toDatabase('my-database')
.toTable('users')
.withHeaders({ 'Authorization': 'Bearer token' })
.transformData((data) => {
// Transform API response to match your table schema
return data.map(user => ({
name: user.fullName,
email: user.emailAddress,
active: user.status === 'active'
}));
})
.execute();Sync from CSV
const csvSync = await client.sync()
.fromCsv('https://example.com/data.csv')
.toDatabase('my-database')
.toTable('users')
.withDelimiter(',')
.withHeaders(true)
.schedule('0 */6 * * *') // Every 6 hours
.execute();Error Handling
import { ZeroTrustError, AuthError, DatabaseError } from 'zero-trust-sdk';
try {
await client.auth().login('user', 'wrong-password');
} catch (error) {
if (error instanceof AuthError) {
console.error('Authentication failed:', error.message);
} else if (error instanceof DatabaseError) {
console.error('Database error:', error.message);
} else if (error instanceof ZeroTrustError) {
console.error('SDK error:', error.message);
} else {
console.error('Unknown error:', error);
}
}Configuration Options
interface ZeroTrustConfig {
apiUrl: string; // Required: API endpoint URL
apiKey?: string; // Optional: API key for authentication
timeout?: number; // Optional: Request timeout in milliseconds (default: 30000)
retryAttempts?: number; // Optional: Number of retry attempts (default: 3)
retryDelay?: number; // Optional: Delay between retries in milliseconds (default: 1000)
headers?: Record<string, string>; // Optional: Custom headers
}TypeScript Support
This SDK is written in TypeScript and provides full type safety:
import {
ZeroTrustClient,
Config,
QueryResult,
Database,
Table,
User
} from 'zero-trust-sdk';
// Type-safe query results
const result: QueryResult<User[]> = await client.databases()
.query('my-database')
.execute('SELECT * FROM users');
// Access typed data
result.data.forEach((user: User) => {
console.log(`User: ${user.name} (${user.email})`);
});Browser Usage
The SDK works in both Node.js and browser environments:
<!DOCTYPE html>
<html>
<head>
<script type="module">
import { ZeroTrustClient } from 'https://unpkg.com/zero-trust-sdk@latest/dist/index.esm.js';
async function main() {
const client = await ZeroTrustClient.create({
apiUrl: 'http://localhost:3000'
});
// Use the client...
}
main();
</script>
</head>
<body>
<!-- Your app content -->
</body>
</html>Examples
Check out the /examples directory for complete usage examples:
- Basic CRUD operations
- Data migration workflows
- Synchronization setups
- Error handling patterns
- TypeScript usage examples
API Reference
ZeroTrustClient
ZeroTrustClient.create(config)- Create a new client instanceclient.auth()- Access authentication methodsclient.databases()- Access database operationsclient.migration()- Access data migration toolsclient.sync()- Access synchronization featuresclient.health()- Check API health status
AuthManager
auth().login(username, password)- Traditional loginauth().walletAuth(address, signature)- Web3 wallet authenticationauth().logout()- Logout current sessionauth().getUser()- Get current user information
DatabaseManager
databases().create(name)- Create a new databasedatabases().list()- List all databasesdatabases().delete(name)- Delete a databasedatabases().query(database)- Create a query builderdatabases().createTable(database, table, columns)- Create a tabledatabases().listTables(database)- List tables in a databasedatabases().getTableSchema(database, table)- Get table schema
Contributing
Please refer to the main Zero Trust project repository for contribution guidelines.
License
MIT License - see LICENSE file for details.
Support
- Documentation: https://docs.zerotrust.com
- Issues: GitHub Issues
- Email: [email protected]
