@juspay/neurolink
Version:
Universal AI Development Platform with working MCP integration, multi-provider support, voice (TTS/STT/realtime), and professional CLI. 58+ external MCP servers discoverable, multimodal file processing, RAG pipelines. Build, test, and deploy AI applicatio
249 lines (248 loc) • 7.15 kB
TypeScript
/**
* Authentication Utilities for NeuroLink Client SDK
*
* Provides authentication configuration, token management, and OAuth2 support
* for securing API requests to NeuroLink servers.
*
* @module @neurolink/client/auth
*/
import type { ClientMiddleware, ClientAuthConfig, ClientOAuth2Config, ClientTokenRefreshResult } from "../types/index.js";
/**
* OAuth2 Token Manager for client credentials flow
*
* Handles token acquisition, caching, and automatic refresh for OAuth2
* client credentials authentication.
*
* @example Basic usage
* ```typescript
* const tokenManager = new OAuth2TokenManager({
* tokenUrl: 'https://auth.example.com/oauth/token',
* clientId: 'your-client-id',
* clientSecret: 'your-client-secret',
* scope: 'api:read api:write',
* });
*
* // Get token (automatically refreshes if needed)
* const token = await tokenManager.getToken();
*
* // Use with client
* const client = createClient({
* baseUrl: 'https://api.example.com',
* });
* client.use(createDynamicAuthInterceptor(() => tokenManager.getToken()));
* ```
*/
export declare class OAuth2TokenManager {
private readonly config;
private token;
private tokenExpiry;
private refreshPromise;
private refreshBufferMs;
constructor(config: ClientOAuth2Config, options?: {
refreshBufferMs?: number;
});
/**
* Get a valid access token
*
* Returns cached token if still valid, otherwise fetches a new one.
* Handles concurrent requests by deduplicating token refresh calls.
*/
getToken(): Promise<string>;
/**
* Invalidate the cached token
*
* Call this when the token is rejected by the server to force a refresh.
*/
invalidate(): void;
/**
* Check if the cached token is valid
*/
isValid(): boolean;
/**
* Get the token expiry time in milliseconds
*/
getExpiryTime(): number | null;
/**
* Fetch a new token from the OAuth2 server
*/
private fetchToken;
}
/**
* JWT Token Manager with automatic refresh
*
* Manages JWT tokens with automatic refresh using a provided refresh function.
*
* @example
* ```typescript
* const tokenManager = new JWTTokenManager({
* token: 'initial-jwt-token',
* expiresAt: Date.now() + 3600000,
* refreshFn: async () => {
* const response = await fetch('/api/auth/refresh', {
* method: 'POST',
* credentials: 'include',
* });
* const data = await response.json();
* return { accessToken: data.token, expiresIn: data.expiresIn };
* },
* });
* ```
*/
export declare class JWTTokenManager {
private readonly config;
private token;
private tokenExpiry;
private refreshPromise;
private refreshBufferMs;
constructor(config: {
token: string;
expiresAt: number;
refreshFn: () => Promise<ClientTokenRefreshResult>;
refreshBufferMs?: number;
});
/**
* Get a valid access token
*/
getToken(): Promise<string>;
/**
* Force token refresh
*/
forceRefresh(): Promise<string>;
/**
* Update token manually
*/
setToken(token: string, expiresAt: number): void;
/**
* Check if token is valid
*/
isValid(): boolean;
private refreshToken;
}
/**
* Create an API key authentication middleware
*
* @example
* ```typescript
* const client = createClient({ baseUrl: 'https://api.example.com' });
* client.use(createApiKeyMiddleware('your-api-key'));
* ```
*/
export declare function createApiKeyMiddleware(apiKey: string, headerName?: string): ClientMiddleware;
/**
* Create a Bearer token authentication middleware
*
* @example
* ```typescript
* const client = createClient({ baseUrl: 'https://api.example.com' });
* client.use(createBearerTokenMiddleware('your-jwt-token'));
* ```
*/
export declare function createBearerTokenMiddleware(token: string): ClientMiddleware;
/**
* Create a dynamic authentication middleware with token manager
*
* @example With OAuth2TokenManager
* ```typescript
* const tokenManager = new OAuth2TokenManager({
* tokenUrl: 'https://auth.example.com/oauth/token',
* clientId: 'client-id',
* clientSecret: 'client-secret',
* });
*
* const client = createClient({ baseUrl: 'https://api.example.com' });
* client.use(createTokenManagerMiddleware(tokenManager));
* ```
*/
export declare function createTokenManagerMiddleware(tokenManager: OAuth2TokenManager | JWTTokenManager): ClientMiddleware;
/**
* Create an authentication middleware with retry on 401
*
* Automatically refreshes token and retries request when receiving 401.
*
* @example
* ```typescript
* const tokenManager = new OAuth2TokenManager({...});
*
* const client = createClient({ baseUrl: 'https://api.example.com' });
* client.use(createAuthWithRetryMiddleware(tokenManager));
* ```
*/
export declare function createAuthWithRetryMiddleware(tokenManager: OAuth2TokenManager, maxRetries?: number): ClientMiddleware;
/**
* Create a multi-auth middleware that supports multiple authentication methods
*
* @example
* ```typescript
* const client = createClient({ baseUrl: 'https://api.example.com' });
* client.use(createMultiAuthMiddleware({
* apiKey: process.env.API_KEY,
* token: sessionToken,
* }));
* ```
*/
export declare function createMultiAuthMiddleware(config: ClientAuthConfig): ClientMiddleware;
/**
* Error thrown during OAuth2 operations
*/
export declare class OAuth2Error extends Error {
readonly status: number;
readonly responseBody: string;
constructor(message: string, status: number, responseBody: string);
}
/**
* Error thrown when authentication fails
*/
export declare class OAuth2AuthenticationError extends Error {
readonly code: string;
readonly status: number;
constructor(message: string, code?: string, status?: number);
}
/**
* Error thrown when token refresh fails
*/
export declare class TokenRefreshError extends Error {
readonly cause?: Error;
constructor(message: string, cause?: Error);
}
/**
* Decode a JWT token payload without verification
*
* @example
* ```typescript
* const payload = decodeJWTPayload(token);
* console.log('Token expires at:', new Date(payload.exp * 1000));
* ```
*/
export declare function decodeJWTPayload(token: string): Record<string, unknown>;
/**
* Check if a JWT token is expired
*
* @example
* ```typescript
* if (isJWTExpired(token)) {
* // Refresh the token
* }
* ```
*/
export declare function isJWTExpired(token: string, bufferMs?: number): boolean;
/**
* Extract expiry time from a JWT token
*
* @returns Expiry time in milliseconds, or null if not available
*/
export declare function getJWTExpiry(token: string): number | null;
/**
* Create an API key from environment variable with validation
*
* @example
* ```typescript
* const apiKey = getApiKeyFromEnv('NEUROLINK_API_KEY');
* const client = createClient({
* baseUrl: 'https://api.example.com',
* apiKey,
* });
* ```
*/
export declare function getApiKeyFromEnv(envVar: string, options?: {
required?: boolean;
}): string | undefined;