Files
proxmox/docs/04-configuration/UNIFI_API_SETUP.md

309 lines
10 KiB
Markdown
Raw Permalink Normal View History

# UniFi API Setup Guide
**Last Updated:** 2025-01-20
**Document Version:** 1.0
**Status:** Active Documentation
---
## Overview
This guide covers setting up API integration for Ubiquiti UniFi/UDM Pro devices using the UniFi API library and MCP server.
## Prerequisites
- UniFi Controller/UDM Pro running and accessible
- Admin access to UniFi Network app or Controller web interface
- Node.js 18+ and pnpm installed
## API Modes
The UniFi integration supports two API modes:
1. **Official Local API** (v1 endpoints) - Uses API key authentication
2. **Private Controller API** (proxy/network endpoints) - Uses cookie-based session authentication
## Step 1: Choose API Mode
### Option A: Official Local API (Recommended for production)
The Official API is documented and version-specific, available in your UniFi Network app.
#### Getting API Credentials
1. **Access UniFi Network App**
- Open your UniFi Network application
- Navigate to: **Settings → Control Plane → Integrations**
- View the API documentation (specific to your Network app version)
2. **Generate API Key**
- From the Integrations page, generate an API key
- Save the API key securely (shown only once)
3. **Documentation**
- The Integrations page provides version-specific API documentation
- Look for OpenAPI/Swagger spec if available
- Base URL is typically your UDM Pro IP/hostname
#### Configuration
```bash
# ~/.env
UNIFI_UDM_URL=https://192.168.1.1
UNIFI_API_MODE=official
UNIFI_API_KEY=your-api-key-here
UNIFI_SITE_ID=default # Optional
UNIFI_VERIFY_SSL=false # Set to true for production
```
### Option B: Private Controller API (Traditional)
The Private API is reverse-engineered and used by many automation tools, but is undocumented and may change between versions.
#### Getting Credentials
- Use your UniFi Controller admin username and password
- No additional setup required
#### Configuration
```bash
# ~/.env
UNIFI_UDM_URL=https://192.168.1.1
UNIFI_API_MODE=private
UNIFI_USERNAME=admin
UNIFI_PASSWORD=your-password
UNIFI_SITE_ID=default # Optional
UNIFI_VERIFY_SSL=false # Set to true for production
```
## Step 2: Install Packages
From the project root:
```bash
pnpm install
pnpm unifi:build
```
This will:
- Install dependencies for `unifi-api` and `mcp-unifi`
- Build TypeScript to JavaScript
## Step 3: Configure Environment Variables
Create or update `~/.env` with your UniFi Controller credentials:
### For Official API Mode
```bash
# UniFi Controller Configuration (Official API)
UNIFI_UDM_URL=https://192.168.1.1
UNIFI_API_MODE=official
UNIFI_API_KEY=your-api-key-here
UNIFI_SITE_ID=default # Optional - will use default site if not provided
UNIFI_VERIFY_SSL=false # Set to true for production with valid SSL certs
```
### For Private API Mode
```bash
# UniFi Controller Configuration (Private API)
UNIFI_UDM_URL=https://192.168.1.1
UNIFI_API_MODE=private
UNIFI_USERNAME=admin
UNIFI_PASSWORD=your-password
UNIFI_SITE_ID=default # Optional - will use default site if not provided
UNIFI_VERIFY_SSL=false # Set to true for production with valid SSL certs
```
## Step 4: Test Connection
### Using CLI Tool
```bash
# Test listing devices
pnpm unifi:cli devices
# Test listing sites
pnpm unifi:cli sites
```
### Using MCP Server
```bash
# Start MCP server (for testing)
pnpm unifi:start
```
## Step 5: Claude Desktop Integration (Optional)
If using the MCP server with Claude Desktop:
1. **Add to Claude Desktop Config**
Edit your Claude Desktop configuration file:
```json
{
"mcpServers": {
"unifi": {
"command": "node",
"args": ["/absolute/path/to/proxmox/mcp-unifi/dist/index.js"]
}
}
}
```
2. **Config File Locations**
- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
- **Linux**: `~/.config/Claude/claude_desktop_config.json`
3. **Restart Claude Desktop**
## API Endpoint Notes
### Official Local API
- **Base Path**: `/v1/sites/{siteId}/...`
- **Authentication**: `Authorization: Bearer {apiKey}`
- **Endpoints**: Version-specific, see Integrations page in UniFi Network app
- **Documentation**: Available in Settings → Control Plane → Integrations
### Private Controller API
- **Base Path**: `/proxy/network/api/s/{site}/...`
- **Authentication**: Cookie-based session (`POST /api/auth/login`)
- **Login Endpoint**: `/api/auth/login` (not prefixed with `/proxy/network`)
- **Endpoints**: Reverse-engineered, may vary between versions
- **Documentation**: See [Ubiquiti Community Wiki](https://www.ubntwiki.com/products/software/unifi-controller/api)
### UDM Pro Specific Notes
- All Network API paths are prefixed with `/proxy/network`
- Example: `https://udmp/proxy/network/api/s/default/self`
- Login endpoint is at `/api/auth/login` (no prefix)
## Troubleshooting
### Connection Errors
- Verify `UNIFI_UDM_URL` is correct (try `http://` if `https://` fails)
- Check that the UniFi Controller is running and accessible
- Ensure firewall allows connections to the controller
- If using self-signed certificates, ensure `UNIFI_VERIFY_SSL=false`
### Authentication Errors
#### Official API
- Verify `UNIFI_API_KEY` is correct
- Check that the API key hasn't expired or been revoked
- Ensure API mode is set to `official`
- Verify the API key is for the correct UDM Pro/controller
- Test the API key directly with curl (or use the script that reads from dotenv):
```bash
# If UNIFI_UDM_URL and UNIFI_API_KEY are in .env or ~/.env:
./scripts/unifi/curl-sites.sh
# Or manually:
curl -k -X GET 'https://YOUR-UDM-IP/proxy/network/integration/v1/sites' \
-H 'X-API-KEY: YOUR_API_KEY' \
-H 'Accept: application/json'
```
- If you get 401 Unauthorized, the API key may be invalid - regenerate it in the UniFi Network app
#### Private API
- Verify `UNIFI_USERNAME` and `UNIFI_PASSWORD` are correct
- Check account permissions (Super Admin may be required for some operations)
- Ensure API mode is set to `private`
### Site Not Found
- Verify `UNIFI_SITE_ID` matches an existing site
- Default site is usually `default`
- List sites to see available site IDs: `pnpm unifi:cli sites`
### SSL Certificate Errors
- Set `UNIFI_VERIFY_SSL=false` for self-signed certificates (API and scripts will then accept the unifi.local cert).
- For production, ensure valid SSL certificates are installed
- Consider using IP address instead of hostname if certificate issues persist
### Fixing browser `ERR_CERT_AUTHORITY_INVALID` for unifi.local
The UniFi controller uses a self-signed certificate (Subject/Issuer: unifi.local), so browsers show "Your connection is not private" / `net::ERR_CERT_AUTHORITY_INVALID`.
**Option A — Quick (per session):** In Chrome/Edge click **Advanced****Proceed to unifi.local (unsafe)**. In Firefox: **Advanced****Accept the Risk and Continue**.
**Option B — Trust the cert on this machine (stops the warning for all browsers):**
1. Copy the UniFi certificate into the system CA store (cert is in the repo for convenience):
```bash
# Debian/Ubuntu (WSL, etc.)
sudo cp config/certs/unifi.local.crt /usr/local/share/ca-certificates/unifi-local.crt
sudo update-ca-certificates
```
2. Restart your browser completely (close all windows), then open `https://unifi.local` again.
**Option C — Use IP in the URL:** If your UDM is at e.g. `192.168.0.1`, use `https://192.168.0.1` instead of `https://unifi.local`. The same self-signed cert may still trigger a warning unless you trust it (Option B) or use Option A.
## Security Considerations
- **Never commit API keys or passwords to version control**
- Store credentials only in **`.env`** (repo root), **`unifi-api/.env`**, or **`~/.env`** (all excluded from git). Scripts like `curl-sites.sh` and `create-firewall-rules.sh` read `UNIFI_API_KEY` from those locations (in that order; later overrides). The `unifi-api` package also reads from `unifi-api/.env` when you run `pnpm unifi:cli`.
- **If you pasted an API key in chat, a ticket, or anywhere else:** revoke it in UniFi (Settings → System → API / Integrations) and create a new key, then put only the new key in your local `.env`.
- Use API keys (Official API) when possible for better security
- Rotate API keys periodically
- Use SSL verification (`UNIFI_VERIFY_SSL=true`) in production
## Production SSL Certificate Setup
### Current Development Setup
Currently using `NODE_TLS_REJECT_UNAUTHORIZED=0` for development with self-signed certificates. This is acceptable for development but **should not be used in production**.
### Production Recommendations
For production environments:
1. **Install Proper SSL Certificates**
- Use Let's Encrypt or another trusted Certificate Authority (CA)
- Install certificates on your UDM Pro
- Ensure certificates are properly configured and auto-renewing
2. **Enable SSL Verification**
```bash
UNIFI_VERIFY_SSL=true
```
Update your `~/.env` file to enable SSL verification after certificates are installed.
3. **Alternative: Use IP Addresses**
- If certificate issues persist, use IP addresses instead of hostnames
- Note: Less secure, but may be necessary for self-signed certificates in internal networks
- Example: `UNIFI_UDM_URL=https://192.168.0.1` instead of `https://udm.local`
### SSL Certificate Installation on UDM Pro
Refer to Ubiquiti documentation for installing SSL certificates on UDM Pro:
- UniFi OS documentation: [help.ui.com](https://help.ui.com)
- UDM Pro user guide and configuration instructions
- Ubiquiti community forums for community-sourced guides
### Removing Development SSL Workaround
Once proper SSL certificates are installed:
1. Set `UNIFI_VERIFY_SSL=true` in `~/.env`
2. Remove `NODE_TLS_REJECT_UNAUTHORIZED=0` from any scripts or environment
3. Test connectivity: `./scripts/unifi/check-health.sh`
4. Verify SSL certificate is trusted: `curl -v https://your-udm-ip`
## Next Steps
- See [UNIFI_ENDPOINTS_REFERENCE.md](./UNIFI_ENDPOINTS_REFERENCE.md) for complete endpoint documentation
- Review [unifi-api README](../../unifi-api/README.md) for API client usage
- Review [mcp-unifi README](../../mcp-unifi/README.md) for MCP server usage