Skip to main content

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:
agentId
string
required
Your unique agent identifier (client ID)
agentSecret
string
Agent secret for confidential clients (optional)
serverUrl
string
Auth server URL (default: process.env.AUTH_SERVER_URL or 'https://api.auth-agent.com')
timeout
number
Request timeout in milliseconds (default: 10000)
customFetch
typeof fetch
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:
access_token
string
required
OAuth access token for API requests
token_type
'Bearer'
required
Token type (always 'Bearer')
expires_in
number
required
Seconds until token expiration
refresh_token
string
Refresh token for obtaining new access tokens
id_token
string
OpenID Connect ID token (JWT)
scope
string
required
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:
accessToken
string | null
Current access token
idToken
string | null
Current OpenID Connect ID token
refreshToken
string | null
Current refresh token
tokenType
string
Token type (always 'Bearer')
expiresAt
number | null
Token expiration timestamp in milliseconds
scopes
string | null
Space-separated list of granted scopes

AuthorizationUrlOptions

Options for generating an authorization URL.
interface AuthorizationUrlOptions {
  redirectUri: string;
  scope?: string;
  state?: string;
}
Properties:
redirectUri
string
required
OAuth callback URL
scope
string
Space-separated list of requested scopes (default: 'openid profile email agent')
state
string
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:
codeVerifier
string
required
Random base64url-encoded string (stored for token exchange)
codeChallenge
string
required
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:
sub
string
required
Subject identifier (user ID)
agent_id
string
required
Agent identifier
name
string
User’s display name
email
string
User’s email address
model_name
string
required
AI model name (e.g., ‘gpt-4’, ‘claude-3’)
permissions
string[]
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:
agent_id
string
required
Unique agent identifier
model_name
string
required
AI model name
owner_name
string
required
Agent owner’s name
owner_email
string
required
Agent owner’s email
permissions
string[]
required
Array of agent permissions
disabled
boolean
required
Whether agent is disabled
created_at
string
required
ISO 8601 timestamp of creation
updated_at
string
required
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:
agent_id
string
required
Unique identifier for the agent
agent_secret
string
required
Secure secret key for the agent
model_name
string
required
AI model name (e.g., ‘gpt-4’, ‘claude-3’)
owner_name
string
required
Agent owner’s full name
owner_email
string
required
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:
success
boolean
required
Whether registration was successful
agent_id
string
required
The registered agent ID
message
string
required
Success or error message
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:
agent_id
string
required
Agent identifier
agent_secret
string
required
Agent secret key
model_name
string
required
AI model name
client_id
string
required
OAuth client ID
redirect_uri
string
required
OAuth redirect URI
state
string
OAuth state parameter
scope
string
Requested scopes
code_challenge
string
PKCE code challenge
code_challenge_method
string
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:
session_id
string
required
Unique session identifier
next_step
'challenge'
required
Next step in authentication flow
challenge_url
string
required
URL for completing the challenge
expires_in
number
required
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:
event
string
required
Event type/name
selector
string
CSS selector or element identifier
site
string
Site or domain name
evidence
string
Evidence or proof of action
result
string
Event result or outcome
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:
ok
boolean
required
Whether request was successful
challenge
string
Challenge string to verify
expires
number
Challenge expiration timestamp
sig
string
Challenge signature
verify_ctx_id
string
Verification context ID
message
string
Response message
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
required
Challenge string from ChallengeResponse
expires
number
required
Challenge expiration timestamp
sig
string
required
Challenge signature
verify_ctx_id
string
required
Verification context ID
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:
active
boolean
required
Whether token is active and valid
scope
string
Space-separated list of scopes
client_id
string
Client identifier
username
string
Username (if available)
token_type
string
Token type
exp
number
Expiration timestamp (Unix time)
iat
number
Issued at timestamp (Unix time)
sub
string
Subject identifier
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:
code
string
required
Error code (e.g., ‘token_expired’, ‘state_mismatch’)
description
string
Human-readable error description
statusCode
number
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