JavaScript SDK Reference
Complete reference for the ClawAuth JavaScript/TypeScript SDK. Supports both CommonJS and ES modules with full TypeScript definitions.
Installation
npm install @clawauth/sdkClawAuth (Service Integration)
The ClawAuth class is used by services to verify agent tokens and manage agent permissions.
Constructor
import { ClawAuth } from '@clawauth/sdk';
const auth = new ClawAuth({
serviceId: 'your-service-id',
apiKey: 'your-api-key',
baseUrl: 'https://api.clawauth.com' // optional
});Configuration Options
serviceId* - Your service identifierapiKey* - Your service API keybaseUrl- API base URL (default: https://api.clawauth.com)
verify(token)
Verify an agent's JWT token and get their identity information.
const result = await auth.verify(agentToken);
if (result.valid) {
console.log('Agent ID:', result.agent.id);
console.log('Agent name:', result.agent.name);
console.log('Trust score:', result.agent.trustScore);
console.log('Roles:', result.agent.roles);
console.log('Permissions:', result.agent.permissions);
} else {
console.log('Invalid token:', result.error);
}Response Type
interface VerifyTokenResponse {
valid: boolean;
agent?: {
id: string;
name: string;
email: string;
trustScore: number;
roles: string[];
permissions: string[];
};
error?: string;
}getAgent(agentId)
Get detailed information about a specific agent.
const agent = await auth.getAgent('agent_abc123');
console.log('Agent details:', {
id: agent.id,
name: agent.name,
trustScore: agent.trustScore,
status: agent.status,
lastSeenAt: agent.lastSeenAt
});assignRole(agentId, roleId)
Assign a role to an agent for your service.
await auth.assignRole('agent_abc123', 'admin');
await auth.assignRole('agent_def456', 'user');
// With expiration
await auth.assignRole('agent_ghi789', 'temporary', new Date('2026-12-31'));revokeRole(agentId, roleId)
Remove a role from an agent.
await auth.revokeRole('agent_abc123', 'admin');reportTrust(agentId, feedback)
Submit trust feedback to improve the agent's reputation score.
// Positive feedback
await auth.reportTrust('agent_abc123', {
score: 9,
reason: 'Excellent API usage, no rate limit violations'
});
// Negative feedback
await auth.reportTrust('agent_def456', {
score: 3,
reason: 'Frequent authentication failures'
});middleware()
Express.js middleware for automatic token verification.
import express from 'express';
const app = express();
// Add ClawAuth middleware
app.use(auth.middleware());
// Protected route - req.agent is automatically populated
app.get('/api/data', (req, res) => {
if (!req.agent) {
return res.status(401).json({ error: 'Authentication required' });
}
// Check permissions
if (!req.agent.permissions.includes('read')) {
return res.status(403).json({ error: 'Insufficient permissions' });
}
res.json({
message: `Hello ${req.agent.name}!`,
trustScore: req.agent.trustScore
});
});ClawAuthAgent (Agent Authentication)
The ClawAuthAgent class is used by AI agents to authenticate themselves and get access tokens.
Constructor
import { ClawAuthAgent } from '@clawauth/sdk';
// Using private key file
const agent = new ClawAuthAgent({
agentId: 'your-agent-id',
privateKeyPath: '/path/to/key.pem',
baseUrl: 'https://api.clawauth.com' // optional
});
// Using private key buffer
const agent = new ClawAuthAgent({
agentId: 'your-agent-id',
privateKey: privateKeyBuffer,
baseUrl: 'https://api.clawauth.com'
});generateKeypair() (static)
Generate a new ECDSA P-256 keypair for agent registration.
const keypair = ClawAuthAgent.generateKeypair();
console.log('Public key (share with ClawAuth):');
console.log(keypair.publicKey);
console.log('Private key (keep secret):');
console.log(keypair.privateKey);
// Save private key securely
import fs from 'fs';
fs.writeFileSync('agent-key.pem', keypair.privateKey, { mode: 0o600 });register() (static)
Register a new agent with ClawAuth.
const registration = await ClawAuthAgent.register({
email: '[email protected]',
name: 'My AI Agent',
publicKey: keypair.publicKey,
baseUrl: 'https://api.clawauth.com' // optional
});
console.log('Agent registered with ID:', registration.agentId);
console.log('Status:', registration.status);verifyEmail(registrationId, code, signature)
Complete email verification during registration.
// After receiving email with verification code
await agent.verifyEmail(
registration.registrationId,
'123456', // code from email
'signature_from_email' // cryptographic proof
);authenticate()
Authenticate and get JWT tokens using challenge-response.
const tokens = await agent.authenticate();
console.log('Access token:', tokens.accessToken);
console.log('Refresh token:', tokens.refreshToken);
console.log('Expires in:', tokens.expiresIn, 'seconds');
// Use access token with services
const response = await fetch('https://api.example.com/data', {
headers: {
'Authorization': `Bearer ${tokens.accessToken}`
}
});refresh(refreshToken)
Get new access tokens using a refresh token.
const newTokens = await agent.refresh(tokens.refreshToken);
console.log('New access token:', newTokens.accessToken);
console.log('New refresh token:', newTokens.refreshToken);
console.log('Expires in:', newTokens.expiresIn, 'seconds');Error Handling
The SDK provides specific error types for different failure scenarios:
import {
ClawAuthError,
AuthenticationError,
InvalidSignatureError,
InsufficientPermissionsError,
RateLimitError
} from '@clawauth/sdk';
try {
const result = await auth.verify(token);
} catch (error) {
if (error instanceof AuthenticationError) {
console.log('Authentication failed:', error.message);
} else if (error instanceof RateLimitError) {
console.log('Rate limit exceeded, try again later');
} else if (error instanceof ClawAuthError) {
console.log('ClawAuth error:', error.code, error.message);
} else {
console.log('Unknown error:', error);
}
}TypeScript Support
The SDK is written in TypeScript with full type definitions:
import { ClawAuth, Agent, VerifyTokenResponse } from '@clawauth/sdk';
const auth = new ClawAuth({
serviceId: 'test-service',
apiKey: 'test-key'
});
// Type-safe verification
const result: VerifyTokenResponse = await auth.verify(token);
if (result.valid && result.agent) {
// result.agent is properly typed
const agent: Agent = result.agent;
console.log(`Trust score: ${agent.trustScore}`);
}Examples
Complete Service Integration
import express from 'express';
import { ClawAuth } from '@clawauth/sdk';
const app = express();
const auth = new ClawAuth({
serviceId: process.env.CLAWAUTH_SERVICE_ID!,
apiKey: process.env.CLAWAUTH_API_KEY!
});
// Add authentication middleware
app.use(auth.middleware());
// Public endpoint
app.get('/public', (req, res) => {
res.json({ message: 'Hello World' });
});
// Protected endpoint
app.get('/protected', async (req, res) => {
if (!req.agent) {
return res.status(401).json({ error: 'Authentication required' });
}
// Check trust score
if (req.agent.trustScore < 5.0) {
return res.status(403).json({ error: 'Trust score too low' });
}
// Provide feedback
await auth.reportTrust(req.agent.id, {
score: 8,
reason: 'Successful API call'
});
res.json({
message: `Hello ${req.agent.name}!`,
trustScore: req.agent.trustScore
});
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});Complete Agent Implementation
import { ClawAuthAgent } from '@clawauth/sdk';
class MyAgent {
private auth: ClawAuthAgent;
private accessToken?: string;
private refreshToken?: string;
constructor(agentId: string, privateKeyPath: string) {
this.auth = new ClawAuthAgent({
agentId,
privateKeyPath
});
}
async initialize() {
const tokens = await this.auth.authenticate();
this.accessToken = tokens.accessToken;
this.refreshToken = tokens.refreshToken;
}
async makeAuthenticatedRequest(url: string, options: RequestInit = {}) {
// Add authorization header
const headers = {
...options.headers,
'Authorization': `Bearer ${this.accessToken}`
};
let response = await fetch(url, { ...options, headers });
// Handle token expiration
if (response.status === 401 && this.refreshToken) {
const newTokens = await this.auth.refresh(this.refreshToken);
this.accessToken = newTokens.accessToken;
this.refreshToken = newTokens.refreshToken;
// Retry request with new token
headers['Authorization'] = `Bearer ${this.accessToken}`;
response = await fetch(url, { ...options, headers });
}
return response;
}
}
// Usage
const agent = new MyAgent('my-agent-id', './agent-key.pem');
await agent.initialize();
const response = await agent.makeAuthenticatedRequest('https://api.example.com/data');
const data = await response.json();