Fast Python gateway for extracting metadata, thumbnails, direct download links, and HLS streaming support from TeraBox share URLs.
Project description
TeraBox Gateway API
Fast Python gateway for extracting metadata, thumbnails, direct download links, and HLS streaming support from TeraBox share URLs.
This project is available as a PyPI package for direct integration into your Python applications, or it can be run as a standalone API gateway. It provides:
- PyPI Library Integration: Easily import package modules like the client directly in your Python code.
- Interactive Swagger Playground: Access
/docsfor testing endpoints directly in the browser. - Web API: Exposes endpoints for listing files and retrieving direct links.
- Unified Cloudflare Worker Proxy: Optimized TeraBox API access handling token resolution.
- Vercel-Ready Deployment: Ready-to-go serverless hosting configuration.
- Flexible Cookie Authentication: Simple string or JSON formatting for upstream auth.
The API uses Flask 3.x native async support with aiohttp for asynchronous requests and leverages a unified Cloudflare Worker proxy with mode-based operations for efficient TeraBox API interaction.
Features
-
Web API Endpoints:
GET /docs: Interactive Swagger UI documentation playground (API playground)GET /swagger.json: OpenAPI 3.0.0 schema specificationGET /api: Unified endpoint - file listing with short links (resolve withresolve=true), and proxy modes (resolve, lookup, stream, page, api, segment, health)GET /admin/*: Path-based admin endpoints to inspect database records and analytics (overview, shares, files, thumbnails, kv/entry)GET /health: Simple health check endpointGET /: API information and status
-
Flexible Cookie Configuration:
- Simple string format: Just paste your
ndustoken - Full JSON format: Supports multiple cookie fields
- Environment variable or file-based configuration
- Simple string format: Just paste your
-
Rate Limiting:
- Per-IP sliding-window rate limiter
- Configurable limits via environment variables
- Returns
429 Too Many RequestswithRetry-Afterheader
-
Response Caching:
- In-memory LRU cache with TTL expiration
- Reduces redundant upstream requests on repeated lookups
- Configurable TTL and max cache size
-
Production Ready:
- CORS enabled for browser clients
- Vercel deployment configuration included
- Error handling with detailed logging
Directory Structure
terabox-gateway/
├── .github/
│ └── workflows/
│ └── publish.yml # GitHub Actions workflow for PyPI publishing
├── src/
│ └── terabox_gateway/
│ ├── __init__.py # Package initialization
│ ├── api.py # Main Flask application and API routes
│ ├── config.py # Configuration and constants (proxy URLs, headers)
│ ├── terabox_client.py # TeraBox API client with unified proxy integration
│ ├── utils.py # Utility functions (validation, formatting)
│ ├── rate_limiter.py # Per-IP sliding-window rate limiter
│ ├── cache.py # In-memory LRU cache with TTL expiration
│ ├── main.py # Package entrypoint for CLI command
│ └── swagger/
│ └── swagger.json # Swagger OpenAPI JSON specification
├── .env # Environment variables (not tracked in git)
├── .env.example # Example environment configuration
├── pyproject.toml # PyPI package build configuration
├── requirements.txt # Python dependencies
├── vercel.json # Vercel deployment configuration
├── tboxproxy_usage.md # Unified proxy API documentation
├── main.py # Root entry point for running Flask locally or on Vercel
├── .gitignore # Git ignore file
├── LICENSE # MIT License
└── README.md # This file
Requirements
- Python 3.8+
- Dependencies:
Flask[async]>=3.1,<4Werkzeug>=3.1,<4aiohttp>=3.8,<4
Installation
You can install terabox-gateway in two ways:
Option 1: Install from PyPI (Recommended)
pip install terabox-gateway
Option 2: Local Installation (For Development)
Clone this repository and install the dependencies locally:
pip install -r requirements.txt
Quick Start
1. Configure Cookies
Create a .env file in the project root (copy from .env.example):
cp .env.example .env
Add your TeraBox ndus cookie token to .env:
Option 1: Simple String Format (Recommended)
COOKIE_JSON=YdPCtvYteHui3XC6demNk-M2HgRzVrnh0txZQG6X
Option 2: Full JSON Format
COOKIE_JSON={"ndus": "YdPCtvYteHui3XC6demNk-M2HgRzVrnh0txZQG6X", "other": "value"}
The API automatically detects the format and handles it accordingly.
2. Run the API Locally
Depending on how you installed the package:
If installed from PyPI: Simply run the CLI command:
terabox-gateway
If running from source:
Run the root main.py entrypoint:
python main.py
The server will start at:
http://localhost:5000http://0.0.0.0:5000(accessible from network)
Getting Your TeraBox Cookies
The API requires a valid ndus cookie to authenticate with TeraBox:
- Log in to terabox.com or 1024terabox.com
- Open your browser's Developer Tools (press
F12) - Go to the Application or Storage tab
- Navigate to Cookies → Select the TeraBox domain
- Find the cookie named
ndusand copy its Value - Paste the value into your
.envfile as shown above
Note: Cookies expire periodically. If you start getting authentication errors, refresh your cookies.
API Usage
Endpoints
GET / - API Information
Returns metadata about the API, available endpoints, and status.
curl http://localhost:5000/
GET /health - Health Check
Simple health check endpoint that returns the current status.
curl http://localhost:5000/health
GET /docs - Interactive Swagger UI Playground
An interactive developer playground to browse endpoints and execute requests directly from the browser.
Access in browser at: http://localhost:5000/docs
GET /swagger.json - OpenAPI Specification
Exposes the OpenAPI 3.0.0 JSON schema defining the entire API.
curl http://localhost:5000/swagger.json
GET /api - Unified Endpoint (File Listing + Proxy Modes)
The /api endpoint handles all use cases in one place:
Pattern 1: File Listing with Short Download Links (Fast - Default) Retrieves file metadata and the shorter proxy-redirect links. This is the default mode and resolves in milliseconds since no slow redirect checks are run.
curl "http://localhost:5000/api?url=https://1024terabox.com/s/1LNr3tyl5pI5KUM8BecGtyQ"
Pattern 2: File Listing with Fully-Resolved Direct Download Links Retrieves file metadata and follows redirects to get the long target PCS direct download URLs.
curl "http://localhost:5000/api?url=https://1024terabox.com/s/1LNr3tyl5pI5KUM8BecGtyQ&resolve=true"
Pattern 3: Proxy Modes Direct access to the Cloudflare Worker proxy with multiple modes for different use cases.
Mode: resolve (Recommended)
Auto extract jsToken + fetch share API in one call.
curl "http://localhost:5000/api?mode=resolve&surl=abc123"
Mode: lookup (🚀 Fastest)
Query the D1 database cache directly with no upstream calls. Requires surl or fid.
curl "http://localhost:5000/api?mode=lookup&surl=abc123"
Mode: page
Proxy raw share HTML page for debugging.
curl "http://localhost:5000/api?mode=page&surl=abc123"
Mode: api
Manual share API proxy when jsToken is already known.
curl "http://localhost:5000/api?mode=api&jsToken=XYZ&shorturl=abc123"
Mode: stream
Fetch and rewrite M3U8 playlist for HLS streaming.
curl "http://localhost:5000/api?mode=stream&surl=abc123"
# Optional: specify quality
curl "http://localhost:5000/api?mode=stream&surl=abc123&type=M3U8_AUTO_720"
Mode: segment
Proxy media segments (.ts, .m4s) - used automatically by rewritten playlists.
curl "http://localhost:5000/api?mode=segment&url=ENCODED_URL"
Mode: health
Check the health status of the worker service.
curl "http://localhost:5000/api?mode=health"
Notes:
- Cookies are forwarded from client request if provided in
Cookieheader - Use
mode=resolvefor most use cases streamandsegmentmodes enable HLS video playback in browsers and players- Legacy
/api?url=...usage remains fully supported
GET /admin/* - Admin Endpoints
Path-based admin endpoints to inspect database records and analytics. All requests require authentication if configured in the worker. Pass the key using either ?key=YOUR_ADMIN_KEY or x-admin-key header.
GET /admin/overview: Summary metrics of shares and filesGET /admin/shares: Search and list resolved sharesGET /admin/files: Search and filter media filesGET /admin/kv/entry?surl=...: Lookup raw cached D1 share record
Supported TeraBox Domains
The API validates and supports the following TeraBox domains:
terabox.appteraboxshare.comterabox.com1024terabox.comteraboxlink.comterasharefile.comterafileshare.comterasharelink.com
Both http:// and https:// protocols are supported.
Integration Examples
You can easily query the gateway API using your preferred programming language. Here are examples of retrieving direct download links for a TeraBox share URL using the /api endpoint:
🐍 Python (using requests)
import requests
def get_direct_links(gateway_url, share_url):
response = requests.get(
f"{gateway_url}/api",
params={"url": share_url}
)
if response.status_code == 200:
data = response.json()
if data.get("status") == "success":
for file in data.get("files", []):
print(f"File: {file['filename']}")
print(f"Size: {file['size']}")
print(f"Direct Link: {file['download_link']}\n")
else:
print("Error:", data.get("message"))
else:
print("HTTP Error:", response.status_code)
# Example Usage:
# get_direct_links("http://localhost:5000", "https://teraboxshare.com/s/1LNr3tyl5pI5KUM8BecGtyQ")
🟨 JavaScript (Node.js / Browser)
async function getDirectLinks(gatewayUrl, shareUrl) {
try {
const response = await fetch(`${gatewayUrl}/api?url=${encodeURIComponent(shareUrl)}`);
const data = await response.json();
if (response.ok && data.status === 'success') {
data.files.forEach(file => {
console.log(`File: ${file.filename}`);
console.log(`Size: ${file.size}`);
console.log(`Direct Link: ${file.download_link}\n`);
});
} else {
console.error('Error:', data.message || 'Failed to resolve links');
}
} catch (error) {
console.error('Fetch Error:', error);
}
}
// Example Usage:
// getDirectLinks("http://localhost:5000", "https://teraboxshare.com/s/1LNr3tyl5pI5KUM8BecGtyQ");
🐹 Go
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
)
type FileItem struct {
Filename string `json:"filename"`
Size string `json:"size"`
DownloadLink string `json:"download_link"`
}
type APIResponse struct {
Status string `json:"status"`
Files []FileItem `json:"files"`
}
func getDirectLinks(gatewayURL, shareURL string) {
resp, err := http.Get(fmt.Sprintf("%s/api?url=%s", gatewayURL, url.QueryEscape(shareURL)))
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
var result APIResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
fmt.Println("Decode Error:", err)
return
}
if result.Status == "success" {
for _, file := range result.Files {
fmt.Printf("File: %s\nSize: %s\nDirect Link: %s\n\n", file.Filename, file.Size, file.DownloadLink)
}
} else {
fmt.Println("API returned an error status")
}
}
func main() {
// getDirectLinks("http://localhost:5000", "https://teraboxshare.com/s/1LNr3tyl5pI5KUM8BecGtyQ")
}
Environment Variables
You can configure the API using environment variables in your .env file:
| Variable | Description | Default |
|---|---|---|
COOKIE_JSON |
TeraBox cookies (simple string or JSON) | - |
TERABOX_COOKIES_JSON |
Alternative: JSON string of cookies | - |
TERABOX_COOKIES_FILE |
Alternative: Path to cookies JSON file | - |
HOST |
Server host address | 0.0.0.0 |
PORT |
Server port | 5000 |
FLASK_DEBUG |
Enable Flask debug mode (1 or 0) |
0 |
RATE_LIMIT |
Max requests per window per IP | 30 |
RATE_WINDOW |
Rate limit window size in seconds | 60 |
CACHE_TTL |
Cache entry time-to-live in seconds | 60 |
CACHE_MAX_SIZE |
Maximum number of cached entries | 500 |
Cookie Priority:
COOKIE_JSON(from.env)TERABOX_COOKIES_JSONTERABOX_COOKIES_FILE
Technical Implementation
Unified Proxy Architecture
The TeraBox Gateway uses a unified Cloudflare Worker proxy for all TeraBox API interactions. This architecture provides:
- Reduced Network Overhead: 33-50% fewer HTTP requests (1-2 instead of 2-3 per request)
- Server-Side Token Handling: Automatic jsToken extraction handled by the proxy
- Mode-Based Operations: Three distinct modes for different use cases
Proxy Modes
The unified proxy supports 5 distinct modes, all accessible via the /proxy endpoint:
1. mode=resolve (Recommended)
- Automatically fetches the share page, extracts jsToken, and returns file metadata
- Single HTTP call for most common use cases
- Returns JSON with file list and metadata
- Best for production use
2. mode=page
- Returns raw HTML of TeraBox share page
- Useful for debugging and manual token extraction
- Returns HTML content
3. mode=api
- Direct API access when jsToken is already known
- Used for directory listings and advanced scenarios
- Returns JSON from TeraBox API
4. mode=stream
- Fetches M3U8 playlist and rewrites segment URLs
- Requires
surlparameter (short URL ID) - Optional
typeparameter for quality selection (default: M3U8_AUTO_360) - Enables HLS video streaming in browsers and players
- Returns modified M3U8 playlist
5. mode=segment
- Proxies individual video segments (.ts, .m4s files)
- Automatically used by rewritten playlists
- Returns binary media data
Request Flow
Client Request → Flask API → Unified Proxy (mode=resolve) → TeraBox API → Response
↓
(if directory)
↓
Unified Proxy (mode=api) → Directory Contents → Response
Key Benefits:
- ✅ Simplified codebase with no manual token parsing
- ✅ Faster response times due to fewer roundtrips
- ✅ More reliable token extraction (handled server-side)
- ✅ Better error handling and reporting
For detailed proxy documentation, see tboxproxy_usage.md.
Deployment
Deploy to Vercel
The easiest way to deploy your own instance of the TeraBox Gateway API is to use Vercel.
Click the button below to clone and deploy this repository with one click:
Alternatively, deploy manually using the Vercel CLI:
-
Install Vercel CLI (optional):
npm i -g vercel
-
Deploy:
vercel
-
Set environment variables in Vercel dashboard:
- Go to your project settings
- Add
COOKIE_JSONwith yourndustoken value
The vercel.json configuration is already set up for you.
Troubleshooting
Common Issues
Error 400141 - Verification Required
- The link is password-protected
- Solution: Add
&pwd=PASSWORDparameter to your request
HTTP 5xx Errors
- Your cookies may have expired
- Solution: Update your
nduscookie following the steps above
No Direct Link Returned
- Cookies are invalid or expired
- The share link itself has expired
- Solution: Refresh cookies or verify the link is still active
"Cookies not loaded" Warning
.envfile is missing orCOOKIE_JSONis not set- Solution: Create
.envfile and add yourndustoken
Authentication Failures
- The
ndustoken is invalid or malformed - Solution: Copy the token again from your browser, ensuring no extra spaces
Development
Running in Debug Mode
Set FLASK_DEBUG=1 in your .env file:
FLASK_DEBUG=1
This enables:
- Auto-reload on code changes
- Detailed error pages
- Interactive debugger
Logging
The API uses Python's logging module with INFO level by default. Logs include:
- Request URLs and parameters
- Cookie loading status (format detection)
- API responses and errors
- Share page tokens and authentication status
License
This project is licensed under the MIT License. See the LICENSE file for details.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Contact
For questions or support, contact @Saahiyo
Acknowledgments
- Built with Flask 3.x (native async) and aiohttp for efficient async operations
- Unified Cloudflare Worker proxy for optimized API access
- Designed for seamless Vercel deployment
- Supports multiple TeraBox domains and share URL formats
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file terabox_gateway-2.0.2.tar.gz.
File metadata
- Download URL: terabox_gateway-2.0.2.tar.gz
- Upload date:
- Size: 31.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ab649b823894acd0f78e1fb33315ee48d189854fbf974c5c15a34d7841460deb
|
|
| MD5 |
8ab42cb5443eccb801c200c8868d58b4
|
|
| BLAKE2b-256 |
13b4b733991e36118c4222928b05c9bef0fb2272bf318d10cd0a281537788bbb
|
Provenance
The following attestation bundles were made for terabox_gateway-2.0.2.tar.gz:
Publisher:
publish.yml on saahiyo/terabox-gateway
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
terabox_gateway-2.0.2.tar.gz -
Subject digest:
ab649b823894acd0f78e1fb33315ee48d189854fbf974c5c15a34d7841460deb - Sigstore transparency entry: 2013158035
- Sigstore integration time:
-
Permalink:
saahiyo/terabox-gateway@753d0e1469c81dc983e989a0e8257c4076e223d5 -
Branch / Tag:
refs/tags/v2.0.2 - Owner: https://github.com/saahiyo
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@753d0e1469c81dc983e989a0e8257c4076e223d5 -
Trigger Event:
release
-
Statement type:
File details
Details for the file terabox_gateway-2.0.2-py3-none-any.whl.
File metadata
- Download URL: terabox_gateway-2.0.2-py3-none-any.whl
- Upload date:
- Size: 27.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
809428de300ee3da49685422f3425dd12b56e2e99a21847fe31468943efb2f4c
|
|
| MD5 |
fd5ec24cf992cc582a4cabaf6907a6a6
|
|
| BLAKE2b-256 |
58b5dbd5336db8b9e6b93566bfa761b2bc4eadd059471c7358293f3c5a45fa41
|
Provenance
The following attestation bundles were made for terabox_gateway-2.0.2-py3-none-any.whl:
Publisher:
publish.yml on saahiyo/terabox-gateway
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
terabox_gateway-2.0.2-py3-none-any.whl -
Subject digest:
809428de300ee3da49685422f3425dd12b56e2e99a21847fe31468943efb2f4c - Sigstore transparency entry: 2013158080
- Sigstore integration time:
-
Permalink:
saahiyo/terabox-gateway@753d0e1469c81dc983e989a0e8257c4076e223d5 -
Branch / Tag:
refs/tags/v2.0.2 - Owner: https://github.com/saahiyo
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@753d0e1469c81dc983e989a0e8257c4076e223d5 -
Trigger Event:
release
-
Statement type: