Skip to main content

Installation

Install the SDK using your preferred package manager:
npm install @trusec/sdk

Requirements

  • Node.js 18 or later
  • TypeScript 4.7+ (optional, for type definitions)
The SDK also works in:
  • Modern browsers (Chrome, Firefox, Safari, Edge)
  • Edge runtimes (Vercel Edge, Cloudflare Workers)
  • Deno and Bun

Quick Start

import { TruSec } from '@trusec/sdk';

// Initialize the client
const trusec = new TruSec({
  apiKey: process.env.TRUSEC_SECRET_KEY,
});

// Use the SDK
const user = await trusec.users.get({ id: 'user_123' });
console.log(user.email);

Configuration

import { TruSec } from '@trusec/sdk';

const trusec = new TruSec({
  // Required
  apiKey: process.env.TRUSEC_SECRET_KEY,
  
  // Optional
  baseUrl: 'https://api.trusec.io',  // Custom API URL
  timeout: 30000,                      // Request timeout (ms)
  retries: 3,                          // Retry attempts
  debug: false,                        // Enable debug logging
  
  // Custom fetch implementation (for edge runtimes)
  fetch: customFetch,
});

Usage Examples

Authentication

// Create a session
const session = await trusec.sessions.create({
  email: '[email protected]',
  password: 'secure-password',
});

console.log('Session token:', session.token);

// Verify a session
const verification = await trusec.sessions.verify({
  token: session.token,
});

if (verification.valid) {
  console.log('User:', verification.user);
}

// Revoke a session
await trusec.sessions.revoke({
  token: session.token,
});

User Management

// List users
const users = await trusec.users.list({
  limit: 20,
  role: 'role_admin',
});

for (const user of users.data) {
  console.log(user.email);
}

// Create a user
const newUser = await trusec.users.create({
  email: '[email protected]',
  name: 'New User',
  roles: ['role_user'],
});

// Update a user
await trusec.users.update({
  id: newUser.id,
  name: 'Updated Name',
});

// Delete a user
await trusec.users.delete({ id: newUser.id });

Policies

// Create a policy
const policy = await trusec.policies.create({
  name: 'read-own-profile',
  effect: 'allow',
  principals: ['user:${self}'],
  actions: ['read'],
  resources: ['users/${self}'],
});

// Check permissions
const check = await trusec.permissions.check({
  principal: 'user:user_123',
  action: 'read',
  resource: 'users/user_123',
});

console.log('Allowed:', check.allowed);

Audit Logs

// Query logs
const logs = await trusec.logs.list({
  events: ['user.login', 'user.logout'],
  from: '2024-01-01T00:00:00Z',
  limit: 100,
});

for (const log of logs.data) {
  console.log(`${log.timestamp}: ${log.event} by ${log.actor.email}`);
}

// Stream logs in real-time
const stream = trusec.logs.stream({
  events: ['user.login.failed'],
});

stream.on('log', (log) => {
  console.log('Failed login attempt:', log);
  alertSecurityTeam(log);
});

stream.on('error', (error) => {
  console.error('Stream error:', error);
});

Error Handling

The SDK throws typed errors for different failure scenarios:
import { TruSec, TruSecError, AuthenticationError, RateLimitError } from '@trusec/sdk';

try {
  await trusec.users.get({ id: 'invalid_id' });
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Invalid API key');
  } else if (error instanceof RateLimitError) {
    console.error('Rate limited. Retry after:', error.retryAfter);
  } else if (error instanceof TruSecError) {
    console.error('API error:', error.code, error.message);
  } else {
    throw error;
  }
}

TypeScript Support

The SDK includes full TypeScript definitions:
import { TruSec, User, Session, Policy } from '@trusec/sdk';

const trusec = new TruSec({ apiKey: '...' });

// Types are inferred automatically
const user: User = await trusec.users.get({ id: 'user_123' });

// Or use generics for custom metadata
interface CustomUserMetadata {
  department: string;
  employeeId: number;
}

const userWithMeta = await trusec.users.get<CustomUserMetadata>({
  id: 'user_123',
});

console.log(userWithMeta.metadata.department);

Testing

Use the mock client for unit tests:
import { MockTruSec } from '@trusec/sdk/testing';

describe('MyService', () => {
  const mockTrusec = new MockTruSec();

  beforeEach(() => {
    mockTrusec.reset();
  });

  it('should authenticate users', async () => {
    // Setup mock
    mockTrusec.sessions.verify.mockResolvedValue({
      valid: true,
      user: { id: 'user_123', email: '[email protected]' },
    });

    // Run test
    const myService = new MyService(mockTrusec);
    const result = await myService.authenticateUser('token');

    expect(result.authenticated).toBe(true);
    expect(mockTrusec.sessions.verify).toHaveBeenCalledWith({
      token: 'token',
    });
  });
});

Framework Integrations

Express

import express from 'express';
import { TruSec } from '@trusec/sdk';

const app = express();
const trusec = new TruSec({ apiKey: process.env.TRUSEC_SECRET_KEY });

// Middleware
const authenticate = async (req, res, next) => {
  const token = req.headers.authorization?.replace('Bearer ', '');
  
  if (!token) {
    return res.status(401).json({ error: 'Missing token' });
  }

  const session = await trusec.sessions.verify({ token });
  
  if (!session.valid) {
    return res.status(401).json({ error: 'Invalid token' });
  }

  req.user = session.user;
  next();
};

app.get('/profile', authenticate, (req, res) => {
  res.json(req.user);
});

Next.js

// app/api/protected/route.ts
import { TruSec } from '@trusec/sdk';
import { NextRequest, NextResponse } from 'next/server';

const trusec = new TruSec({ apiKey: process.env.TRUSEC_SECRET_KEY });

export async function GET(request: NextRequest) {
  const token = request.cookies.get('session')?.value;

  if (!token) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  const session = await trusec.sessions.verify({ token });

  if (!session.valid) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  return NextResponse.json({ user: session.user });
}

Edge Runtime Support

The SDK works in edge runtimes without any additional configuration:
// Vercel Edge Function
import { TruSec } from '@trusec/sdk';

export const config = { runtime: 'edge' };

const trusec = new TruSec({ apiKey: process.env.TRUSEC_SECRET_KEY });

export default async function handler(request: Request) {
  const session = await trusec.sessions.verify({
    token: request.headers.get('Authorization')?.replace('Bearer ', ''),
  });

  return new Response(JSON.stringify(session), {
    headers: { 'Content-Type': 'application/json' },
  });
}