UNPKG

@auth-agent/sdk

Version:

Complete server-side SDK for Auth-Agent - OAuth 2.1 / OIDC authentication for AI agents

415 lines (316 loc) 8.65 kB
# @auth-agent/sdk Complete server-side TypeScript SDK for Auth-Agent - OAuth 2.1 / OIDC authentication for AI agents. ## Features ✅ **OAuth 2.1 Compliant** - Full Authorization Code Flow with PKCE ✅ **Automatic Token Refresh** - Tokens refresh automatically before expiration ✅ **Server-Side Ready** - Works with Node.js, Bun, Deno ✅ **Type-Safe** - Full TypeScript support with comprehensive types ✅ **Agent Management** - Registration, authentication, and profile updates ✅ **Event Tracking** - Send verified clicks and agent events ✅ **Challenge Flow** - AI verification and challenge handling ## Installation ```bash npm install @auth-agent/sdk # or yarn add @auth-agent/sdk # or pnpm add @auth-agent/sdk # or bun add @auth-agent/sdk ``` ## Quick Start ### 1. Register Your Agent ```typescript import { AgentSDK } from '@auth-agent/sdk'; const sdk = new AgentSDK({ agentId: 'my_agent_123', serverUrl: 'https://auth-agent.com', }); // Register your agent await sdk.registerAgent({ agent_id: 'my_agent_123', agent_secret: 'your_secret_key', model_name: 'gpt-4', owner_name: 'Your Name', owner_email: 'you@example.com', }); ``` ### 2. Authenticate with OAuth 2.1 ```typescript const sdk = new AgentSDK({ agentId: 'my_agent_123', agentSecret: 'your_secret_key', }); // Get authorization URL const { url, codeVerifier, state } = await sdk.getAuthorizationUrl({ redirectUri: 'http://localhost:8080/callback', scope: 'openid profile email agent', }); console.log('Visit this URL to authorize:', url); // After user authorizes, exchange the code const tokens = await sdk.exchangeCode( authorizationCode, state, 'http://localhost:8080/callback' ); console.log('Access token:', tokens.access_token); ``` ### 3. Make Authenticated Requests ```typescript // Get user info const userInfo = await sdk.getUserInfo(); console.log('User:', userInfo); // Get agent profile const profile = await sdk.getAgentProfile(); console.log('Agent:', profile); // Send events await sdk.sendVerifiedClick('#submit-button', 'https://example.com'); await sdk.sendPostRun('#result', 'https://example.com', 'Success'); ``` ## API Reference ### Constructor ```typescript new AgentSDK(config: SDKConfig) ``` **Config Options:** - `agentId` (required): Your agent identifier - `agentSecret` (optional): Agent secret for server-side operations - `serverUrl` (optional): Auth-Agent server URL (default: 'https://auth-agent.com') - `timeout` (optional): Request timeout in ms (default: 10000) - `customFetch` (optional): Custom fetch implementation ### OAuth 2.1 Methods #### `getAuthorizationUrl(options)` Generate OAuth authorization URL with PKCE. ```typescript const { url, codeVerifier, state } = await sdk.getAuthorizationUrl({ redirectUri: 'http://localhost:8080/callback', scope: 'openid profile email agent', state: 'optional-csrf-token', }); ``` #### `exchangeCode(code, state, redirectUri)` Exchange authorization code for access tokens. ```typescript const tokens = await sdk.exchangeCode( 'auth_code_from_callback', 'state_from_url', 'http://localhost:8080/callback' ); ``` #### `refreshAccessToken()` Refresh expired access token using refresh token. ```typescript const newTokens = await sdk.refreshAccessToken(); ``` #### `authenticateHeadless(username, password, scope?)` Headless authentication (less secure, use for trusted agents only). ```typescript const tokens = await sdk.authenticateHeadless( 'user@example.com', 'password', 'openid profile email agent' ); ``` ### Agent Management #### `registerAgent(request)` Register a new AI agent. ```typescript await sdk.registerAgent({ agent_id: 'my_agent', agent_secret: 'secret_key', model_name: 'gpt-4', owner_name: 'Your Name', owner_email: 'you@example.com', }); ``` #### `getAgentProfile()` Get current agent profile. ```typescript const profile = await sdk.getAgentProfile(); console.log(profile.model_name, profile.permissions); ``` #### `updateAgentProfile(updates)` Update agent profile information. ```typescript await sdk.updateAgentProfile({ owner_name: 'New Name', model_name: 'gpt-4-turbo', }); ``` #### `getUserInfo()` Get OIDC user information. ```typescript const userInfo = await sdk.getUserInfo(); console.log(userInfo.sub, userInfo.email); ``` ### Event Tracking #### `sendEvent(eventData)` Send custom event data. ```typescript await sdk.sendEvent({ event: 'custom_action', data: { foo: 'bar' }, }); ``` #### `sendVerifiedClick(selector, site?, evidence?)` Send a verified click event. ```typescript await sdk.sendVerifiedClick('#button', 'https://example.com'); ``` #### `sendPostRun(selector, site, result)` Send post-run event with results. ```typescript await sdk.sendPostRun('#result', 'https://example.com', 'Operation completed'); ``` ### Challenge Flow #### `requestChallenge()` Request an AI verification challenge. ```typescript const challenge = await sdk.requestChallenge(); console.log(challenge.challenge, challenge.expires); ``` #### `confirmVerification(request)` Confirm verification with challenge response. ```typescript await sdk.confirmVerification({ challenge: 'challenge_string', expires: 1234567890, sig: 'signature', verify_ctx_id: 'context_id', }); ``` #### `pollAndAuthenticate(verifyCtxId, options?)` Poll for challenge and authenticate. ```typescript const success = await sdk.pollAndAuthenticate('verify_context_id', { timeout: 30000, interval: 2000, }); ``` ### Token Management #### `revokeToken(token?)` Revoke access or refresh token. ```typescript await sdk.revokeToken(); // Revokes current token await sdk.revokeToken('specific_token'); // Revokes specific token ``` #### `logout()` Logout agent (revoke tokens and clear session). ```typescript await sdk.logout(); ``` #### `introspectToken(token?)` Introspect token to check validity. ```typescript const info = await sdk.introspectToken(); console.log(info.active, info.exp); ``` ### Status Methods #### `isAuthenticated()` Check if agent is authenticated. ```typescript if (sdk.isAuthenticated()) { console.log('Authenticated!'); } ``` #### `getAccessToken()` Get current access token. ```typescript const token = sdk.getAccessToken(); ``` #### `getRefreshToken()` Get current refresh token. ```typescript const refreshToken = sdk.getRefreshToken(); ``` ## Error Handling All methods throw `AuthError` on failure: ```typescript try { await sdk.getUserInfo(); } catch (error) { if (error.code === 'token_expired') { await sdk.refreshAccessToken(); } else { console.error(error.description); } } ``` ## Examples ### Complete OAuth Flow ```typescript import { AgentSDK } from '@auth-agent/sdk'; import express from 'express'; const app = express(); const sdk = new AgentSDK({ agentId: 'my_agent', agentSecret: 'my_secret', }); // Start OAuth flow app.get('/login', async (req, res) => { const { url } = await sdk.getAuthorizationUrl({ redirectUri: 'http://localhost:3000/callback', }); res.redirect(url); }); // Handle callback app.get('/callback', async (req, res) => { const { code, state } = req.query; try { await sdk.exchangeCode( code as string, state as string, 'http://localhost:3000/callback' ); const userInfo = await sdk.getUserInfo(); res.json({ success: true, user: userInfo }); } catch (error) { res.status(500).json({ error: error.message }); } }); app.listen(3000); ``` ### Automatic Token Refresh ```typescript const sdk = new AgentSDK({ agentId: 'my_agent' }); // Exchange code and store tokens await sdk.exchangeCode(code, state, redirectUri); // Make requests - token will auto-refresh if needed const profile = await sdk.getAgentProfile(); // May auto-refresh const events = await sdk.sendEvent({ event: 'test' }); // May auto-refresh ``` ### Event Tracking ```typescript // Send click event await sdk.sendVerifiedClick('.submit-button', 'https://myapp.com'); // Send custom event await sdk.sendEvent({ event: 'task_completed', task_id: '123', duration: 5000, result: 'success', }); // Send post-run with results await sdk.sendPostRun( '.output', 'https://myapp.com', 'Task completed successfully with 95% accuracy' ); ``` ## TypeScript Support Full TypeScript support with comprehensive type definitions: ```typescript import type { SDKConfig, TokenResponse, UserInfo, AgentProfile, EventData, } from '@auth-agent/sdk'; ``` ## License MIT ## Support - Documentation: https://auth-agent.com/docs - GitHub: https://github.com/auth-agent/auth-agent - Email: support@auth-agent.com