TypeScript Types
Complete type reference for the Auth-Agent JavaScript/TypeScript SDK.
Configuration Types
SDKConfig
Configuration object for initializing the AgentSDK.
interface SDKConfig {
agentId: string;
agentSecret?: string;
serverUrl?: string;
timeout?: number;
customFetch?: typeof fetch;
onTokensReceived?: (tokens: TokenResponse) => void | Promise<void>;
onTokensRefreshed?: (tokens: TokenResponse) => void | Promise<void>;
onTokensRevoked?: () => void | Promise<void>;
}
Properties:
Your unique agent identifier (client ID)
Agent secret for confidential clients (optional)
Auth server URL (default: process.env.AUTH_SERVER_URL or
'https://api.auth-agent.com')
Request timeout in milliseconds (default: 10000)
Custom fetch implementation for HTTP requests
onTokensReceived
(tokens: TokenResponse) => void | Promise<void>
Callback invoked when new tokens are received
onTokensRefreshed
(tokens: TokenResponse) => void | Promise<void>
Callback invoked when tokens are refreshed
onTokensRevoked
() => void | Promise<void>
Callback invoked when tokens are revoked
Example:
const config: SDKConfig = {
agentId: "my-agent",
agentSecret: "secret-key",
serverUrl: "https://api.auth-agent.com",
timeout: 15000,
onTokensReceived: async (tokens) => {
await db.saveTokens(tokens);
},
};
OAuth & Token Types
TokenResponse
OAuth 2.1 token response from the server.
interface TokenResponse {
access_token: string;
token_type: "Bearer";
expires_in: number;
refresh_token?: string;
id_token?: string;
scope: string;
}
Properties:
OAuth access token for API requests
Token type (always 'Bearer')
Seconds until token expiration
Refresh token for obtaining new access tokens
OpenID Connect ID token (JWT)
Space-separated list of granted scopes
Example:
const tokens: TokenResponse = {
access_token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
token_type: "Bearer",
expires_in: 3600,
refresh_token: "refresh_token_value",
id_token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
scope: "openid profile email agent",
};
TokenManager
Interface for token manager state.
interface TokenManager {
accessToken: string | null;
idToken: string | null;
refreshToken: string | null;
tokenType: string;
expiresAt: number | null;
scopes: string | null;
}
Properties:
Current OpenID Connect ID token
Token type (always 'Bearer')
Token expiration timestamp in milliseconds
Space-separated list of granted scopes
AuthorizationUrlOptions
Options for generating an authorization URL.
interface AuthorizationUrlOptions {
redirectUri: string;
scope?: string;
state?: string;
}
Properties:
Space-separated list of requested scopes (default: 'openid profile email agent')
Custom state parameter for CSRF protection (auto-generated if not provided)
Example:
const options: AuthorizationUrlOptions = {
redirectUri: "https://myapp.com/callback",
scope: "openid profile email agent",
state: "custom-state-value",
};
PKCEPair
PKCE code verifier and challenge pair.
interface PKCEPair {
codeVerifier: string;
codeChallenge: string;
}
Properties:
Random base64url-encoded string (stored for token exchange)
SHA-256 hash of code verifier (sent to authorization server)
Example:
const pkce: PKCEPair = {
codeVerifier: "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk",
codeChallenge: "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",
};
User & Agent Types
UserInfo
OpenID Connect user information from /oauth2/userinfo endpoint.
interface UserInfo {
sub: string;
agent_id: string;
name?: string;
email?: string;
model_name: string;
permissions?: string[];
[key: string]: any;
}
Properties:
Subject identifier (user ID)
AI model name (e.g., ‘gpt-4’, ‘claude-3’)
Array of granted permissions
Example:
const userInfo: UserInfo = {
sub: "user-123",
agent_id: "my-agent",
name: "John Doe",
email: "john@example.com",
model_name: "gpt-4",
permissions: ["read", "write"],
};
AgentProfile
Agent profile information.
interface AgentProfile {
agent_id: string;
model_name: string;
owner_name: string;
owner_email: string;
permissions: string[];
disabled: boolean;
created_at: string;
updated_at: string;
}
Properties:
Array of agent permissions
Whether agent is disabled
ISO 8601 timestamp of creation
ISO 8601 timestamp of last update
Example:
const profile: AgentProfile = {
agent_id: "my-agent",
model_name: "gpt-4",
owner_name: "Jane Doe",
owner_email: "jane@example.com",
permissions: ["read", "write", "admin"],
disabled: false,
created_at: "2024-01-15T10:30:00Z",
updated_at: "2024-02-20T14:45:00Z",
};
Registration & Authentication Types
AgentRegistrationRequest
Request payload for registering a new agent.
interface AgentRegistrationRequest {
agent_id: string;
agent_secret: string;
model_name: string;
owner_name: string;
owner_email: string;
}
Properties:
Unique identifier for the agent
Secure secret key for the agent
AI model name (e.g., ‘gpt-4’, ‘claude-3’)
Agent owner’s email address
Example:
const request: AgentRegistrationRequest = {
agent_id: "my-ai-agent",
agent_secret: "secure-random-secret",
model_name: "gpt-4",
owner_name: "John Doe",
owner_email: "john@example.com",
};
AgentRegistrationResponse
Response from agent registration.
interface AgentRegistrationResponse {
success: boolean;
agent_id: string;
message: string;
}
Properties:
Whether registration was successful
Example:
const response: AgentRegistrationResponse = {
success: true,
agent_id: "my-ai-agent",
message: "Agent registered successfully",
};
AgentAuthRequest
Request payload for agent authentication (legacy challenge flow).
interface AgentAuthRequest {
agent_id: string;
agent_secret: string;
model_name: string;
client_id: string;
redirect_uri: string;
state?: string;
scope?: string;
code_challenge?: string;
code_challenge_method?: string;
}
Properties:
PKCE method (should be ‘S256’)
AgentAuthResponse
Response from agent authentication.
interface AgentAuthResponse {
session_id: string;
next_step: "challenge";
challenge_url: string;
expires_in: number;
}
Properties:
Unique session identifier
Next step in authentication flow
URL for completing the challenge
Session expiration in seconds
Event & Verification Types
EventData
Event data for tracking and analytics.
interface EventData {
event: string;
selector?: string;
site?: string;
evidence?: string;
result?: string;
[key: string]: any;
}
Properties:
CSS selector or element identifier
Evidence or proof of action
Example:
const event: EventData = {
event: "click",
selector: "#purchase-button",
site: "store.example.com",
evidence: "oauth_authenticated",
customField: "custom value",
};
ChallengeResponse
Response from requesting a verification challenge.
interface ChallengeResponse {
ok: boolean;
challenge?: string;
expires?: number;
sig?: string;
verify_ctx_id?: string;
message?: string;
}
Properties:
Whether request was successful
Challenge string to verify
Challenge expiration timestamp
Example:
const challengeResponse: ChallengeResponse = {
ok: true,
challenge: "verify-123-abc",
expires: 1735689600,
sig: "signature-value",
verify_ctx_id: "ctx-456-def",
};
VerificationConfirmRequest
Request payload for confirming verification.
interface VerificationConfirmRequest {
challenge: string;
expires: number;
sig: string;
verify_ctx_id: string;
}
Properties:
Challenge string from ChallengeResponse
Challenge expiration timestamp
Example:
const confirmRequest: VerificationConfirmRequest = {
challenge: "verify-123-abc",
expires: 1735689600,
sig: "signature-value",
verify_ctx_id: "ctx-456-def",
};
IntrospectionResponse
Token introspection response.
interface IntrospectionResponse {
active: boolean;
scope?: string;
client_id?: string;
username?: string;
token_type?: string;
exp?: number;
iat?: number;
sub?: string;
[key: string]: any;
}
Properties:
Whether token is active and valid
Space-separated list of scopes
Expiration timestamp (Unix time)
Issued at timestamp (Unix time)
Example:
const introspection: IntrospectionResponse = {
active: true,
scope: "openid profile email agent",
client_id: "my-agent",
token_type: "Bearer",
exp: 1735689600,
iat: 1735686000,
sub: "user-123",
};
Error Types
AuthError
Extended error type for authentication errors.
interface AuthError extends Error {
code: string;
description?: string;
statusCode?: number;
}
Properties:
Error code (e.g., ‘token_expired’, ‘state_mismatch’)
Human-readable error description
HTTP status code (if applicable)
Example:
try {
await sdk.exchangeCode(code, state, redirectUri);
} catch (error) {
const authError = error as AuthError;
console.error("Code:", authError.code);
console.error("Description:", authError.description);
console.error("Status:", authError.statusCode);
if (authError.code === "token_expired") {
// Handle expired token
}
}
Common Error Codes:
state_mismatch - State parameter mismatch (CSRF)
pkce_missing - Code verifier not found
token_expired - Access token expired
forbidden - Insufficient permissions
no_refresh_token - Refresh token not provided
refresh_failed - Token refresh failed
revoke_failed - Token revocation failed
introspection_failed - Token introspection failed
no_token - Token required but not provided
Type Guards
You can use TypeScript type guards to safely work with SDK types:
function isTokenResponse(obj: any): obj is TokenResponse {
return (
typeof obj === "object" &&
typeof obj.access_token === "string" &&
obj.token_type === "Bearer" &&
typeof obj.expires_in === "number"
);
}
function isAuthError(error: any): error is AuthError {
return (
error instanceof Error && "code" in error && typeof error.code === "string"
);
}
// Usage
try {
const tokens = await sdk.exchangeCode(code, state, redirectUri);
if (isTokenResponse(tokens)) {
console.log("Valid token response");
}
} catch (error) {
if (isAuthError(error)) {
console.error("Auth error:", error.code);
}
}
Complete Type Usage Example
import type {
SDKConfig,
TokenResponse,
UserInfo,
AgentProfile,
AgentRegistrationRequest,
AgentRegistrationResponse,
EventData,
ChallengeResponse,
VerificationConfirmRequest,
IntrospectionResponse,
AuthError,
PKCEPair,
AuthorizationUrlOptions,
} from "ai-auth";
// Configuration
const config: SDKConfig = {
agentId: "my-agent",
agentSecret: "secret",
serverUrl: "https://api.auth-agent.com",
timeout: 15000,
onTokensReceived: async (tokens: TokenResponse) => {
await saveTokens(tokens);
},
};
// Registration
const registrationRequest: AgentRegistrationRequest = {
agent_id: "my-agent",
agent_secret: "secret",
model_name: "gpt-4",
owner_name: "John Doe",
owner_email: "john@example.com",
};
const registrationResponse: AgentRegistrationResponse = await sdk.registerAgent(
registrationRequest
);
// OAuth Flow
const authOptions: AuthorizationUrlOptions = {
redirectUri: "https://myapp.com/callback",
scope: "openid profile email agent",
};
const { url, codeVerifier, state } = await sdk.getAuthorizationUrl(authOptions);
// Token handling
const tokens: TokenResponse = await sdk.exchangeCode(code, state, redirectUri);
// User info
const userInfo: UserInfo = await sdk.getUserInfo(tokens.access_token);
// Agent profile
const profile: AgentProfile = await sdk.getAgentProfile(tokens.access_token);
// Events
const eventData: EventData = {
event: "click",
selector: "#button",
site: "example.com",
};
await sdk.sendEvent(tokens.access_token, eventData);
// Verification
const challenge: ChallengeResponse = await sdk.requestChallenge(
tokens.access_token
);
if (challenge.ok && challenge.challenge) {
const confirmRequest: VerificationConfirmRequest = {
challenge: challenge.challenge,
expires: challenge.expires!,
sig: challenge.sig!,
verify_ctx_id: challenge.verify_ctx_id!,
};
await sdk.confirmVerification(tokens.access_token, confirmRequest);
}
// Token introspection
const introspection: IntrospectionResponse = await sdk.introspectToken(
tokens.access_token
);
if (introspection.active) {
console.log("Token is valid");
}
// Error handling
try {
await sdk.exchangeCode(code, state, redirectUri);
} catch (error) {
const authError = error as AuthError;
console.error(authError.code, authError.description);
}
Next Steps