marzban-sdk
Version:
Fully typed client SDK for the Marzban API, supporting both browser and Node.js environments.
228 lines (158 loc) β’ 8.79 kB
Markdown
<div align="center">
<img src="./docs/logo.png" alt="MarzbanSDK" width="320px" height="320px" />
</div>
# π MarzbanSDK
<div align="center">
[](https://www.npmjs.com/package/marzban-sdk/v/latest)
[](https://www.npmjs.com/package/marzban-sdk)
[](https://www.npmjs.com/package/marzban-sdk)
[](https://github.com/Ilmar7786/marzban-sdk/blob/main/LICENSE)
[](https://github.com/Ilmar7786/marzban-sdk)
</div>
**MarzbanSDK** is a fully typed, auto-generated client library for interacting with the [Marzban](https://github.com/Gozargah/Marzban) API.
It works seamlessly in both **Node.js** and **browser environments**, giving developers a clean, strongly-typed interface to Marzbanβs full feature set β including real-time WebSocket support, token refresh handling, and robust retry mechanisms.
π [View on GitHub](https://github.com/Ilmar7786/marzban-sdk)
## π Table of Contents
- [β¨ Features](#-features)
- [π¦ Installation](#-installation)
- [π Quick Start](#-quick-start)
- [π Configuration Options](#-configuration-options)
- [π Authorization Control](#-authorization-control)
- [π How It Works](#-how-it-works)
- [π API Documentation](#-api-documentation)
- [π― Error Handling](#-error-handling)
- [π Data Validation](#-data-validation)
- [π¨ Webhook Support](#-webhook-support)
- [π οΈ Utilities](#-utilities)
- [π‘ WebSocket Support](#-websocket-support)
- [π€ Contributing](#-contributing)
- [π License](#-license)
- [β Support the Project](#-support-the-project)
## β¨ Features
- β
**First-class TypeScript Support** β Autocomplete and type safety for all inputs and responses.
- π **Manual or Automatic Authorization** β Choose between explicit login with full error handling, or backward-compatible automatic login.
- π **Auto Token Refresh** β Seamless handling of session expiration.
- π **Built-in Retry Logic** β Robust handling of network errors and downtime.
- π― **[Classified Error System](./docs/ERRORS.md)** β Type-safe error handling with detailed error codes and guards.
- π **[Zod Validation](./docs/VALIDATION.md)** β Runtime type validation for configuration and API payloads.
- π¨ **[Webhook Support](./docs/WEBHOOK.md)** β Real-time event handling with signature verification and payload validation.
- π οΈ **[Utility Functions](./docs/UTILITIES.md)** β Helpers for bytes conversion, datetime calculations, and template variables.
- π‘ **[Real-time WebSocket Logging](./docs/WEBSOCKET.md)** β Stream logs from the core and nodes with ease.
- π **Generated from OpenAPI** β Always up-to-date with the official Marzban API.
## π¦ Installation
Install MarzbanSDK via npm:
```sh
npm install marzban-sdk
```
Or using yarn:
```sh
yarn add marzban-sdk
```
## π Configuration Options
The `Config` object is used to initialize the MarzbanSDK instance. Below are all available options:
| Name | Type | Required | Default | Description |
| -------------------- | ------- | -------- | ------- | -------------------------------------------------------------------------------------------------- |
| `baseUrl` | string | Yes | β | The base URL of the Marzban API instance. Example: `https://api.example.com` |
| `username` | string | Yes | β | The username for authentication. |
| `password` | string | Yes | β | The password for authentication. |
| `token` | string | No | β | Optional JWT token for direct authorization. If provided, SDK uses this token for requests. |
| `retries` | number | No | 3 | Number of automatic retries for failed HTTP requests. |
| `authenticateOnInit` | boolean | No | true | If true (default), SDK authenticates automatically on init. If false, call `authorize()` manually. |
## π Authorization Control
MarzbanSDK gives you full control over authentication:
- **Automatic authentication** (default): The SDK logs in as soon as you create an instance.
- **Manual authentication**: Set `authenticateOnInit: false` to delay login and handle errors yourself.
```typescript
import { createMarzbanSDK, isAuthError } from 'marzban-sdk'
const sdk = await createMarzbanSDK({
baseUrl: 'https://api.example.com',
username: 'admin',
password: 'secret',
authenticateOnInit: false, // Manual mode
})
try {
await sdk.authorize() // Explicit login
// Now you can make authenticated requests
} catch (e) {
if (isAuthError(e)) {
// Handle authentication failure
console.error('Invalid credentials')
}
}
```
You can also force re-authentication at any time:
```typescript
await sdk.authorize(true) // Force a new login, even if already authenticated
```
See [Error Handling Guide](./docs/ERRORS.md) for comprehensive error handling patterns.
## π Quick Start
```typescript
import { createMarzbanSDK } from 'marzban-sdk'
// Create SDK instance with automatic authentication
const sdk = await createMarzbanSDK({
baseUrl: 'https://api.example.com',
username: 'your-username',
password: 'your-password',
})
// Or with manual authentication
const sdkManual = await createMarzbanSDK({
baseUrl: 'https://api.example.com',
username: 'your-username',
password: 'your-password',
authenticateOnInit: false,
})
await sdkManual.authorize()
// Fetch user details
const user = await sdk.user.getUser('username')
console.log(user)
// Get an authorization token
const token = sdk.getAuthToken()
console.log(token)
```
## π How It Works
### **1οΈβ£ Full Typing and Schema**
MarzbanSDK provides full TypeScript typing and schema definitions for all API methods, parameters, and responses.
### **2οΈβ£ Generated Sources**
The SDK is **auto-generated from the OpenAPI specification**, ensuring it stays up-to-date with API changes.
- The entry point for the SDK is the **`MarzbanSDK`** class.
- All API methods are dynamically generated based on the OpenAPI schema.
## π API Documentation
For detailed API reference, visit the [API Documentation](./docs/API_DOCUMENTATION.md).
## π― Error Handling
MarzbanSDK provides a comprehensive error handling system with classified errors, type-safe guards, and detailed error information.
Learn how to handle:
- **Authentication errors** β Login and token failures
- **Configuration errors** β Invalid SDK setup
- **HTTP errors** β Network failures
- **Webhook errors** β Invalid signatures and payloads
β See [Error Handling Guide](./docs/ERRORS.md)
## π Data Validation
All SDK configuration and API payloads are validated using **Zod** at runtime, ensuring type safety both at compile-time and runtime.
β See [Validation Guide](./docs/VALIDATION.md)
## π¨ Webhook Support
Handle real-time events from Marzban with full webhook support:
- **Signature verification** β HMAC-SHA256 validation
- **Payload validation** β Zod-powered type-safe schemas
- **Event subscriptions** β Typed listeners with wildcards
- **Batch processing** β Handle multiple webhooks at once
β See [Webhook Guide](./docs/WEBHOOK.md)
## π οΈ Utilities
Helper utilities for common operations:
- **Bytes conversion** β Parse and format data sizes (GB, MB, etc.)
- **Datetime** β Date calculations and remaining time
- **Template variables** β Work with Marzban host-settings variables
β See [Utilities Guide](./docs/UTILITIES.md)
## π‘ WebSocket Support
MarzbanSDK supports WebSocket for **real-time log streaming**.
You can receive logs from both the **core server** and individual **nodes**.
For more details, check the [WebSocket Guide](./docs/WEBSOCKET.md).
## π€ Contributing
We welcome contributions! If you'd like to improve MarzbanSDK, please:
1. Fork the repository π
2. Create a new branch π§
3. Submit a pull request π
For details, check our [Contribution Guidelines](./docs/CONTRIBUTING.md).
## π License
This project is licensed under the MIT License.
## β Support the Project
If you find marzban-sdk useful, please give it a star on [GitHub](https://github.com/Ilmar7786/marzban-sdk)! It helps us stay motivated and grow the project.