trasorio-sdk
v1.1.0
Published
Official Node.js SDK for Trasor.io trust infrastructure platform
Downloads
18
Maintainers
Readme
Trasor.io Node.js SDK
Official Node.js SDK for Trasor.io - Trust infrastructure for AI agent workflows.
Trasor.io provides secure, immutable audit trails for AI agents using blockchain-style verification. Perfect for teams building with Node.js, Express, NestJS, and other frameworks who need SOC 2 / ISO27001 compliance.
Features
- 🔐 Secure audit logging with automatic hash chaining
- 🚀 Developer-friendly - Get started in minutes
- 📊 Chain verification - Ensure data integrity
- 🔑 Simple authentication with API keys
- 📦 Zero dependencies - Uses native Node.js fetch
- 🛡️ TypeScript ready - Full type definitions included
- ⚡ Node.js 14+ compatible
Installation
npm install trasorio-sdkQuick Start
const { TrasorClient } = require('trasorio-sdk');
// Initialize client with your API key
const client = new TrasorClient('trasor_live_your_api_key');
// Log an AI agent event
async function logEvent() {
try {
const response = await client.logEvent({
agentName: 'data_processor',
action: 'process_customer_data',
inputs: { customerId: 'cust_123', dataType: 'profile' },
outputs: { status: 'processed', recordCount: 1 },
metadata: { processingTime: '1.2s' },
workflowId: 'workflow_456',
status: 'success'
});
console.log(`Audit log created: ${response.id}`);
console.log(`Hash: ${response.hash}`);
} catch (error) {
console.error('Error logging event:', error.message);
}
}
logEvent();API Reference
TrasorClient
Constructor
new TrasorClient(apiKey, options)Parameters:
apiKey(string): Your Trasor.io API key (format:trasor_live_*)options(Object, optional): Configuration optionsbaseUrl(string): Base URL for the API (default:https://api.trasor.io)timeout(number): Request timeout in milliseconds (default:30000)debug(boolean): Enable debug logging (default:false)
Example:
const client = new TrasorClient('trasor_live_abc123...', {
baseUrl: 'https://api.trasor.io',
timeout: 30000,
debug: process.env.NODE_ENV === 'development'
});logEvent(params)
Create a new audit log entry.
Parameters:
params(Object): Log event parametersagentName(string): Name/identifier of the AI agent or serviceaction(string): The action that was performedinputs(Object, optional): Input data/parameters for the actionoutputs(Object, optional): Output data/results from the actionmetadata(Object, optional): Additional metadata about the eventworkflowId(string, optional): Workflow or session identifierstatus(string, optional): Status of the action
Returns: Promise<Object> - The created audit log entry
Example:
const response = await client.logEvent({
agentName: 'email_agent',
action: 'send_notification',
inputs: { recipient: '[email protected]' },
outputs: { messageId: 'msg_123' },
status: 'success'
});getLogs(options)
Retrieve audit logs with pagination.
Parameters:
options(Object, optional): Query optionslimit(number): Number of logs to return (max 100, default: 50)offset(number): Number of logs to skip (default: 0)workflowId(string): Filter by workflow ID
Returns: Promise<Object> - Paginated list of audit logs
Example:
const logs = await client.getLogs({ limit: 20, offset: 0 });
for (const log of logs.logs) {
console.log(`Agent: ${log.agentId}, Action: ${log.action}`);
}verifyChain()
Verify the integrity of the audit log chain.
Returns: Promise<Object> - Verification results
Example:
const verification = await client.verifyChain();
console.log(`Chain integrity: ${verification.isValid}`);getStats()
Get account statistics and metrics.
Returns: Promise<Object> - Account statistics
Example:
const stats = await client.getStats();
console.log(`Total logs: ${stats.totalLogs}`);
console.log(`Chain integrity: ${stats.chainIntegrity}%`);Framework Examples
Express.js Integration
const express = require('express');
const { TrasorClient } = require('trasorio-sdk');
const app = express();
const trasor = new TrasorClient('trasor_live_your_api_key');
// Middleware to log API requests
app.use(async (req, res, next) => {
const startTime = Date.now();
res.on('finish', async () => {
try {
await trasor.logEvent({
agentName: 'express_server',
action: 'api_request',
inputs: {
method: req.method,
url: req.url,
userAgent: req.get('User-Agent')
},
outputs: {
statusCode: res.statusCode,
responseTime: `${Date.now() - startTime}ms`
},
metadata: {
framework: 'express',
ip: req.ip
},
status: res.statusCode < 400 ? 'success' : 'error'
});
} catch (error) {
console.error('Failed to log request:', error.message);
}
});
next();
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});NestJS Integration
import { Injectable, NestMiddleware } from '@nestjs/common';
import { TrasorClient } from 'trasorio-sdk';
@Injectable()
export class AuditMiddleware implements NestMiddleware {
private trasor = new TrasorClient('trasor_live_your_api_key');
async use(req: any, res: any, next: () => void) {
const startTime = Date.now();
res.on('finish', async () => {
try {
await this.trasor.logEvent({
agentName: 'nestjs_service',
action: 'api_request',
inputs: {
method: req.method,
route: req.route?.path,
params: req.params
},
outputs: {
statusCode: res.statusCode,
responseTime: `${Date.now() - startTime}ms`
},
metadata: {
framework: 'nestjs',
controller: req.route?.stack?.[0]?.name
},
status: res.statusCode < 400 ? 'success' : 'error'
});
} catch (error) {
console.error('Audit logging failed:', error.message);
}
});
next();
}
}Custom AI Agent Integration
const { TrasorClient } = require('trasorio-sdk');
class AIAgent {
constructor(name, apiKey) {
this.name = name;
this.trasor = new TrasorClient(apiKey);
}
async processTask(task) {
const workflowId = `workflow_${Date.now()}`;
try {
// Log task start
await this.trasor.logEvent({
agentName: this.name,
action: 'task_started',
inputs: { taskType: task.type, taskId: task.id },
workflowId,
status: 'started'
});
// Process the task
const result = await this.performTask(task);
// Log successful completion
await this.trasor.logEvent({
agentName: this.name,
action: 'task_completed',
inputs: { taskType: task.type, taskId: task.id },
outputs: { result, duration: result.processingTime },
workflowId,
status: 'success'
});
return result;
} catch (error) {
// Log failure
await this.trasor.logEvent({
agentName: this.name,
action: 'task_failed',
inputs: { taskType: task.type, taskId: task.id },
outputs: { error: error.message },
workflowId,
status: 'error'
});
throw error;
}
}
async performTask(task) {
// Your AI agent logic here
return { success: true, processingTime: '2.1s' };
}
}
// Usage
const agent = new AIAgent('data_processor', 'trasor_live_your_api_key');Error Handling
The SDK includes comprehensive error handling with specific error types:
const {
TrasorClient,
TrasorError,
AuthenticationError,
ValidationError,
APIError
} = require('trasorio-sdk');
const client = new TrasorClient('trasor_live_your_api_key');
try {
await client.logEvent({
agentName: 'test_agent',
action: 'test_action'
});
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Authentication failed:', error.message);
} else if (error instanceof ValidationError) {
console.error('Validation error:', error.message);
} else if (error instanceof APIError) {
console.error('API error:', error.message, 'Status:', error.statusCode);
} else if (error instanceof TrasorError) {
console.error('SDK error:', error.message);
} else {
console.error('Unexpected error:', error);
}
}Debug Mode
Enable debug logging to see detailed request/response information:
// Enable via constructor
const client = new TrasorClient('trasor_live_your_api_key', { debug: true });
// Or via environment variable
process.env.VERIFIK_DEBUG = 'true';
const client = new TrasorClient('trasor_live_your_api_key');Debug output includes:
- Request details (URL, headers, body)
- Response status and data
- Timing information
- Error details
TypeScript Support
The SDK includes TypeScript definitions:
import { TrasorClient, TrasorError } from 'trasorio-sdk';
interface LogParams {
agentName: string;
action: string;
inputs?: Record<string, any>;
outputs?: Record<string, any>;
metadata?: Record<string, any>;
workflowId?: string;
status?: string;
}
const client = new TrasorClient('trasor_live_your_api_key');
async function logEvent(params: LogParams): Promise<void> {
try {
const response = await client.logEvent(params);
console.log(`Log created: ${response.id}`);
} catch (error) {
if (error instanceof TrasorError) {
console.error('SDK error:', error.message);
}
}
}Getting Your API Key
- Sign up at trasor.io
- Go to your Settings page
- Generate a new API key
- Copy the key (format:
trasor_live_...)
Environment Variables
VERIFIK_DEBUG: Set to'true'to enable debug loggingVERIFIK_API_KEY: Default API key (can be overridden in constructor)VERIFIK_BASE_URL: Default base URL (can be overridden in constructor)
Contributing
- Fork the repository
- Create a feature branch:
git checkout -b feature-name - Make your changes and add tests
- Run the test suite:
npm test - Submit a pull request
Testing
# Run all tests
npm test
# Run unit tests only
npm run test:unit
# Run with debug output
VERIFIK_DEBUG=true npm testLicense
This project is licensed under the MIT License - see the LICENSE file for details.
Support
- 📧 Email: [email protected]
- 📖 Documentation: https://docs.trasor.io
- 🐛 Bug Reports: https://github.com/trasor/sdk/issues
- 💬 Community: https://discord.gg/trasor
Changelog
1.0.1 (2024-01-15)
- Migrated to scoped package
trasorio-sdk - Updated all documentation and examples
- Improved repository structure
1.0.0 (2024-01-14)
- Initial release
- Core audit logging functionality
- Chain verification support
- Full API coverage
- Zero dependencies
- Node.js 14+ support
