npm package: @identitymachines/ironbook
Description: IronBook SDK for Node.js
Author: Identity Machines
Latest version: 0.3.3

# @identitymachines/ironbook

IronBook SDK for Node.js - A comprehensive SDK for interacting with the IronBook Trust Service.

## Installation

```bash
npm install @identitymachines/ironbook
```

## Usage

### Basic Setup

```javascript
import { IronBookClient } from '@identitymachines/ironbook';

// Create a client instance
const client = new IronBookClient({
  apiKey: 'your-api-key',
  // Optional:
  // baseUrl: 'https://api.ironbook.identitymachines.com',
  // timeoutMs: 10000, // default 10s
});
```

### Agent Operations

```javascript
// Register an agent
const agent = await client.registerAgent({
  agentName: 'my-agent',
  capabilities: ['read', 'write'],
});

// Update an agent
const updateResult = await client.updateAgent(agent.agentDid, {
  description: 'Updated agent for customer support',
  status: 'inactive',
});

// Get authentication token
const { access_token } = await client.getAuthToken({
  agentDid: agent.agentDid,
  developerDid: agent.developerDid,
  vc: agent.vc,
  action: 'read',
  resource: 'user-data',
});

// Upload a policy
const policy = await client.uploadPolicy({
  policyContent: `
    package policy
    
    allow if {
      input.action == "read"
      input.resource == "user-data"
    }
  `,
  metadata: {
    name: 'User Data Access Policy',
    description: 'Controls access to user data',
  },
});

// Get a policy decision
const decision = await client.policyDecision({
  agentDid: agent.agentDid,
  policyId: policy.policyId,
  context: {
    user: 'alice',
    user_role: 'user',
  },
  token: access_token,
});

console.log('Access allowed:', decision.allow);

// Get a single agent by DID
const gotAgent = await client.getAgent(agent.agentDid);
console.log('Agent status:', gotAgent.status);

// List agents (with filters and pagination)
const agentList = await client.listAgents({ status: 'active', limit: 25 });
console.log('Agents count:', agentList.count);
for (const a of agentList.items) console.log(a.did, a.capabilities);

// Get a single policy by ID
const gotPolicy = await client.getPolicy(policy.policyId);
console.log('Policy ID:', gotPolicy.policyId);

// List policies (with pagination)
const policies = await client.listPolicies({ limit: 10 });
console.log('Policies count:', policies.count);
for (const p of policies.items) console.log(p.policyId, p.isActive);

// List audit logs (with filters and pagination)
const logs = await client.listAuditLogs({
  agentDid: agent.agentDid,
  limit: 20,
});
console.log('Log entries:', logs.count);
for (const entry of logs.items)
  console.log(entry.timestamp, entry.eventType, entry.trustScore);

// Get organization settings
const orgSettings = await client.getOrgSettings();
console.log('Organization:', orgSettings.name);
console.log('Default Trust Score:', orgSettings.defaultTrustScore);
console.log('Token Expiration:', orgSettings.tokenExpiration);
```

## Features

- **Agent Management**: Register, update, and manage agents with the IronBook Trust Service
- **Policy Management**: Create and validate Rego policies
- **Authentication**: Generate and manage authentication tokens
- **Policy Decisions**: Get real-time policy decisions for access control

## API Reference

### IronBookClient

The main client class for interacting with the IronBook Trust Service.

#### Constructor

```javascript
new IronBookClient(options);
```

**Options:**

- `apiKey` (string, required): Your IronBook API key
- `baseUrl` (string, optional): Custom API base URL (defaults to the hosted IronBook API)
- `timeoutMs` (number, optional): Request timeout in milliseconds (default: 10000)

#### Methods

- `registerAgent(options)` - Register a new agent
- `updateAgent(agentDid, options)` - Update agent description and status
- `getAuthToken(options)` - Generate authentication tokens
- `uploadPolicy(options)` - Upload a new policy
- `policyDecision(options)` - Get policy decisions
- `getAgent(agentDid)` - Retrieve a single agent by DID
- `listAgents(options)` - List agents with filters and pagination
- `getPolicy(policyId)` - Retrieve a single policy by ID
- `listPolicies(options)` - List policies with pagination
- `listAuditLogs(options)` - List audit logs with filters and pagination
- `getOrgSettings()` - Retrieve organization settings for the caller's organization

### Error handling

All SDK methods throw a typed `IronBookError` on non-2xx responses and network/timeouts.

```javascript
import { IronBookClient } from '@identitymachines/ironbook';

const client = new IronBookClient({ apiKey: 'your-api-key', timeoutMs: 15000 });

try {
  const agent = await client.registerAgent({
    agentName: 'my-agent',
    capabilities: ['read', 'write'],
  });
} catch (err) {
  if (err.name === 'IronBookError') {
    console.error('status:', err.status); // e.g., 400, 401, 409
    console.error('code:', err.code); // e.g., 'VALIDATION_ERROR'
    console.error('requestId:', err.requestId); // correlation ID if provided
    console.error('details:', err.details); // parsed problem+json body when available
  } else {
    console.error('unexpected error:', err);
  }
}
```

The service returns RFC 7807 `application/problem+json` errors. The SDK surfaces `status`, a machine-readable `code`, and any additional `details` to make client-side handling predictable.

## Requirements

- Node.js 18+
- Valid IronBook API key

## License

MIT