@clawauth/sdk
v1.0.0
Published
Official ClawAuth SDK for JavaScript/TypeScript - Cryptographic authentication for AI Agents
Maintainers
Readme
ClawAuth JavaScript/TypeScript SDK
Official JavaScript SDK for ClawAuth. Provides cryptographic authentication for AI agents using ECDSA P-256 signatures.
Features
- 🔐 Cryptographic Authentication - ECDSA P-256 signature-based auth (no passwords)
- 🌐 Cross-Platform - Works in Node.js and browsers (Web Crypto API)
- 🎯 Role-Based Access Control - Flexible permissions and roles
- 📊 Trust Scoring - Dynamic trust levels based on behavior
- ⚡ Express Middleware - Easy integration with Express.js
- 🔄 Token Management - Automatic refresh and revocation
- 📘 TypeScript - Full TypeScript support with types
- 🛡️ Security First - Private keys never leave the device
Installation
npm install @clawauth/sdkQuick Start
Agent Registration & Authentication
import { ClawAuthAgent } from '@clawauth/sdk';
// 1. Generate a keypair (ECDSA P-256)
const keypair = await ClawAuthAgent.generateKeypair();
console.log('Public key:', keypair.publicKey);
// Private key stays on device: keypair.privateKey
// 2. Register the agent
const registration = await ClawAuthAgent.register({
email: '[email protected]',
name: 'MyAIAgent',
publicKey: keypair.publicKey,
baseUrl: 'https://api.clawauth.com' // or your ClawAuth instance
});
console.log('Agent ID:', registration.agentId);
// 3. Create agent instance
const agent = new ClawAuthAgent({
agentId: registration.agentId,
privateKey: keypair.privateKey,
baseUrl: 'https://api.clawauth.com'
});
// 4. Authenticate (challenge-response flow)
const tokens = await agent.authenticate();
console.log('Access token:', tokens.accessToken);
console.log('Refresh token:', tokens.refreshToken);
// 5. Refresh tokens when needed
const newTokens = await agent.refreshToken(tokens.refreshToken);Service-Side Token Verification
import { ClawAuthService } from '@clawauth/sdk';
const service = new ClawAuthService({
serviceId: 'your-service-id',
apiKey: 'your-service-api-key',
baseUrl: 'https://api.clawauth.com'
});
// Verify agent token
const result = await service.verifyToken(agentToken);
if (result.valid) {
console.log('Agent info:', result.agent);
console.log('Roles:', result.agent.roles);
console.log('Trust score:', result.agent.trustScore);
} else {
console.error('Invalid token:', result.error);
}
// Report agent behavior
await service.reportTrust(agentId, {
score: 8.5,
reason: 'Excellent task completion'
});Express.js Middleware
import express from 'express';
import { requireClawAuth } from '@clawauth/sdk';
const app = express();
const service = new ClawAuthService({
serviceId: 'your-service-id',
apiKey: 'your-api-key'
});
// Basic authentication required
app.get('/protected',
requireClawAuth({ service }),
(req, res) => {
res.json({
message: `Hello, ${req.agent.name}!`,
trustScore: req.agent.trustScore
});
}
);
// Admin role required
app.get('/admin',
requireClawAuth({
service,
requiredRoles: ['admin']
}),
(req, res) => {
res.json({ message: 'Admin access granted' });
}
);
// High trust score required
app.post('/sensitive',
requireClawAuth({
service,
minTrustScore: 8.0
}),
(req, res) => {
res.json({ message: 'High-trust operation allowed' });
}
);
// Optional authentication
app.get('/optional',
requireClawAuth({
service,
optional: true
}),
(req, res) => {
if (req.agent) {
res.json({ message: `Welcome back, ${req.agent.name}!` });
} else {
res.json({ message: 'Hello, anonymous visitor!' });
}
}
);Browser Usage (Web Crypto API)
<!DOCTYPE html>
<html>
<head>
<title>ClawAuth Browser Example</title>
</head>
<body>
<script type="module">
import { ClawAuthAgent } from '@clawauth/sdk';
// Generate keypair in browser using Web Crypto API
const keypair = await ClawAuthAgent.generateKeypair();
// Register and authenticate...
const agent = new ClawAuthAgent({
agentId: 'your-agent-id',
privateKey: keypair.privateKey // CryptoKey object in browser
});
const tokens = await agent.authenticate();
// Use tokens in fetch requests
const response = await fetch('/api/protected', {
headers: {
'Authorization': `Bearer ${tokens.accessToken}`
}
});
</script>
</body>
</html>API Reference
ClawAuthAgent
Main class for agent-side authentication.
class ClawAuthAgent {
constructor(config: ClawAuthAgentConfig)
static generateKeypair(): Promise<KeyPair>
static register(options: RegisterOptions): Promise<RegisterAgentResponse>
authenticate(serviceId?: string): Promise<AuthenticateResponse>
refreshToken(refreshToken: string): Promise<AuthenticateResponse>
revoke(refreshToken?: string): Promise<{ revoked: number }>
}
interface ClawAuthAgentConfig {
agentId?: string;
privateKey?: any; // CryptoKey in browser, PEM string in Node.js
privateKeyPath?: string; // Node.js only
baseUrl?: string;
}
interface KeyPair {
publicKey: string; // PEM format
privateKey: any; // Platform-specific
}ClawAuthService
Main class for service-side token verification.
class ClawAuthService {
constructor(config: ClawAuthConfig)
verifyToken(token: string): Promise<VerifyTokenResponse>
reportTrust(agentId: string, feedback: TrustFeedback): Promise<TrustFeedbackResponse>
assignRole(agentId: string, roleId: string, expiresAt?: Date): Promise<{ assigned: boolean }>
createRole(name: string, description: string, permissions: string[]): Promise<{ roleId: string }>
}
interface ClawAuthConfig {
serviceId: string;
apiKey: string;
baseUrl?: string;
}
interface VerifyTokenResponse {
valid: boolean;
agent?: {
id: string;
name: string;
email: string;
trustScore: number;
roles: string[];
permissions: string[];
};
error?: string;
}Middleware
Express.js middleware for automatic token verification.
function requireClawAuth(options: RequireClawAuthOptions): ExpressMiddleware
interface RequireClawAuthOptions {
service?: ClawAuthService;
serviceId?: string;
apiKey?: string;
baseUrl?: string;
requiredRoles?: string[];
requiredPermissions?: string[];
minTrustScore?: number;
optional?: boolean;
}
// Middleware presets
const middlewarePresets = {
requireUser: (config, minTrustScore?) => ExpressMiddleware,
requireAdmin: (config) => ExpressMiddleware,
requirePermissions: (config, permissions) => ExpressMiddleware,
requireHighTrust: (config, minTrustScore?) => ExpressMiddleware
};Crypto Utilities
Cross-platform cryptographic functions.
// Generate ECDSA P-256 keypair
function generateKeypair(): Promise<KeyPair>
// Sign message with private key
function signMessage(privateKey: any, message: string): Promise<string>
// Verify signature
function verifySignature(publicKey: string, signature: string, message: string): Promise<boolean>
// Key format conversion
function importPrivateKey(pemKey: string): Promise<any>
function exportPublicKey(publicKey: any): Promise<string>Error Handling
The SDK provides specific error classes for different failure modes:
import {
ClawAuthError,
AuthenticationError,
InvalidSignatureError,
InsufficientPermissionsError,
RateLimitError
} from '@clawauth/sdk';
try {
await agent.authenticate();
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Authentication failed:', error.message);
} else if (error instanceof RateLimitError) {
console.error('Rate limit exceeded, please retry later');
} else if (error instanceof InvalidSignatureError) {
console.error('Cryptographic signature verification failed');
}
}Examples
Check out the /examples directory for complete examples:
basic-agent.js- Agent registration and authenticationexpress-service.js- Express.js service with middlewarebrowser-agent.html- Browser-based agent using Web Crypto API
TypeScript Support
The SDK is written in TypeScript and includes complete type definitions. No additional @types packages needed.
import { ClawAuthAgent, ClawAuthService, VerifyTokenResponse } from '@clawauth/sdk';
const agent: ClawAuthAgent = new ClawAuthAgent({ /* config */ });
const result: VerifyTokenResponse = await service.verifyToken(token);Browser Compatibility
- Node.js: 16+ (uses Node.js
cryptomodule) - Browsers: Modern browsers with Web Crypto API support
- Chrome 37+
- Firefox 34+
- Safari 7+
- Edge 12+
Security Considerations
- 🔑 Private keys never leave the device - Generated and stored locally
- 🌐 HTTPS required - All API communications must use TLS
- ⏱️ Token expiration - Access tokens expire after 1 hour
- 🔄 Automatic rotation - Refresh tokens rotate on each use
- 📝 Signature verification - All authentication uses cryptographic signatures
License
MIT License - see LICENSE file for details.
