UNPKG

trasorio-sdk

Version:

Official Node.js SDK for Trasor.io trust infrastructure platform

455 lines (359 loc) 11.8 kB
# Trasor.io Node.js SDK [![npm version](https://badge.fury.io/js/trasorio-sdk.svg)](https://www.npmjs.com/package/trasorio-sdk) [![npm downloads](https://img.shields.io/npm/dm/trasorio-sdk.svg)](https://www.npmjs.com/package/trasorio-sdk) [![Node.js Support](https://img.shields.io/node/v/trasorio-sdk.svg)](https://www.npmjs.com/package/trasorio-sdk) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) Official Node.js SDK for [Trasor.io](https://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 ```bash npm install trasorio-sdk ``` ## Quick Start ```javascript 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 ```javascript new TrasorClient(apiKey, options) ``` **Parameters:** - `apiKey` (string): Your Trasor.io API key (format: `trasor_live_*`) - `options` (Object, optional): Configuration options - `baseUrl` (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:** ```javascript 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 parameters - `agentName` (string): Name/identifier of the AI agent or service - `action` (string): The action that was performed - `inputs` (Object, optional): Input data/parameters for the action - `outputs` (Object, optional): Output data/results from the action - `metadata` (Object, optional): Additional metadata about the event - `workflowId` (string, optional): Workflow or session identifier - `status` (string, optional): Status of the action **Returns:** `Promise<Object>` - The created audit log entry **Example:** ```javascript const response = await client.logEvent({ agentName: 'email_agent', action: 'send_notification', inputs: { recipient: 'user@example.com' }, outputs: { messageId: 'msg_123' }, status: 'success' }); ``` #### getLogs(options) Retrieve audit logs with pagination. **Parameters:** - `options` (Object, optional): Query options - `limit` (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:** ```javascript 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:** ```javascript const verification = await client.verifyChain(); console.log(`Chain integrity: ${verification.isValid}`); ``` #### getStats() Get account statistics and metrics. **Returns:** `Promise<Object>` - Account statistics **Example:** ```javascript const stats = await client.getStats(); console.log(`Total logs: ${stats.totalLogs}`); console.log(`Chain integrity: ${stats.chainIntegrity}%`); ``` ## Framework Examples ### Express.js Integration ```javascript 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 ```javascript 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 ```javascript 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: ```javascript 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: ```javascript // 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: ```typescript 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 1. Sign up at [trasor.io](https://trasor.io) 2. Go to your Settings page 3. Generate a new API key 4. Copy the key (format: `trasor_live_...`) ## Environment Variables - `VERIFIK_DEBUG`: Set to `'true'` to enable debug logging - `VERIFIK_API_KEY`: Default API key (can be overridden in constructor) - `VERIFIK_BASE_URL`: Default base URL (can be overridden in constructor) ## Contributing 1. Fork the repository 2. Create a feature branch: `git checkout -b feature-name` 3. Make your changes and add tests 4. Run the test suite: `npm test` 5. Submit a pull request ## Testing ```bash # Run all tests npm test # Run unit tests only npm run test:unit # Run with debug output VERIFIK_DEBUG=true npm test ``` ## License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. ## Support - 📧 **Email**: support@trasor.io - 📖 **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