

Context: N-able released patches for 17 zero-day vulnerabilities in N-central (CVE-2024-XXXX series). This guide shows how to automate patch deployment, compliance checking, and vulnerability monitoring via the N-central API.
| Requirement | Details |
|---|---|
| N-central Instance | On-premise or hosted (v2024.1+) |
| API Service Account | Role: API Access + Patch Management + Device Management |
| API Credentials | Client ID + Client Secret (OAuth 2.0) |
| Network Access | Port 443 to your N-central FQDN |
# Python 3.10+
python3 --version
# Node.js 18+
node --version
# HTTP client for testing
curl --version
# Required
export NCENTRAL_BASE_URL="https://your-instance.n-able.com"
export NCENTRAL_CLIENT_ID="your-client-id"
export NCENTRAL_CLIENT_SECRET="your-client-secret"
# Optional
export NCENTRAL_TENANT_ID="your-tenant-id" # For multi-tenant
export LOG_LEVEL="INFO"
# Create virtual environment
python3 -m venv venv
source venv/bin/activate
# Install dependencies
pip install --upgrade pip
pip install httpx pydantic pydantic-settings python-dotenv tenacity rich
requirements.txt
httpx>=0.27.0
pydantic>=2.7.0
pydantic-settings>=2.3.0
python-dotenv>=1.0.0
tenacity>=8.2.0
rich>=13.7.0
# Initialize project
mkdir ncentral-patch-automation && cd ncentral-patch-automation
npm init -y
# Install dependencies
npm install axios zod dotenv p-retry winston
npm install -D typescript @types/node tsx vitest
package.json (key scripts)
{
"scripts": {
"dev": "tsx src/index.ts",
"build": "tsc",
"start": "node dist/index.js",
"test": "vitest run"
}
}
src/ncentral/client.py
"""
N-central API Client with OAuth 2.0 authentication and automatic token refresh.
Production-ready with retry logic, structured logging, and type safety.
"""
from __future__ import annotations
import base64
import logging
import time
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Any, Optional
from urllib.parse import urljoin
import httpx
from pydantic import BaseModel, Field
from tenacity import (
retry,
retry_if_exception_type,
stop_after_attempt,
wait_exponential_jitter,
)
# ─── Configuration ────────────────────────────────────────────────────────
logger = logging.getLogger("ncentral")
class NCentralSettings(BaseModel):
"""Settings loaded from environment variables."""
base_url: str = Field(..., description="N-central base URL (e.g., https://instance.n-able.com)")
client_id: str = Field(..., description="OAuth client ID")
client_secret: str = Field(..., description="OAuth client secret")
tenant_id: Optional[str] = Field(None, description="Tenant ID for multi-tenant instances")
timeout: float = Field(30.0, description="Request timeout in seconds")
max_retries: int = Field(3, description="Max retry attempts for transient errors")
# ─── Token Management ─────────────────────────────────────────────────────
@dataclass
class TokenInfo:
"""OAuth token with expiration tracking."""
access_token: str
expires_at: datetime
token_type: str = "Bearer"
scope: str = ""
@property
def is_expired(self) -> bool:
# Refresh 60 seconds before actual expiry
return datetime.utcnow() >= (self.expires_at - timedelta(seconds=60))
@property
def auth_header(self) -> str:
return f"{self.token_type} {self.access_token}"
# ─── API Models ───────────────────────────────────────────────────────────
class Device(BaseModel):
"""N-central device summary."""
id: str
name: str
ip_address: Optional[str] = None
os_name: Optional[str] = None
os_version: Optional[str] = None
last_contact: Optional[datetime] = None
patch_status: Optional[str] = None # "Compliant", "Non-Compliant", "Unknown"
class Patch(BaseModel):
"""Patch definition from N-central catalog."""
id: str
title: str
description: Optional[str] = None
severity: str # Critical, Important, Moderate, Low
classification: str # Security, Update, FeaturePack, etc.
kb_number: Optional[str] = None
cve_ids: list[str] = Field(default_factory=list)
release_date: Optional[datetime] = None
superseded: bool = False
class PatchCompliance(BaseModel):
"""Patch compliance status for a device."""
device_id: str
patch_id: str
status: str # "Installed", "Missing", "Failed", "PendingReboot", "NotApplicable"
last_scan: Optional[datetime] = None
install_date: Optional[datetime] = None
class PatchDeploymentRequest(BaseModel):
"""Request to deploy patches to devices."""
patch_ids: list[str]
device_ids: list[str]
schedule: Optional[datetime] = None
reboot_option: str = "IfRequired" # Never, IfRequired, Always
maintenance_window_id: Optional[str] = None
class DeploymentJob(BaseModel):
"""Patch deployment job status."""
id: str
status: str # "Pending", "InProgress", "Completed", "Failed", "Cancelled"
total_devices: int
successful: int
failed: int
created_at: datetime
completed_at: Optional[datetime] = None
# ─── Exceptions ───────────────────────────────────────────────────────────
class NCentralError(Exception):
"""Base exception for N-central API errors."""
def __init__(self, message: str, status_code: Optional[int] = None, response: Optional[dict] = None):
super().__init__(message)
self.status_code = status_code
self.response = response
class AuthenticationError(NCentralError):
"""Authentication/authorization failure."""
pass
class RateLimitError(NCentralError):
"""Rate limit exceeded (429)."""
def __init__(self, message: str, retry_after: int = 60, **kwargs):
super().__init__(message, **kwargs)
self.retry_after = retry_after
class NotFoundError(NCentralError):
"""Resource not found (404)."""
pass
# ─── Main Client ──────────────────────────────────────────────────────────
class NCentralClient:
"""
Thread-safe N-central API client with automatic token management.
Usage:
client = NCentralClient(settings)
devices = await client.get_devices(patch_status="Non-Compliant")
await client.deploy_patches(patch_ids=["CVE-2024-XXXX"], device_ids=[d.id for d in devices])
"""
# API endpoints (relative to base_url)
TOKEN_ENDPOINT = "/api/oauth/token"
DEVICES_ENDPOINT = "/api/v2/devices"
PATCHES_ENDPOINT = "/api/v2/patches"
COMPLIANCE_ENDPOINT = "/api/v2/patch-compliance"
DEPLOYMENTS_ENDPOINT = "/api/v2/patch-deployments"
JOBS_ENDPOINT = "/api/v2/jobs"
def __init__(self, settings: NCentralSettings):
self.settings = settings
self._token: Optional[TokenInfo] = None
self._client = httpx.AsyncClient(
base_url=settings.base_url.rstrip("/"),
timeout=httpx.Timeout(settings.timeout),
headers={"Accept": "application/json", "User-Agent": "ncentral-patch-automation/1.0"},
)
async def __aenter__(self) -> NCentralClient:
return self
async def __aexit__(self, *args) -> None:
await self.close()
async def close(self) -> None:
"""Close the HTTP client."""
await self._client.aclose()
# ─── Authentication ────────────────────────────────────────────────
async def _get_token(self) -> TokenInfo:
"""Fetch new OAuth token using client credentials grant."""
credentials = base64.b64encode(
f"{self.settings.client_id}:{self.settings.client_secret}".encode()
).decode()
headers = {
"Authorization": f"Basic {credentials}",
"Content-Type": "application/x-www-form-urlencoded",
}
data = {"grant_type": "client_credentials"}
if self.settings.tenant_id:
data["tenant_id"] = self.settings.tenant_id
response = await self._client.post(self.TOKEN_ENDPOINT, headers=headers, data=data)
if response.status_code == 401:
raise AuthenticationError("Invalid client credentials", status_code=401)
response.raise_for_status()
token_data = response.json()
expires_in = token_data.get("expires_in", 3600)
self._token = TokenInfo(
access_token=token_data["access_token"],
expires_at=datetime.utcnow() + timedelta(seconds=expires_in),
token_type=token_data.get("token_type", "Bearer"),
scope=token_data.get("scope", ""),
)
logger.info("Obtained new OAuth token (expires in %ds)", expires_in)
return self._token
async def _ensure_valid_token(self) -> str:
"""Get valid token, refreshing if necessary."""
if self._token is None or self._token.is_expired:
return (await self._get_token()).auth_header
return self._token.auth_header
# ─── Request Helper with Retry Logic ───────────────────────────────
@retry(
wait=wait_exponential_jitter(initial=1, max=30),
stop=stop_after_attempt(3),
retry=retry_if_exception_type((httpx.TimeoutException, httpx.NetworkError, RateLimitError)),
reraise=True,
)
async def _request(
self,
method: str,
endpoint: str,
*,
params: Optional[dict] = None,
json: Optional[dict] = None,
expected_status: int = 200,
) -> httpx.Response:
"""Make authenticated request with automatic retry on transient errors."""
headers = {"Authorization": await self._ensure_valid_token()}
response = await self._client.request(
method, endpoint, params=params, json=json, headers=headers
)
if response.status_code == 401:
# Token might have been revoked - force refresh and retry once
self._token = None
headers["Authorization"] = await self._ensure_valid_token()
response = await self._client.request(
method, endpoint, params=params, json=json, headers=headers
)
if response.status_code == 429:
retry_after = int(response.headers.get("Retry-After", "60"))
raise RateLimitError("Rate limited", retry_after=retry_after, status_code=429)
if response.status_code == 404:
raise NotFoundError(f"Resource not found: {endpoint}", status_code=404)
if response.status_code != expected_status:
raise NCentralError(
f"API error: {response.status_code}",
status_code=response.status_code,
response=response.json() if response.content else None,
)
return response
# ─── Device Management ─────────────────────────────────────────────
async def get_devices(
self,
*,
patch_status: Optional[str] = None,
os_filter: Optional[str] = None,
limit: int = 100,
offset: int = 0,
) -> list[Device]:
"""
Retrieve devices with optional filtering.
Args:
patch_status: Filter by patch status ("Compliant", "Non-Compliant", "Unknown")
os_filter: Filter by OS (e.g., "Windows 10", "Windows Server 2019")
limit: Max results per page (max 1000)
offset: Pagination offset
"""
params = {"limit": min(limit, 1000), "offset": offset}
if patch_status:
params["patchStatus"] = patch_status
if os_filter:
params["osName"] = os_filter
response = await self._request("GET", self.DEVICES_ENDPOINT, params=params)
data = response.json()
return [Device(**item) for item in data.get("items", [])]
async def get_device(self, device_id: str) -> Device:
"""Get single device by ID."""
response = await self._request("GET", f"{self.DEVICES_ENDPOINT}/{device_id}")
return Device(**response.json())
# ─── Patch Catalog ─────────────────────────────────────────────────
async def get_patches(
self,
*,
severity: Optional[str] = None,
classification: Optional[str] = None,
cve_ids: Optional[list[str]] = None,
released_after: Optional[datetime] = None,
limit: int = 100,
) -> list[Patch]:
"""
Query patch catalog with filters.
Example: Get all Critical security patches for CVE-2024-XXXX series
"""
params = {"limit": min(limit, 1000)}
if severity:
params["severity"] = severity
if classification:
params["classification"] = classification
if cve_ids:
params["cveIds"] = ",".join(cve_ids)
if released_after:
params["releasedAfter"] = released_after.isoformat()
response = await self._request("GET", self.PATCHES_ENDPOINT, params=params)
data = response.json()
return [Patch(**item) for item in data.get("items", [])]
async def get_patch(self, patch_id: str) -> Patch:
"""Get single patch details."""
response = await self._request("GET", f"{self.PATCHES_ENDPOINT}/{patch_id}")
return Patch(**response.json())
# ─── Compliance Checking ───────────────────────────────────────────
async def get_compliance(
self,
*,
device_ids: Optional[list[str]] = None,
patch_ids: Optional[list[str]] = None,
status: Optional[str] = None, # "Missing", "Installed", "Failed", etc.
) -> list[PatchCompliance]:
"""
Get patch compliance status across devices.
Critical for identifying which devices need the 17 zero-day patches.
"""
params = {}
if device_ids:
params["deviceIds"] = ",".join(device_ids)
if patch_ids:
params["patchIds"] = ",".join(patch_ids)
if status:
params["status"] = status
response = await self._request("GET", self.COMPLIANCE_ENDPOINT, params=params)
data = response.json()
return [PatchCompliance(**item) for item in data.get("items", [])]
async def get_device_compliance_summary(self, device_id: str) -> dict[str, int]:
"""Get compliance counts for a single device."""
compliance = await self.get_compliance(device_ids=[device_id])
summary = {"Installed": 0, "Missing": 0, "Failed": 0, "PendingReboot": 0, "NotApplicable": 0}
for c in compliance:
summary[c.status] = summary.get(c.status, 0) + 1
return summary
# ─── Patch Deployment ──────────────────────────────────────────────
async def deploy_patches(
self,
patch_ids: list[str],
device_ids: list[str],
*,
schedule: Optional[datetime] = None,
reboot_option: str = "IfRequired",
maintenance_window_id: Optional[str] = None,
) -> DeploymentJob:
"""
Deploy patches to target devices.
Returns a job ID for tracking deployment progress.
"""
request = PatchDeploymentRequest(
patch_ids=patch_ids,
device_ids=device_ids,
schedule=schedule,
reboot_option=reboot_option,
maintenance_window_id=maintenance_window_id,
)
response = await self._request(
"POST", self.DEPLOYMENTS_ENDPOINT, json=request.model_dump(exclude_none=True), expected_status=202
)
return DeploymentJob(**response.json())
async def get_deployment_job(self, job_id: str) -> DeploymentJob:
"""Get deployment job status."""
response = await self._request("GET", f"{self.JOBS_ENDPOINT}/{job_id}")
return DeploymentJob(**response.json())
async def wait_for_deployment(
self, job_id: str, *, poll_interval: int = 30, timeout: int = 3600
) -> DeploymentJob:
"""
Poll deployment job until completion.
Args:
job_id: Deployment job ID
poll_interval: Seconds between polls
timeout: Max seconds to wait
"""
start = time.time()
while time.time() - start < timeout:
job = await self.get_deployment_job(job_id)
if job.status in ("Completed", "Failed", "Cancelled"):
return job
logger.info(
"Deployment %s: %s (%d/%d successful)",
job_id, job.status, job.successful, job.total_devices
)
await asyncio.sleep(poll_interval)
raise TimeoutError(f"Deployment {job_id} did not complete within {timeout}s")
# ─── Convenience Functions ──────────────────────────────────────────────
async def find_zero_day_patches(client: NCentralClient, cve_prefix: str = "CVE-2024") -> list[Patch]:
"""Find patches matching the recent zero-day CVEs."""
all_patches = await client.get_patches(severity="Critical", classification="Security")
return [p for p in all_patches if any(cve.startswith(cve_prefix) for cve in p.cve_ids)]
async def get_non_compliant_devices_for_patches(
client: NCentralClient, patch_ids: list[str]
) -> list[Device]:
"""Get devices missing any of the specified patches."""
compliance = await client.get_compliance(patch_ids=patch_ids, status="Missing")
missing_device_ids = list({c.device_id for c in compliance})
if not missing_device_ids:
return []
# Fetch device details in batches
devices = []
for i in range(0, len(missing_device_ids), 100):
batch = missing_device_ids[i:i+100]
# Note: API may not support batch device lookup; fallback to individual
for dev_id in batch:
try:
devices.append(await client.get_device(dev_id))
except NotFoundError:
logger.warning("Device %s not found", dev_id)
return devices
src/main.py - Complete Working Example
"""
Main automation script: Detect and deploy N-central zero-day patches.
Run: python -m src.main
"""
import asyncio
import logging
import sys
from pathlib import Path
from rich.console import Console
from rich.logging import RichHandler
from rich.table import Table
# Add src to path
sys.path.insert(0, str(Path(__file__).parent))
from ncentral.client import (
NCentralClient,
NCentralSettings,
find_zero_day_patches,
get_non_compliant_devices_for_patches,
)
# ─── Setup ────────────────────────────────────────────────────────────────
console = Console()
logging.basicConfig(
level=logging.INFO,
format="%(message)s",
handlers=[RichHandler(console=console, rich_tracebacks=True)],
)
logger = logging.getLogger(__name__)
# ─── Core Logic ───────────────────────────────────────────────────────────
async def main() -> int:
"""Main automation workflow."""
# Load settings from environment
settings = NCentralSettings() # pydantic-settings auto-loads from .env
async with NCentralClient(settings) as client:
console.rule("[bold blue]N-central Zero-Day Patch Automation[/bold blue]")
# Step 1: Find the 17 zero-day patches (Critical security patches from 2024)
console.print("\n[1/5] Searching for zero-day patches (CVE-2024-*)...")
zero_day_patches = await find_zero_day_patches(client)
if not zero_day_patches:
console.print("[yellow]No zero-day patches found in catalog.[/yellow]")
return 0
console.print(f"Found [bold]{len(zero_day_patches)}[/bold] critical security patches:")
patch_table = Table("Patch ID", "Title", "Severity", "CVEs", "Released")
for p in zero_day_patches:
patch_table.add_row(
p.id, p.title[:60], p.severity, ", ".join(p.cve_ids[:3]),
p.release_date.strftime("%Y-%m-%d") if p.release_date else "N/A"
)
console.print(patch_table)
patch_ids = [p.id for p in zero_day_patches]
# Step 2: Find non-compliant devices
console.print("\n[2/5] Checking compliance for target patches...")
non_compliant = await get_non_compliant_devices_for_patches(client, patch_ids)
if not non_compliant:
console.print("[green]All devices compliant! No action needed.[/green]")
return 0
console.print(f"Found [bold red]{len(non_compliant)}[/bold red] non-compliant devices:")
device_table = Table("Device ID", "Name", "IP", "OS", "Last Contact")
for d in non_compliant[:20]: # Show first 20
device_table.add_row(
d.id, d.name, d.ip_address or "N/A",
f"{d.os_name or 'Unknown'} {d.os_version or ''}".strip(),
d.last_contact.strftime("%Y-%m-%d %H:%M") if d.last_contact else "Never"
)
console.print(device_table)
if len(non_compliant) > 20:
console.print(f"... and {len(non_compliant) - 20} more devices")
# Step 3: Confirm deployment (in production, use maintenance windows)
console.print("\n[3/5] Preparing deployment...")
device_ids = [d.id for d in non_compliant]
# Step 4: Deploy patches
console.print(f"Deploying {len(patch_ids)} patches to {len(device_ids)} devices...")
job = await client.deploy_patches(
patch_ids=patch_ids,
device_ids=device_ids,
reboot_option="IfRequired", # Respect maintenance windows in production
)
console.print(f"Deployment job created: [bold]{job.id}[/bold]")
# Step 5: Monitor deployment
console.print("\n[4/5] Monitoring deployment progress...")
with console.status("[bold green]Waiting for deployment to complete...") as status:
final_job = await client.wait_for_deployment(job.id, poll_interval=30)
console.print("\n[5/5] Deployment complete!")
result_table = Table("Metric", "Value")
result_table.add_row("Job ID", final_job.id)
result_table.add_row("Status", final_job.status)
result_table.add_row("Total Devices", str(final_job.total_devices))
result_table.add_row("Successful", str(final_job.successful))
result_table.add_row("Failed", str(final_job.failed))
console.print(result_table)
if final_job.failed > 0:
console.print("[red]Some deployments failed. Check N-central console for details.[/red]")
return 1
console.print("[green]All patches deployed successfully![/green]")
return 0
if __name__ == "__main__":
try:
exit_code = asyncio.run(main())
sys.exit(exit_code)
except KeyboardInterrupt:
console.print("\n[yellow]Interrupted by user[/yellow]")
sys.exit(130)
except Exception as e:
console.print(f"[red]Fatal error: {e}[/red]")
logger.exception("Unhandled exception")
sys.exit(1)
src/client.ts
/**
* N-central API Client for TypeScript/Node.js
* Features: OAuth 2.0, automatic token refresh, retry logic, type-safe models
*/
import axios, { AxiosInstance, AxiosError, InternalAxiosRequestConfig } from 'axios';
import { z } from 'zod';
import pRetry from 'p-retry';
import winston from 'winston';
// ─── Logger ────────────────────────────────────────────────────────────────
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [new winston.transports.Console()],
});
// ─── Configuration ─────────────────────────────────────────────────────────
export interface NCentralConfig {
baseUrl: string;
clientId: string;
clientSecret: string;
tenantId?: string;
timeout?: number;
maxRetries?: number;
}
function loadConfig(): NCentralConfig {
return {
baseUrl: process.env.NCENTRAL_BASE_URL!,
clientId: process.env.NCENTRAL_CLIENT_ID!,
clientSecret: process.env.NCENTRAL_CLIENT_SECRET!,
tenantId: process.env.NCENTRAL_TENANT_ID,
timeout: Number(process.env.NCENTRAL_TIMEOUT) || 30000,
maxRetries: Number(process.env.NCENTRAL_MAX_RETRIES) || 3,
};
}
// ─── Zod Schemas (Runtime Validation) ──────────────────────────────────────
const TokenResponseSchema = z.object({
access_token: z.string(),
token_type: z.string().default('Bearer'),
expires_in: z.number().default(3600),
scope: z.string().optional(),
});
export const DeviceSchema = z.object({
id: z.string(),
name: z.string(),
ipAddress: z.string().nullable().optional(),
osName: z.string().nullable().optional(),
osVersion: z.string().nullable().optional(),
lastContact: z.string().datetime().nullable().optional(),
patchStatus: z.string().nullable().optional(),
});
export const PatchSchema = z.object({
id: z.string(),
title: z.string(),
description: z.string().nullable().optional(),
severity: z.enum(['Critical', 'Important', 'Moderate', 'Low']),
classification: z.string(),
kbNumber: z.string().nullable().optional(),
cveIds: z.array(z.string()).default([]),
releaseDate: z.string().datetime().nullable().optional(),
superseded: z.boolean().default(false),
});
export const PatchComplianceSchema = z.object({
deviceId: z.string(),
patchId: z.string(),
status: z.enum(['Installed', 'Missing', 'Failed', 'PendingReboot', 'NotApplicable']),
lastScan: z.string().datetime().nullable().optional(),
installDate: z.string().datetime().nullable().optional(),
});
export const DeploymentRequestSchema = z.object({
patchIds: z.array(z.string()).min(1),
deviceIds: z.array(z.string()).min(1),
schedule: z.string().datetime().optional(),
rebootOption: z.enum(['Never', 'IfRequired', 'Always']).default('IfRequired'),
maintenanceWindowId: z.string().optional(),
});
export const DeploymentJobSchema = z.object({
id: z.string(),
status: z.enum(['Pending', 'InProgress', 'Completed', 'Failed', 'Cancelled']),
totalDevices: z.number(),
successful: z.number(),
failed: z.number(),
createdAt: z.string().datetime(),
completedAt: z.string().datetime().nullable().optional(),
});
// ─── Types ─────────────────────────────────────────────────────────────────
export type Device = z.infer<typeof DeviceSchema>;
export type Patch = z.infer<typeof PatchSchema>;
export type PatchCompliance = z.infer<typeof PatchComplianceSchema>;
export type DeploymentRequest = z.infer<typeof DeploymentRequestSchema>;
export type DeploymentJob = z.infer<typeof DeploymentJobSchema>;
// ─── Custom Errors ─────────────────────────────────────────────────────────
export class NCentralError extends Error {
constructor(
message: string,
public readonly statusCode?: number,
public readonly response?: unknown
) {
super(message);
this.name = 'NCentralError';
}
}
export class AuthenticationError extends NCentralError {
constructor(message: string, statusCode = 401, response?: unknown) {
super(message, statusCode, response);
this.name = 'AuthenticationError';
}
}
export class RateLimitError extends NCentralError {
constructor(
message: string,
public readonly retryAfter: number = 60,
statusCode = 429,
response?: unknown
) {
super(message, statusCode, response);
this.name = 'RateLimitError';
}
}
export class NotFoundError extends NCentralError {
constructor(message: string, statusCode = 404, response?: unknown) {
super(message, statusCode, response);
this.name = 'NotFoundError';
}
}
// ─── Token Manager ─────────────────────────────────────────────────────────
interface TokenInfo {
accessToken: string;
expiresAt: number; // Unix timestamp ms
tokenType: string;
}
class TokenManager {
private token: TokenInfo | null = null;
constructor(private readonly client: AxiosInstance, private readonly config: NCentralConfig) {}
async getAuthHeader(): Promise<string> {
if (!this.token || this.isExpired()) {
await this.refreshToken();
}
return `${this.token!.tokenType} ${this.token!.accessToken}`;
}
private isExpired(): boolean {
// Refresh 60 seconds before expiry
return Date.now() >= this.token!.expiresAt - 60_000;
}
private async refreshToken(): Promise<void> {
const credentials = Buffer.from(
`${this.config.clientId}:${this.config.clientSecret}`
).toString('base64');
const response = await this.client.post<z.infer<typeof TokenResponseSchema>>(
'/api/oauth/token',
new URLSearchParams({
grant_type: 'client_credentials',
...(this.config.tenantId && { tenant_id: this.config.tenantId }),
}),
{
headers: {
Authorization: `Basic ${credentials}`,
'Content-Type': 'application/x-www-form-urlencoded',
},
}
);
const data = TokenResponseSchema.parse(response.data);
this.token = {
accessToken: data.access_token,
expiresAt: Date.now() + data.expires_in * 1000,
tokenType: data.token_type,
};
logger.info('Obtained new OAuth token', { expiresIn: data.expires_in });
}
invalidate(): void {
this.token = null;
}
}
// ─── Main Client ───────────────────────────────────────────────────────────
export class NCentralClient {
private readonly axios: AxiosInstance;
private readonly tokenManager: TokenManager;
private readonly config: NCentralConfig;
constructor(config: NCentralConfig) {
this.config = config;
this.axios = axios.create({
baseURL: config.baseUrl.replace(/\/+$/, ''),
timeout: config.timeout,
headers: {
Accept: 'application/json',
'User-Agent': 'ncentral-patch-automation/1.0',
},
});
this.tokenManager = new TokenManager(this.axios, config);
this.setupInterceptors();
}
private setupInterceptors(): void {
// Request interceptor: add auth header
this.axios.interceptors.request.use(async (config: InternalAxiosRequestConfig) => {
config.headers.Authorization = await this.tokenManager.getAuthHeader();
return config;
});
// Response interceptor: handle 401 (token expired), 429 (rate limit)
this.axios.interceptors.response.use(
(response) => response,
async (error: AxiosError) => {
const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean };
if (error.response?.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
this.tokenManager.invalidate();
originalRequest.headers.Authorization = await this.tokenManager.getAuthHeader();
return this.axios.request(originalRequest);
}
if (error.response?.status === 429) {
const retryAfter = Number(error.response.headers['retry-after'] || '60');
throw new RateLimitError('Rate limited', retryAfter, 429, error.response.data);
}
throw this.mapError(error);
}
);
}
private mapError(error: AxiosError): NCentralError {
const status = error.response?.status;
const data = error.response?.data;
switch (status) {
case 401:
return new AuthenticationError('Authentication failed', status, data);
case 404:
return new NotFoundError(`Resource not found: ${error.config?.url}`, status, data);
default:
return new NCentralError(
---
## Next Steps
1. **Get API Access** - Sign up at the official website
2. **Try the Examples** - Run the code snippets above
3. **Read the Docs** - Check official documentation
4. **Join Communities** - Discord, Reddit, GitHub discussions
5. **Experiment** - Build something cool!
## Further Reading
- [TechCrunch AI](https://techcrunch.com/category/artificial-intelligence/)
- [The Verge](https://www.theverge.com/technology)
- [Wired AI](https://www.wired.com/tag/artificial-intelligence/)
- [Medium AI](https://medium.com/topic/artificial-intelligence)
**Source:** [Security Week AI](https://www.securityweek.com/n-able-kills-legacy-apis-patches-17-n-central-zero-days/)
---
*Follow ICARAX for more AI insights and tutorials.*
