Spaces:
Paused
Paused
Commit Β·
be8c7bb
0
Parent(s):
feat: initial HuggingClip release
Browse filesPaperclip AI agent orchestration platform on Hugging Face Spaces.
- Dockerfile: node:lts-trixie-slim, builds Paperclip from source
- start.sh: orchestrate postgres β restore β proxy β sync β launch
- health-server.js: port 7861 gateway, dashboard, proxy to 3100
- paperclip-sync.py: pg_dump + tarball backup/restore via HF Dataset
- cloudflare-proxy: bypass HF Spaces outbound network blocks
- docker-compose.yml: local dev environment
- .env.example: full configuration reference
- README.md: deployment guide with quick start
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Files changed (16)
- .env.exampleAdded+127
- CHANGELOG.mdAdded+57
- CODE_OF_CONDUCT.mdAdded+30
- CONTRIBUTING.mdAdded+67
- DockerfileAdded+80
- LICENSEAdded+28
- README.mdAdded+407
- SECURITY.mdAdded+62
- cloudflare-proxy-setup.pyAdded+253
- cloudflare-proxy.jsAdded+375
- cloudflare-worker.jsAdded+103
- docker-compose.ymlAdded+91
- health-server.jsAdded+683
- paperclip-sync.pyAdded+494
- setup-uptimerobot.shAdded+84
- start.shAdded+202
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127# ============================================================================# HuggingClip - Paperclip on Hugging Face Spaces# Configuration Reference# ============================================================================
# ============================================================================# Hugging Face Integration (REQUIRED for backup persistence)# ============================================================================
# Your Hugging Face API token (needed for backup/restore)# Get it from: https://huggingface.co/settings/tokensHF_TOKEN=hf_xxxxxxxxxxxxxxxxxxxxxxxxxxxx
# Your Hugging Face username (optional, auto-detected from token if not set)# HF_USERNAME=your-username
# ============================================================================# Paperclip Core Configuration# ============================================================================
# PostgreSQL connection string# Format: postgres://user:password@host:port/databaseDATABASE_URL=postgres://postgres:paperclip@localhost:5432/paperclip
# Paperclip API portPORT=3100
# Serve the Paperclip UI (true/false)SERVE_UI=true
# Node.js environment (development/production)NODE_ENV=production
# Server bind addressHOST=0.0.0.0
# Paperclip home directory for config/data storagePAPERCLIP_HOME=/paperclip
# Deployment mode (local/authenticated)# Use 'authenticated' for production with Better AuthPAPERCLIP_DEPLOYMENT_MODE=authenticated
# ============================================================================# Paperclip Agent Providers (varies by setup)# ============================================================================
# If using Claude as an agent providerCLAUDE_API_KEY=sk-ant-xxxxxxxxxxxxxxxxxxxxxxxxxxxx
# For other LLM providers (OpenAI, etc.)# LLM_API_KEY=your-api-key
# Allow Claude Code to use all models (default: restricted)OPENCODE_ALLOW_ALL_MODELS=true
# ============================================================================# Cloudflare Proxy (Optional - for bypassing HF Spaces network blocks)# ============================================================================
# Cloudflare API token for setting up outbound proxy# Get it from: https://dash.cloudflare.com/profile/api-tokens# CLOUDFLARE_WORKERS_TOKEN=xxx
# Your Cloudflare account ID# CLOUDFLARE_ACCOUNT_ID=xxx
# ============================================================================# Database Backup Configuration# ============================================================================
# Sync interval in seconds (how often to backup to HF Dataset)SYNC_INTERVAL=180
# Maximum file size for individual backups (in bytes)# Default: 52428800 (50MB)SYNC_MAX_FILE_BYTES=52428800
# Name of the HF Dataset to store backups# Will be created as: {HF_USERNAME}/{BACKUP_DATASET_NAME}BACKUP_DATASET_NAME=paperclip-backup
# ============================================================================# Authentication & Security# ============================================================================
# Better Auth secret for user authentication# Generate a random secret: openssl rand -base64 32BETTER_AUTH_SECRET=your-random-secret-here-minimum-32-characters
# Optional: Discord webhook for admin notifications# DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...
# ============================================================================# Monitoring & Uptime# ============================================================================
# Optional: Webhook URL for restart/failure alerts# Useful for UptimeRobot or similar monitoring services# WEBHOOK_URL=https://uptime-robot-webhook-url
# ============================================================================# Telemetry & Privacy# ============================================================================
# Disable Paperclip telemetry (1 = disabled)PAPERCLIP_TELEMETRY_DISABLED=1
# Respect Do Not Track headerDO_NOT_TRACK=1
# ============================================================================# Development-Only Variables (for local testing)# ============================================================================
# Debug logging (set to anything to enable)# DEBUG=1
# ============================================================================# HuggingFace Spaces Specific# ============================================================================
# These are automatically set by HF Spaces:# SPACE_ID: your-space-id# SPACE_PERSISTENT_DIRECTORY: /tmp (ephemeral, 50GB)# SPACE_AUTHOR_NAME: your-hf-username# SPACE_RUNTIME: docker123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.0.0] - 2026-04-27
### Added
- Initial release of HuggingClip- Paperclip AI agent orchestration platform deployment on Hugging Face Spaces- Automatic database persistence via Hugging Face Dataset backup/restore- Health monitoring dashboard with real-time status- PostgreSQL backup and restore functionality- Health check endpoint for uptime monitoring- Reverse proxy for Paperclip API and UI- Environment variable configuration system- Cloudflare proxy integration for network-restricted API providers- Docker and Docker Compose support for local development- Graceful shutdown with data synchronization- UptimeRobot integration for preventing Space sleep- Comprehensive documentation and guides- MIT License
### Features
- **One-click Deploy**: Easy deployment to Hugging Face Spaces- **Data Persistence**: Automatic backup and restore of database- **Health Monitoring**: Dashboard showing service status and metrics- **Flexible Configuration**: Environment variable-based configuration- **Network Bypass**: Optional Cloudflare proxy for blocked domains- **Local Development**: Docker Compose setup for testing- **Extensible**: Based on Paperclip's plugin architecture
### Documentation
- README.md with deployment and usage guides- .env.example with comprehensive configuration reference- SECURITY.md with security best practices- CONTRIBUTING.md with contribution guidelines- CODE_OF_CONDUCT.md with community guidelines
## [Unreleased]
### Planned
- Multi-Space federation support- Backup versioning and rotation policies- Advanced monitoring integrations (Prometheus, Grafana)- One-click restore from specific backup snapshots- CLI tool for local backup management- Multi-database support (external PostgreSQL)- Kubernetes deployment manifests- Better Auth integration improvements- Agent plugin marketplace123456789101112131415161718192021222324252627282930# Code of Conduct
## Our Pledge
We pledge to make participation in our project a harassment-free experience for everyone.
## Our Standards
**Positive behavior:**- Using welcoming and inclusive language- Being respectful of differing viewpoints- Gracefully accepting constructive criticism- Focusing on what is best for the community
**Unacceptable behavior:**- Trolling, insulting, or derogatory comments- Harassment in any form- Publishing others' private information without permission
## Enforcement
Project maintainers may remove, edit, or reject contributions that violate this Code of Conduct.
## Scope
Applies in all project spaces and public spaces when representing the project.
## Attribution
Adapted from the [Contributor Covenant](https://www.contributor-covenant.org/), version 2.1.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667# Contributing to HuggingClip
## How to Contribute
### Bug Reports
1. Check existing [issues](https://github.com/somratpro/HuggingClip/issues) first2. Create a new issue with: - Clear title and description - Steps to reproduce - Expected vs actual behavior - Environment details (OS, Docker version, HF Space tier)
### Pull Requests
1. Fork the repository2. Create a feature branch: `git checkout -b feature/your-feature`3. Make changes and test locally with `docker-compose up`4. Commit: `git commit -m "feat: description of change"`5. Push and open a Pull Request
### Local Development Setup
```bash# Clonegit clone https://github.com/somratpro/HuggingClip.gitcd HuggingClip
# Configurecp .env.example .env# Edit .env with your HF_TOKEN and any provider keys
# Build and startdocker-compose up --build
# Test healthcurl http://localhost:7861/health
# Access dashboardopen http://localhost:7861/```
### File Overview
| File | Purpose ||------|---------|| `Dockerfile` | Container build definition || `start.sh` | Orchestration script (startup sequence) || `health-server.js` | Port 7861 gateway + dashboard || `paperclip-sync.py` | PostgreSQL backup/restore to HF Dataset || `cloudflare-proxy.js` | Outbound proxy for blocked domains || `cloudflare-proxy-setup.py` | Auto-provision Cloudflare Worker || `docker-compose.yml` | Local development setup |
### Commit Convention
Follow [Conventional Commits](https://www.conventionalcommits.org/):
- `feat:` New features- `fix:` Bug fixes- `docs:` Documentation changes- `refactor:` Code restructuring- `chore:` Maintenance tasks
## Questions?
Open an issue or check the [Paperclip docs](https://docs.paperclip.ing).1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980# Stage 1: Build Paperclip from sourceFROM node:lts-trixie-slim AS paperclip-builder
WORKDIR /build
RUN apt-get update && apt-get install -y \ git \ python3 \ python3-pip \ && rm -rf /var/lib/apt/lists/*
# Clone Paperclip repositoryRUN git clone https://github.com/paperclipai/paperclip.git . && \ git checkout main
# Install pnpmRUN npm install -g pnpm@9.15.2
# Install dependenciesRUN pnpm install --frozen-lockfile
# Build PaperclipRUN pnpm build
# Stage 2: RuntimeFROM node:lts-trixie-slim
WORKDIR /app
# Install system dependenciesRUN apt-get update && apt-get install -y \ curl \ postgresql-client \ postgresql \ postgresql-contrib \ python3 \ python3-pip \ python3-venv \ git \ && rm -rf /var/lib/apt/lists/*
# Create PostgreSQL data directoryRUN mkdir -p /var/run/postgresql && chown postgres:postgres /var/run/postgresql
# Install Node dependencies for health-serverRUN npm install -g express@4.18.2 cors@2.8.5 morgan@1.10.0 uuid@9.0.1
# Install Python dependencies for syncRUN pip install --no-cache-dir huggingface_hub==0.24.5 PyYAML==6.0.1
# Copy Paperclip build from builderCOPY --from=paperclip-builder /build/dist /app/paperclipCOPY --from=paperclip-builder /build/package.json /app/paperclip/COPY --from=paperclip-builder /build/node_modules /app/paperclip/node_modules
# Copy orchestration filesCOPY start.sh /app/COPY health-server.js /app/COPY paperclip-sync.py /app/COPY cloudflare-proxy.js /app/COPY cloudflare-proxy-setup.py /app/COPY cloudflare-worker.js /app/COPY setup-uptimerobot.sh /app/
# Make scripts executableRUN chmod +x /app/start.sh /app/setup-uptimerobot.sh
# Create persistent storage directoryRUN mkdir -p /paperclip /var/lib/postgresql/data && \ chown -R postgres:postgres /var/lib/postgresql/data /paperclip
# Set secure file permissionsRUN umask 0077
EXPOSE 7861
HEALTHCHECK --interval=30s --timeout=10s --start-period=90s --retries=3 \ CMD curl -f http://localhost:7861/health || exit 1
CMD ["/app/start.sh"]12345678910111213141516171819202122232425262728MIT License
Copyright (c) 2026 HuggingClip Contributors
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.
---
This project builds upon:- Paperclip: https://github.com/paperclipai/paperclip (MIT License)- HuggingClaw: https://github.com/democra-ai/HuggingClaw (Apache 2.0)- Hugging8n: https://github.com/somratpro/Hugging8n (MIT License)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407# π HuggingClip
Paperclip AI Agent Orchestration Platform running on Hugging Face Spaces.
Deploy your own instance of [Paperclip](https://paperclip.ing/) β the open-source platform for orchestrating AI agents to run autonomous businesses β on Hugging Face Spaces with automatic persistent backup to Hugging Face Datasets.
**Features:**- β
Run Paperclip on HF Spaces (free tier compatible)- β
Automatic database backup to HF Dataset (survives restarts)- β
Health monitoring dashboard with real-time status- β
One-click deploy with configuration via environment variables- β
Cloudflare proxy integration (for network-restricted providers)- β
Graceful shutdown and data persistence
## Quick Start
### 1-Click Deploy (Recommended)
[Deploy to Hugging Face Spaces](https://huggingface.co/new-space?template=somratpro/HuggingClip)
Or manually:1. Create a new Space on [Hugging Face](https://huggingface.co/new-space)2. Choose **Docker** as the runtime3. Copy this repository as the source4. Configure required secrets (see **Configuration** below)5. Deploy!
### Local Development
#### Prerequisites- Docker & Docker Compose- Node.js 20+ (for direct testing)- PostgreSQL 13+ (if running outside Docker)
#### Setup
```bash# Clone repositorygit clone https://github.com/somratpro/HuggingClip.gitcd HuggingClip
# Copy environment templatecp .env.example .env
# Edit .env with your configuration# At minimum set: HF_TOKEN for backup persistence
# Start with Docker Composedocker-compose up -d
# Check healthcurl http://localhost:7861/health
# Open dashboardopen http://localhost:7861/```
## Configuration
### Required Environment Variables
| Variable | Description | Example ||----------|-------------|---------|| `HF_TOKEN` | Hugging Face API token (for backup persistence) | `hf_xxxx...` |
Get your HF token from [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens)
### Paperclip Configuration
| Variable | Default | Description ||----------|---------|-------------|| `DATABASE_URL` | `postgres://postgres:paperclip@localhost:5432/paperclip` | PostgreSQL connection string || `PORT` | `3100` | Paperclip API port || `NODE_ENV` | `production` | Node.js environment || `PAPERCLIP_HOME` | `/paperclip` | Paperclip data directory || `PAPERCLIP_DEPLOYMENT_MODE` | `authenticated` | Deployment mode (local/authenticated) |
### Agent Provider Keys
Configure API keys for your agent providers:
```bash# Claude agentsCLAUDE_API_KEY=sk-ant-xxxx...
# Other LLM providersLLM_API_KEY=xxxx...
# Allow all Claude modelsOPENCODE_ALLOW_ALL_MODELS=true```
### Backup Configuration
| Variable | Default | Description ||----------|---------|-------------|| `SYNC_INTERVAL` | `180` | Backup interval (seconds) || `SYNC_MAX_FILE_BYTES` | `52428800` | Max backup size (50MB) || `BACKUP_DATASET_NAME` | `paperclip-backup` | HF Dataset name for backups |
### Optional: Cloudflare Proxy
Enable outbound connections to blocked domains (Telegram, Discord, WhatsApp, etc.):
```bashCLOUDFLARE_WORKERS_TOKEN=xxx # From https://dash.cloudflare.com/CLOUDFLARE_ACCOUNT_ID=xxx # From Cloudflare dashboard```
See [cloudflare-proxy-setup.py](cloudflare-proxy-setup.py) for details.
### Optional: Authentication
```bashBETTER_AUTH_SECRET=your-random-secret # Generate: openssl rand -base64 32DISCORD_WEBHOOK_URL=https://... # For admin notifications```
## Deployment
### Hugging Face Spaces
1. **Create Space**: [huggingface.co/new-space](https://huggingface.co/new-space) - **Space name**: `huggingclip` - **Space type**: Public (or Private) - **Runtime**: Docker
2. **Configure Secrets**: Settings β Repository Secrets - `HF_TOKEN`: Your Hugging Face API token - `CLAUDE_API_KEY`: Claude API key (if using Claude agents) - Add any other provider keys needed
3. **Deploy**: Push to the Space repo or use the web editor
4. **Monitor**: Dashboard appears at `https://your-username-huggingclip.hf.space/`
### Docker
```bash# Builddocker build -t huggingclip .
# Rundocker run -d \ -p 7861:7861 \ -e HF_TOKEN=hf_xxxx... \ -e CLAUDE_API_KEY=sk-ant-xxxx... \ -e DATABASE_URL=postgres://... \ -v paperclip_data:/paperclip \ huggingclip```
### Docker Compose (Development)
```bashdocker-compose up -d```
## Usage
### Dashboard
Access the health monitoring dashboard at: `http://your-space-url/`
**Shows:**- Paperclip service status (running/down)- Database health & last backup timestamp- System uptime & start time- Quick links to Paperclip UI and API
### Paperclip UI
Full Paperclip interface at: `http://your-space-url/app/`
**Features:**- Create companies and organizational structures- Recruit AI agents with specific roles- Define tasks and monitor execution- View conversation logs and agent decisions- Manage budgets and costs- Approve/override agent actions
### API
Direct API access at: `http://your-space-url/api/*`
Examples:```bash# Get API statuscurl http://localhost:7861/health
# Check dashboard datacurl http://localhost:7861/dashboard/status
# Access Paperclip APIcurl http://localhost:7861/api/companies```
## Data Persistence
### Automatic Backup
HuggingClip automatically backs up your Paperclip database every 180 seconds (configurable):
1. **Database dump** - PostgreSQL SQL format2. **Paperclip data** - Config files, plugins, etc.3. **Upload to HF** - Stored in your `paperclip-backup` Dataset4. **On restart** - Data automatically restored
You can view backups at: `https://huggingface.co/datasets/your-username/paperclip-backup`
### Manual Backup
```bash# From inside containerpython3 /app/paperclip-sync.py sync```
### Manual Restore
```bash# From inside containerpython3 /app/paperclip-sync.py restore```
## Troubleshooting
### Database Connection Failed
**Problem**: "Cannot connect to PostgreSQL"
**Solution:**1. Check DATABASE_URL is correct: `postgres://user:pass@host:port/db`2. Verify PostgreSQL is running: `docker ps | grep postgres`3. Check credentials in DATABASE_URL match PostgreSQL setup4. Wait 10-30s for PostgreSQL to initialize on first startup
### Backup Not Uploading
**Problem**: "Sync status shows error"
**Solution:**1. Verify `HF_TOKEN` is set and valid2. Check HF Dataset is created: `huggingface-cli repo info datasets/your-username/paperclip-backup`3. Look at container logs: `docker logs huggingclip-app`4. Run manual backup: `python3 paperclip-sync.py sync`
### Paperclip Not Accessible
**Problem**: Can't reach http://localhost:7861/app/
**Solution:**1. Check container is running: `docker ps`2. Check ports are exposed: `docker port huggingclip-app`3. Verify port 3100 is not blocked4. Check health: `curl http://localhost:7861/health`5. Look at Paperclip logs: Search container logs for errors
### Space Keeps Restarting
**Problem**: Container exits repeatedly
**Solution:**1. Check logs: `docker logs --tail=100 huggingclip-app`2. Common causes: - Invalid DATABASE_URL - Missing required env vars - PostgreSQL not responding - Out of memory (HF free tier is limited)3. Verify all required env vars are set correctly
### Out of Memory
**Problem**: "Killed" message or container restarts
**Solution:**1. HF Spaces free tier: 2 vCPU, 16GB RAM, 50GB storage2. Reduce backup interval: `SYNC_INTERVAL=600` (every 10 min instead of 3)3. Reduce database size: Archive old agent runs and conversations4. Use upgraded HF Space (Pro) for more resources
## Architecture
### Components
1. **Health Server** (Node.js, port 7861) - Public gateway + dashboard - Proxies requests to Paperclip - Health checks for monitoring
2. **Paperclip** (Node.js, port 3100) - Main AI agent orchestration app - React UI + REST API - PostgreSQL database
3. **PostgreSQL** (port 5432) - Stores companies, agents, tasks, conversations - Embedded in container - Synced to HF Dataset
4. **Sync Worker** (Python) - Periodic backup to Hugging Face - Restore on startup - Handles database persistence
5. **Cloudflare Proxy** (Optional) - Bypasses HF Spaces network blocks - Routes outbound API calls - Auto-provisioned if token provided
### Data Flow
```ββββββββββββββββββββ Paperclip UI β (http://space-url/app/)β & REST API βββββββββββ¬βββββββββ β (port 3100) βββββββββββΌβββββββββ Every 180s βββββββββββββββββββββ Health Server ββββββββββββββββββββββΆ β Sync to HF ββ (7861) β β (PostgreSQL dump)βββββββββββ¬βββββββββ ββββββββββββββββββββ β β β βΌ β ββββββββββββββββββββββββ ββββββββββββββββββββββββββΆβ HF Dataset Backup β β paperclip-backup β βββββββββββββββββββββββββββ β β (on restart) ββββββββββββββββββββββββ βΌ ββββββββββββββ β PostgreSQL β β /paperclip β ββββββββββββββ```
## Backup Retention
HuggingClip stores only the **latest backup** in HF Dataset (`snapshots/latest.tar.gz`).
**To keep multiple backups manually:**```bash# Download backup from HFhuggingface-cli download datasets/your-username/paperclip-backup \ snapshots/latest.tar.gz --repo-type dataset
# Save a copycp latest.tar.gz paperclip-backup-$(date +%Y%m%d-%H%M%S).tar.gz```
## Monitoring
### UptimeRobot Integration
Prevent HF Spaces from sleeping (free tier auto-suspends idle Spaces):
1. Create UptimeRobot account: [uptimerobot.com](https://uptimerobot.com)2. Add monitor: `https://your-space-url/health` (HTTP check every 5 min)3. Configure alerts in HuggingClip: - `POST /dashboard/uptimerobot/setup` with webhook URL4. UptimeRobot will ping your Space regularly, preventing sleep
### Health Check
The `/health` endpoint returns JSON with full service status:
```bashcurl -s http://localhost:7861/health | jq .```
Response includes:- Service uptime- Database status- Last backup timestamp- Any errors
## Contributing
Found a bug? Want to improve HuggingClip?
1. Check [HuggingClip issues](https://github.com/somratpro/HuggingClip/issues)2. Submit PR with: - Clear description of changes - Any needed documentation updates - Test of changes locally
## License
MIT License - see [LICENSE](LICENSE) file
## Resources
- **Paperclip**: [paperclip.ing](https://paperclip.ing/) | [GitHub](https://github.com/paperclipai/paperclip)- **Documentation**: [docs.paperclip.ing](https://docs.paperclip.ing)- **HuggingClip**: [GitHub](https://github.com/somratpro/HuggingClip)
## Support
- π [Paperclip Docs](https://docs.paperclip.ing)- π¬ [Paperclip Discord](https://discord.gg/paperclipai)- π [Report Issues](https://github.com/somratpro/HuggingClip/issues)
---
Made with β€οΈ for the AI agent community1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162# Security Policy
## Supported Versions
| Version | Supported ||---------|-----------|| 1.x | β
Yes |
## Reporting a Vulnerability
**Do NOT open a public issue for security vulnerabilities.**
Email: security@somratpro.com (or create a private GitHub security advisory)
Include:- Description of the vulnerability- Steps to reproduce- Potential impact- Suggested fix (if any)
We will respond within 48 hours and aim to patch critical issues within 7 days.
## Security Best Practices
### Secrets Management
- **Never commit secrets to git** β use HF Space secrets or environment variables- `HF_TOKEN`: Store as HF Space secret, not in code- `CLAUDE_API_KEY`, `LLM_API_KEY`: Same β HF Space secrets only- `BETTER_AUTH_SECRET`: Generate strong random secret (`openssl rand -base64 32`)- Rotate tokens if accidentally exposed
### Network Security
- `umask 0077` enforced at startup β all files created owner-only- Cloudflare proxy uses shared secret for authentication- No hardcoded credentials anywhere in codebase
### Database Security
- PostgreSQL runs locally inside container β not exposed externally- HF Dataset backups are **private by default**- Backup file contains all database data β protect your HF Dataset access
### API Security
- Paperclip API runs on port 3100 (internal only)- Port 7861 exposes health dashboard and proxied access only- Configure `BETTER_AUTH_SECRET` for production authentication- Use `PAPERCLIP_DEPLOYMENT_MODE=authenticated` for public-facing deployments
### Container Security
- Based on `node:lts-trixie-slim` (minimal attack surface)- No root process execution where avoidable- Regular base image updates recommended
## Known Limitations
- HF Spaces free tier is public β anyone can access your Paperclip UI unless auth is configured- Database backup stored in HF Dataset β ensure dataset is **private**- Cloudflare Worker proxy can access proxied traffic β review before enabling123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253#!/usr/bin/env python3
import jsonimport osimport reimport secretsimport sysimport urllib.errorimport urllib.requestfrom pathlib import Path
API_BASE = "https://api.cloudflare.com/client/v4"ENV_FILE = Path("/tmp/huggingclaw-cloudflare-proxy.env")DEFAULT_ALLOWED = [ "api.telegram.org", "discord.com", "discordapp.com", "gateway.discord.gg", "status.discord.com", "web.whatsapp.com", "graph.facebook.com", "googleapis.com", "google.com", "googleusercontent.com", "gstatic.com",]
def cf_request(method: str, path: str, token: str, body: bytes | None = None, content_type: str = "application/json"): req = urllib.request.Request( f"{API_BASE}{path}", data=body, method=method, headers={ "Authorization": f"Bearer {token}", "Content-Type": content_type, }, ) with urllib.request.urlopen(req, timeout=30) as response: payload = json.loads(response.read().decode("utf-8")) if not payload.get("success"): errors = payload.get("errors") or [{"message": "Unknown Cloudflare API error"}] raise RuntimeError(errors[0].get("message", "Unknown Cloudflare API error")) return payload["result"]
def slugify(value: str) -> str: cleaned = re.sub(r"[^a-z0-9-]+", "-", value.lower()).strip("-") cleaned = re.sub(r"-{2,}", "-", cleaned) if not cleaned: cleaned = "huggingclaw-proxy" return cleaned[:63].rstrip("-")
def derive_worker_name() -> str: explicit = os.environ.get("CLOUDFLARE_WORKER_NAME", "").strip() if explicit: return slugify(explicit) space_host = os.environ.get("SPACE_HOST", "").strip() if space_host: base = space_host.replace(".hf.space", "") return slugify(f"{base}-proxy") return "huggingclaw-proxy"
def render_worker(secret_value: str, allowed_targets: list[str], allow_proxy_all: bool) -> str: allowed_json = json.dumps(allowed_targets) allow_all_js = "true" if allow_proxy_all else "false" secret_json = json.dumps(secret_value) return f"""addEventListener("fetch", (event) => {{ event.respondWith(handleRequest(event.request));}});
const PROXY_SHARED_SECRET = {secret_json};const ALLOW_PROXY_ALL = {allow_all_js};const ALLOWED_TARGETS = {allowed_json};
function isAllowedHost(hostname) {{ const normalized = String(hostname || "").trim().toLowerCase(); if (!normalized) return false; if (ALLOW_PROXY_ALL) return true; return ALLOWED_TARGETS.some( (domain) => normalized === domain || normalized.endsWith(`.${{domain}}`), );}}
async function handleRequest(request) {{ const url = new URL(request.url); const queryTarget = url.searchParams.get("proxy_target"); const targetHost = request.headers.get("x-target-host") || queryTarget;
if (PROXY_SHARED_SECRET) {{ const providedSecret = request.headers.get("x-proxy-key") || url.searchParams.get("proxy_key") || ""; if (providedSecret !== PROXY_SHARED_SECRET) {{ if (url.pathname.startsWith("/bot") && !targetHost) {{ // Allowed fallback }} else {{ return new Response("Unauthorized: Invalid proxy key", {{ status: 401 }}); }} }} }}
let targetBase = ""; if (targetHost) {{ if (!isAllowedHost(targetHost)) {{ return new Response(`Forbidden: Host ${{targetHost}} is not allowed.`, {{ status: 403 }}); }} targetBase = `https://${{targetHost}}`; }} else if (url.pathname.startsWith("/bot")) {{ targetBase = "https://api.telegram.org"; }} else {{ return new Response("Invalid request: No target host provided.", {{ status: 400 }}); }}
const cleanSearch = new URLSearchParams(url.search); cleanSearch.delete("proxy_target"); cleanSearch.delete("proxy_key"); const searchStr = cleanSearch.toString(); const targetUrl = targetBase + url.pathname + (searchStr ? `?${{searchStr}}` : ""); const headers = new Headers(request.headers); headers.delete("cf-connecting-ip"); headers.delete("cf-ray"); headers.delete("cf-visitor"); headers.delete("host"); headers.delete("x-real-ip"); headers.delete("x-target-host"); headers.delete("x-proxy-key");
const proxiedRequest = new Request(targetUrl, {{ method: request.method, headers, body: request.body, redirect: "follow", }});
try {{ return await fetch(proxiedRequest); }} catch (error) {{ return new Response(`Proxy Error: ${{error.message}}`, {{ status: 502 }}); }}}}"""
def write_env(proxy_url: str, proxy_secret: str) -> None: ENV_FILE.write_text( "\n".join( [ f'export CLOUDFLARE_PROXY_URL="{proxy_url}"', f'export CLOUDFLARE_PROXY_SECRET="{proxy_secret}"', ] ) + "\n", encoding="utf-8", ) # Belt-and-suspenders: even with umask 0077 on the parent shell, force # 0600 since the file holds the worker shared secret. try: ENV_FILE.chmod(0o600) except OSError: pass
def main() -> int: existing_url = os.environ.get("CLOUDFLARE_PROXY_URL", "").strip() existing_secret = os.environ.get("CLOUDFLARE_PROXY_SECRET", "").strip() api_token = os.environ.get("CLOUDFLARE_WORKERS_TOKEN", "").strip()
if existing_url: # Always write the env file so downstream `. $CF_PROXY_ENV_FILE` in # start.sh has CLOUDFLARE_PROXY_URL set even when no secret was # supplied. Empty secret means we send no x-proxy-key header β that # only works if the deployed worker also has no secret baked in. write_env(existing_url, existing_secret) if not existing_secret: print( "Warning: CLOUDFLARE_PROXY_URL is set but CLOUDFLARE_PROXY_SECRET " "is empty. Requests will succeed only if the deployed worker " "was built without PROXY_SHARED_SECRET; otherwise you'll see " "401 Unauthorized.", file=sys.stderr, ) return 0
if not api_token: return 0
account_id = os.environ.get("CLOUDFLARE_ACCOUNT_ID", "").strip() try: if not account_id: accounts = cf_request("GET", "/accounts", api_token) if not accounts: raise RuntimeError("No Cloudflare account available for this token.") account_id = accounts[0]["id"]
subdomain_info = cf_request( "GET", f"/accounts/{account_id}/workers/subdomain", api_token, ) subdomain = (subdomain_info or {}).get("subdomain", "").strip() if not subdomain: raise RuntimeError( "Cloudflare Workers subdomain is not configured. Enable workers.dev in your Cloudflare account first." )
worker_name = derive_worker_name() allowed_raw = os.environ.get("CLOUDFLARE_PROXY_DOMAINS", "").strip() allow_proxy_all = not allowed_raw or allowed_raw == "*" allowed_targets = DEFAULT_ALLOWED if not allowed_raw or allow_proxy_all else [ value.strip() for value in allowed_raw.split(",") if value.strip() ] proxy_secret = existing_secret or secrets.token_urlsafe(24) worker_source = render_worker(proxy_secret, allowed_targets, allow_proxy_all)
cf_request( "PUT", f"/accounts/{account_id}/workers/scripts/{worker_name}", api_token, body=worker_source.encode("utf-8"), content_type="application/javascript", ) cf_request( "POST", f"/accounts/{account_id}/workers/scripts/{worker_name}/subdomain", api_token, body=json.dumps({"enabled": True, "previews_enabled": True}).encode("utf-8"), )
proxy_url = f"https://{worker_name}.{subdomain}.workers.dev" write_env(proxy_url, proxy_secret) return 0 except urllib.error.HTTPError as error: detail = error.read().decode("utf-8", errors="replace") if error.code == 403 and '"code":9109' in detail: print( "Cloudflare proxy setup failed: invalid Workers token. " "Use a Cloudflare API Token in CLOUDFLARE_WORKERS_TOKEN " "(not a Global API Key, tunnel token, or worker secret). " "For auto-setup, it should have account-level 'Workers Scripts: Edit'. " "The setup can auto-discover your account; CLOUDFLARE_ACCOUNT_ID is not required.", file=sys.stderr, ) print(f"Cloudflare proxy setup failed: HTTP {error.code} {detail}", file=sys.stderr) return 1 except Exception as error: print(f"Cloudflare proxy setup failed: {error}", file=sys.stderr) return 1
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375/** * Cloudflare Proxy: Transparent Fix for Blocked Domains * * Patches https.request/http.request/fetch and undici to redirect traffic * for blocked hosts through a Cloudflare Worker proxy. */"use strict";
const https = require("https");const http = require("http");
// Use stderr for logs to avoid breaking child processes that communicate via stdout JSONconst log = (...args) => console.error(...args);
let PROXY_URL = process.env.CLOUDFLARE_PROXY_URL;if ( PROXY_URL && !PROXY_URL.startsWith("http://") && !PROXY_URL.startsWith("https://")) { PROXY_URL = `https://${PROXY_URL}`;}
const DEBUG = process.env.CLOUDFLARE_PROXY_DEBUG === "true";const PROXY_SHARED_SECRET = (process.env.CLOUDFLARE_PROXY_SECRET || "").trim();const PROXY_DOMAINS = process.env.CLOUDFLARE_PROXY_DOMAINS || "*";const BLOCKED_DOMAINS = PROXY_DOMAINS.split(",") .map((domain) => domain.trim()) .filter(Boolean);const PROXY_ALL = PROXY_DOMAINS === "*";
if (PROXY_URL) { try { const proxy = new URL(PROXY_URL); const originalHttpsRequest = https.request; const originalHttpRequest = http.request; const originalFetch = typeof globalThis.fetch === "function" ? globalThis.fetch.bind(globalThis) : null;
const shouldProxyHost = (hostname) => { const normalized = String(hostname || "").trim().toLowerCase(); if (!normalized) return false;
const isInternal = normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1" || normalized === "0.0.0.0" || normalized === proxy.hostname || normalized.endsWith(".hf.space") || normalized.endsWith(".huggingface.co") || normalized === "huggingface.co";
const should = PROXY_ALL ? !isInternal : BLOCKED_DOMAINS.some( (domain) => normalized === domain || normalized.endsWith(`.${domain}`), );
return should; };
const patch = (original, originalModuleName) => { return function patchedRequest(arg1, arg2, arg3) { let options = {}; let callback;
if (typeof arg1 === "string" || arg1 instanceof URL) { const url = typeof arg1 === "string" ? new URL(arg1) : arg1; options = { protocol: url.protocol, hostname: url.hostname, port: url.port, path: url.pathname + url.search, }; if (typeof arg2 === "object" && arg2 !== null) { options = { ...options, ...arg2 }; callback = arg3; } else { callback = arg2; } } else { options = { ...arg1 }; callback = arg2; }
const hostname = options.hostname || (options.host ? String(options.host).split(":")[0] : ""); const path = options.path || "/"; const headers = options.headers || {};
const shouldProxy = shouldProxyHost(hostname); const alreadyProxied = options._proxied; const hasTargetHeader = headers["x-target-host"] || headers["X-Target-Host"];
if (shouldProxy && !alreadyProxied && !hasTargetHeader) { if (DEBUG) { log( `[cloudflare-proxy] Redirecting ${originalModuleName}://${hostname}${path} -> ${proxy.hostname}`, ); }
const newOptions = { ...options }; newOptions._proxied = true; newOptions.protocol = "https:"; newOptions.hostname = proxy.hostname; newOptions.port = proxy.port || 443; newOptions.servername = proxy.hostname; delete newOptions.host; delete newOptions.agent;
newOptions.headers = { ...(options.headers || {}), host: proxy.host, "x-target-host": hostname, };
if (PROXY_SHARED_SECRET) { newOptions.headers["x-proxy-key"] = PROXY_SHARED_SECRET; }
return originalHttpsRequest.call(https, newOptions, callback); }
return original.call(this, arg1, arg2, arg3); }; };
https.request = patch(originalHttpsRequest, "https"); http.request = patch(originalHttpRequest, "http");
if (originalFetch) { globalThis.fetch = async function patchedFetch(input, init) { const request = input instanceof Request ? input : null; const urlStr = request ? request.url : String(input); let url; try { url = new URL(urlStr); } catch (e) { return originalFetch(input, init); }
const hostname = url.hostname; const shouldProxy = shouldProxyHost(hostname); let mergedHeaders; if (request) { mergedHeaders = new Headers(request.headers); } else { mergedHeaders = new Headers(init?.headers || {}); }
const alreadyProxied = mergedHeaders.has("x-target-host") || mergedHeaders.has("X-Target-Host");
if (!shouldProxy || alreadyProxied) { return originalFetch(input, init); }
if (DEBUG) { log( `[cloudflare-proxy] Redirecting fetch://${hostname}${url.pathname}${url.search} -> ${proxy.hostname}`, ); }
mergedHeaders.set("x-target-host", hostname); if (PROXY_SHARED_SECRET) { mergedHeaders.set("x-proxy-key", PROXY_SHARED_SECRET); }
const proxiedUrl = new URL(url.pathname + url.search, proxy);
const logProxyError = (promise, debugInfo) => { promise .then(r => { if (DEBUG && !r.ok) { log(`[cloudflare-proxy] Proxy HTTP ${r.status} for ${hostname}: ${r.statusText}`); } }) .catch(err => { const cause = err?.cause; const causeStr = cause ? ` | cause: ${cause?.code || cause?.message || String(cause)}` : ""; log(`[cloudflare-proxy] Proxy FAILED ${hostname}: ${err?.message}${causeStr}`); if (DEBUG && debugInfo) { log(`[cloudflare-proxy] Debug: ${debugInfo}`); } }); return promise; };
if (request) { const fetchOpts = { method: request.method, headers: mergedHeaders, redirect: request.redirect, }; if (request.body) { fetchOpts.body = request.body; fetchOpts.duplex = "half"; } return logProxyError( originalFetch(String(proxiedUrl), fetchOpts), `request-mode method=${request.method} hasBody=${!!request.body}`, ); }
// Build a fresh init: do NOT spread `init` because it may carry a // `dispatcher`/`client` pinned to the original target's connection // pool, which causes undici to throw UND_ERR_INVALID_ARG when we // change the origin. Forward only well-known fetch options. const newInit = { method: init?.method || "GET", headers: mergedHeaders, }; if (init?.body != null) { newInit.body = init.body; if (init.body instanceof ReadableStream) { newInit.duplex = init.duplex || "half"; } } if (init?.signal) newInit.signal = init.signal; if (init?.redirect) newInit.redirect = init.redirect; if (init?.credentials) newInit.credentials = init.credentials; if (init?.cache) newInit.cache = init.cache; if (init?.mode) newInit.mode = init.mode; if (init?.referrer) newInit.referrer = init.referrer; if (init?.referrerPolicy) newInit.referrerPolicy = init.referrerPolicy; if (init?.integrity) newInit.integrity = init.integrity; if (init?.keepalive != null) newInit.keepalive = init.keepalive;
const bodyType = init?.body == null ? "none" : init.body instanceof ReadableStream ? "ReadableStream" : (init.body?.constructor?.name || typeof init.body);
return logProxyError( originalFetch(String(proxiedUrl), newInit), `init-mode method=${newInit.method} body=${bodyType} initKeys=${Object.keys(init || {}).join(",")}`, ); }; }
// undici patching const patchUndiciInstance = (exports) => { if (!exports) return;
const patchDispatch = (proto, name) => { if (proto && proto.dispatch && !proto.dispatch._patched) { const origDispatch = proto.dispatch; proto.dispatch = function(options, handler) { let origin = options.origin || this.origin; if (origin && typeof origin !== 'string') { try { origin = origin.origin || origin.toString(); } catch (e) { origin = ""; } } let hostname = ""; try { hostname = new URL(String(origin)).hostname; } catch(e) { hostname = String(origin || "").split(':')[0]; }
if (hostname && shouldProxyHost(hostname)) { if (DEBUG) log(`[cloudflare-proxy] Redirecting undici ${name}.dispatch: ${hostname}${options.path || ""} -> ${proxy.hostname}`); const targetHeader = "x-target-host"; const secretHeader = "x-proxy-key";
if (Array.isArray(options.headers)) { let foundTarget = false; for (let i = 0; i < options.headers.length; i += 2) { if (String(options.headers[i]).toLowerCase() === targetHeader) { foundTarget = true; break; } } if (!foundTarget) { options.headers.push(targetHeader, hostname); if (PROXY_SHARED_SECRET) options.headers.push(secretHeader, PROXY_SHARED_SECRET); } } else { options.headers = options.headers || {}; if (options.headers instanceof Map || (typeof options.headers.set === 'function')) { options.headers.set(targetHeader, hostname); if (PROXY_SHARED_SECRET) options.headers.set(secretHeader, PROXY_SHARED_SECRET); } else { options.headers[targetHeader] = hostname; if (PROXY_SHARED_SECRET) options.headers[secretHeader] = PROXY_SHARED_SECRET; } } options.origin = `https://${proxy.hostname}`; } return origDispatch.call(this, options, handler); }; proto.dispatch._patched = true; } };
for (const key in exports) { if (exports[key] && exports[key].prototype && typeof exports[key].prototype.dispatch === 'function') { patchDispatch(exports[key].prototype, key); } }
if (exports.getGlobalDispatcher) { try { const globalDispatcher = exports.getGlobalDispatcher(); if (globalDispatcher && globalDispatcher.dispatch && !globalDispatcher.dispatch._patched) { patchDispatch(globalDispatcher, "GlobalDispatcherInstance"); } } catch (e) {} }
// Also patch Agent and other potentially unexported classes if they have dispatch if (exports.Agent && exports.Agent.prototype) patchDispatch(exports.Agent.prototype, "Agent"); if (exports.Pool && exports.Pool.prototype) patchDispatch(exports.Pool.prototype, "Pool"); if (exports.Client && exports.Client.prototype) patchDispatch(exports.Client.prototype, "Client");
if (exports.fetch && !exports.fetch._patched) { const origFetch = exports.fetch; exports.fetch = async function (input, init) { // If we are calling undici.fetch, it should use our globalThis.fetch which is patched return globalThis.fetch(input, init); }; exports.fetch._patched = true; } };
// Try to require undici immediately try { const undici = require("undici"); patchUndiciInstance(undici); } catch (e) {}
// Hook require() to patch any undici instance the moment it loads. // Match either the bare "undici" id or paths whose final package // segment IS undici (e.g. "/foo/node_modules/undici/index.js"). The // earlier substring check `id.includes("/undici/")` would also match // unrelated packages like "super-undici-x". const Module = require("module"); const originalRequire = Module.prototype.require; const UNDICI_PATH_RE = /(?:^|\/)node_modules\/undici(?:\/|$)/; Module.prototype.require = function (id) { const exports = originalRequire.apply(this, arguments); if (id === "undici" || UNDICI_PATH_RE.test(id)) { try { patchUndiciInstance(exports); } catch (e) {} } return exports; };
// Startup banner: print once across all Node spawns. Use a file marker // because every Node process (health-server, gateway, sync subprocess) // is spawned fresh from bash with NODE_OPTIONS=--require, so an env-var // marker won't propagate. /tmp is per-container so it resets on rebuild. if (DEBUG) { try { require("fs").writeFileSync("/tmp/.cf-proxy-banner-shown", "1", { flag: "wx", }); log( `[cloudflare-proxy] active (${PROXY_ALL ? "wildcard" : "list"}) -> ${proxy.hostname}`, ); } catch (_) { // marker exists β banner already shown by another process } } } catch (error) { log(`[cloudflare-proxy] Failed to initialize: ${error.message}`); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103/** * Cloudflare Worker: Universal Outbound Proxy * * Manual setup: * 1. Create a Cloudflare Worker. * 2. Paste this file and deploy it. * 3. Use the worker URL as CLOUDFLARE_PROXY_URL. * * Optional worker vars: * - PROXY_SHARED_SECRET * - ALLOWED_TARGETS * - ALLOW_PROXY_ALL */
function normalizeList(raw) { return String(raw || "") .split(",") .map((value) => value.trim().toLowerCase()) .filter(Boolean);}
export default { async fetch(request, env) { const url = new URL(request.url); const queryTarget = url.searchParams.get("proxy_target"); const targetHost = request.headers.get("x-target-host") || queryTarget; const proxySecret = ( env.PROXY_SHARED_SECRET || env.CLOUDFLARE_PROXY_SECRET || "" ).trim();
if (proxySecret) { const providedSecret = request.headers.get("x-proxy-key") || url.searchParams.get("proxy_key") || ""; if (providedSecret !== proxySecret) { // Fallback: allow Telegram requests via path without secret if it looks like a bot API call. // This is safe because it only proxies to api.telegram.org. if (url.pathname.startsWith("/bot") && !targetHost) { // Allowed } else { return new Response("Unauthorized: Invalid proxy key", { status: 401 }); } } }
const allowProxyAll = String(env.ALLOW_PROXY_ALL || "true").toLowerCase() === "true"; const allowedTargets = normalizeList( env.ALLOWED_TARGETS || "api.telegram.org,discord.com,discordapp.com,gateway.discord.gg,status.discord.com,web.whatsapp.com,graph.facebook.com,googleapis.com,google.com,googleusercontent.com,gstatic.com", );
const isAllowedHost = (hostname) => { const normalized = String(hostname || "") .trim() .toLowerCase(); if (!normalized) return false; if (allowProxyAll) return true; return allowedTargets.some( (domain) => normalized === domain || normalized.endsWith(`.${domain}`), ); };
let targetBase = ""; if (targetHost) { if (!isAllowedHost(targetHost)) { return new Response(`Forbidden: Host ${targetHost} is not allowed.`, { status: 403 }); } targetBase = `https://${targetHost}`; } else if (url.pathname.startsWith("/bot")) { targetBase = "https://api.telegram.org"; } else { return new Response("Invalid request: No target host provided.", { status: 400 }); }
const cleanSearch = new URLSearchParams(url.search); cleanSearch.delete("proxy_target"); cleanSearch.delete("proxy_key"); const searchStr = cleanSearch.toString(); const targetUrl = targetBase + url.pathname + (searchStr ? `?${searchStr}` : ""); const headers = new Headers(request.headers); headers.delete("cf-connecting-ip"); headers.delete("cf-ray"); headers.delete("cf-visitor"); headers.delete("host"); headers.delete("x-real-ip"); headers.delete("x-target-host"); headers.delete("x-proxy-key");
const proxiedRequest = new Request(targetUrl, { method: request.method, headers, body: request.body, redirect: "follow", });
try { return await fetch(proxiedRequest); } catch (error) { return new Response(`Proxy Error: ${error.message}`, { status: 502 }); } },};12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091version: '3.8'
services: # PostgreSQL database postgres: image: postgres:16-alpine container_name: huggingclip-postgres environment: POSTGRES_DB: paperclip POSTGRES_USER: postgres POSTGRES_PASSWORD: paperclip POSTGRES_INITDB_ARGS: "--encoding=UTF8" ports: - "5432:5432" volumes: - postgres_data:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres"] interval: 10s timeout: 5s retries: 5 networks: - huggingclip-network
# HuggingClip application paperclip: build: context: . dockerfile: Dockerfile container_name: huggingclip-app depends_on: postgres: condition: service_healthy environment: # Database DATABASE_URL: postgres://postgres:paperclip@postgres:5432/paperclip
# Paperclip config PORT: 3100 SERVE_UI: "true" NODE_ENV: development HOST: 0.0.0.0 PAPERCLIP_HOME: /paperclip PAPERCLIP_DEPLOYMENT_MODE: local
# Agent providers (add your keys here) # CLAUDE_API_KEY: ${CLAUDE_API_KEY:-} # LLM_API_KEY: ${LLM_API_KEY:-}
# HF Backup (optional for local testing) HF_TOKEN: ${HF_TOKEN:-} HF_USERNAME: ${HF_USERNAME:-} SYNC_INTERVAL: "180" BACKUP_DATASET_NAME: paperclip-backup-dev
# Cloudflare (optional) # CLOUDFLARE_WORKERS_TOKEN: ${CLOUDFLARE_WORKERS_TOKEN:-} # CLOUDFLARE_ACCOUNT_ID: ${CLOUDFLARE_ACCOUNT_ID:-}
# Telemetry PAPERCLIP_TELEMETRY_DISABLED: "1" DO_NOT_TRACK: "1"
ports: - "7861:7861" # Public health server + dashboard - "3100:3100" # Direct Paperclip access (development only) volumes: - paperclip_data:/paperclip - ./paperclip-sync.py:/app/paperclip-sync.py - ./health-server.js:/app/health-server.js - ./start.sh:/app/start.sh healthcheck: test: ["CMD", "curl", "-f", "http://localhost:7861/health"] interval: 30s timeout: 10s retries: 3 start_period: 90s networks: - huggingclip-network cap_add: - NET_ADMIN # For potential network utilities
volumes: postgres_data: driver: local paperclip_data: driver: local
networks: huggingclip-network: driver: bridge123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683const express = require('express');const cors = require('cors');const morgan = require('morgan');const fs = require('fs');const path = require('path');const { promisify } = require('util');const http = require('http');
const app = express();const PORT = process.env.PORT || 7861;const PAPERCLIP_HOST = process.env.HOST || '127.0.0.1';const PAPERCLIP_PORT = 3100;
// Middlewareapp.use(cors());app.use(morgan('combined'));app.use(express.json());app.use(express.urlencoded({ extended: true }));
// ============================================================================// Health Check Endpoint// ============================================================================app.get('/health', async (req, res) => { try { const syncStatus = readSyncStatus(); const now = Math.floor(Date.now() / 1000); const uptime = process.uptime();
// Try to check if Paperclip is responding const paperclipStatus = await checkPaperclipHealth();
res.status(200).json({ status: 'healthy', timestamp: new Date().toISOString(), uptime: Math.floor(uptime), services: { healthServer: { status: 'running', port: PORT, uptime: Math.floor(uptime) }, paperclip: { status: paperclipStatus.status, port: PAPERCLIP_PORT, url: `http://${PAPERCLIP_HOST}:${PAPERCLIP_PORT}` }, database: { status: syncStatus.db_status || 'unknown', lastSync: syncStatus.last_sync_time || null, lastSyncError: syncStatus.last_error || null } }, backup: { enabled: process.env.SYNC_DISABLED !== 'true', interval: process.env.SYNC_INTERVAL || 180, lastSync: syncStatus.last_sync_time, nextSync: syncStatus.last_sync_time ? new Date((syncStatus.last_sync_time + (parseInt(process.env.SYNC_INTERVAL || 180) * 1000))).toISOString() : null } }); } catch (error) { res.status(503).json({ status: 'unhealthy', error: error.message, timestamp: new Date().toISOString() }); }});
// ============================================================================// Dashboard Route// ============================================================================app.get('/', (req, res) => { res.send(getDashboardHTML());});
app.get('/dashboard/', (req, res) => { res.send(getDashboardHTML());});
app.get('/dashboard/status', (req, res) => { const syncStatus = readSyncStatus(); const uptime = process.uptime();
res.json({ uptime: Math.floor(uptime), startTime: new Date(Date.now() - uptime * 1000).toISOString(), syncStatus: syncStatus, environment: { syncDisabled: process.env.SYNC_DISABLED === 'true', syncInterval: process.env.SYNC_INTERVAL || 180, paperclipHome: process.env.PAPERCLIP_HOME || '/paperclip' } });});
// ============================================================================// UptimeRobot Setup Route// ============================================================================app.post('/dashboard/uptimerobot/setup', (req, res) => { const { webhookUrl } = req.body;
if (!webhookUrl) { return res.status(400).json({ error: 'webhookUrl required' }); }
// Store webhook URL in environment or file process.env.WEBHOOK_URL = webhookUrl;
res.json({ success: true, message: 'UptimeRobot webhook configured', details: 'Health checks will now notify UptimeRobot to prevent sleep' });});
// ============================================================================// Reverse Proxy Routes// ============================================================================
// Proxy all /app/* requests to Paperclipapp.all('/app/*', async (req, res) => { const targetPath = req.path.replace('/app', '') || '/'; const targetUrl = `http://${PAPERCLIP_HOST}:${PAPERCLIP_PORT}${targetPath}`;
try { const response = await proxyRequest( req.method, targetUrl, req.headers, req.body );
// Copy response headers Object.keys(response.headers).forEach(key => { res.setHeader(key, response.headers[key]); });
res.status(response.statusCode).send(response.body); } catch (error) { console.error(`Proxy error: ${error.message}`); res.status(503).json({ error: 'Paperclip service unavailable', details: error.message }); }});
// Proxy all /api/* requests to Paperclipapp.all('/api/*', async (req, res) => { const targetPath = req.path; const targetUrl = `http://${PAPERCLIP_HOST}:${PAPERCLIP_PORT}${targetPath}`;
try { const response = await proxyRequest( req.method, targetUrl, req.headers, req.body );
Object.keys(response.headers).forEach(key => { res.setHeader(key, response.headers[key]); });
res.status(response.statusCode).send(response.body); } catch (error) { console.error(`API proxy error: ${error.message}`); res.status(503).json({ error: 'Paperclip API unavailable', details: error.message }); }});
// ============================================================================// Default Route - Redirect to Dashboard// ============================================================================app.get('/', (req, res) => { res.send(getDashboardHTML());});
// ============================================================================// Helper Functions// ============================================================================
function readSyncStatus() { try { if (fs.existsSync('/tmp/sync-status.json')) { const data = fs.readFileSync('/tmp/sync-status.json', 'utf8'); return JSON.parse(data); } } catch (error) { console.error('Error reading sync status:', error.message); }
return { db_status: 'unknown', last_sync_time: null, last_error: null, sync_count: 0 };}
function checkPaperclipHealth() { return new Promise((resolve) => { const healthUrl = `http://${PAPERCLIP_HOST}:${PAPERCLIP_PORT}/health`;
const timeout = setTimeout(() => { resolve({ status: 'unreachable', reason: 'timeout' }); }, 5000);
http.get(healthUrl, (res) => { clearTimeout(timeout); resolve({ status: 'running', statusCode: res.statusCode }); }).on('error', (err) => { clearTimeout(timeout); resolve({ status: 'unreachable', reason: err.message }); }); });}
function proxyRequest(method, url, headers, body) { return new Promise((resolve, reject) => { const options = { method, headers: { ...headers, 'host': `${PAPERCLIP_HOST}:${PAPERCLIP_PORT}` }, timeout: 30000 };
const req = http.request(url, options, (res) => { let data = '';
res.on('data', (chunk) => { data += chunk; });
res.on('end', () => { resolve({ statusCode: res.statusCode, headers: res.headers, body: data }); }); });
req.on('error', (err) => { reject(err); });
if (body && Object.keys(body).length > 0) { req.write(JSON.stringify(body)); }
req.end(); });}
function getDashboardHTML() { return `<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>HuggingClip - Paperclip on HF Spaces</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; padding: 20px; }
.container { max-width: 1200px; margin: 0 auto; }
.header { text-align: center; color: white; margin-bottom: 40px; animation: slideDown 0.6s ease-out; }
@keyframes slideDown { from { opacity: 0; transform: translateY(-20px); } to { opacity: 1; transform: translateY(0); } }
.header h1 { font-size: 2.5em; margin-bottom: 10px; font-weight: 700; }
.header p { font-size: 1.1em; opacity: 0.9; }
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-bottom: 30px; }
.card { background: white; border-radius: 12px; padding: 24px; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2); animation: fadeIn 0.6s ease-out; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
.card:nth-child(1) { animation-delay: 0.1s; } .card:nth-child(2) { animation-delay: 0.2s; } .card:nth-child(3) { animation-delay: 0.3s; } .card:nth-child(4) { animation-delay: 0.4s; }
.card h2 { color: #333; font-size: 1.3em; margin-bottom: 16px; display: flex; align-items: center; gap: 10px; }
.status-indicator { width: 12px; height: 12px; border-radius: 50%; display: inline-block; }
.status-indicator.running { background-color: #4ade80; box-shadow: 0 0 10px rgba(74, 222, 128, 0.5); }
.status-indicator.stopped { background-color: #ef4444; }
.status-indicator.unknown { background-color: #eab308; }
.stat { margin: 12px 0; display: flex; justify-content: space-between; align-items: center; padding: 8px 0; border-bottom: 1px solid #f0f0f0; }
.stat:last-child { border-bottom: none; }
.stat-label { color: #666; font-size: 0.95em; }
.stat-value { color: #333; font-weight: 600; font-size: 0.95em; }
.button-group { display: flex; gap: 10px; margin-top: 16px; }
.button { flex: 1; padding: 10px 16px; border: none; border-radius: 6px; font-size: 0.9em; cursor: pointer; transition: all 0.3s ease; text-decoration: none; display: inline-flex; align-items: center; justify-content: center; gap: 6px; }
.button-primary { background: #667eea; color: white; }
.button-primary:hover { background: #5568d3; transform: translateY(-2px); box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4); }
.button-secondary { background: #f3f4f6; color: #333; border: 1px solid #e5e7eb; }
.button-secondary:hover { background: #e5e7eb; }
.footer { text-align: center; color: white; margin-top: 40px; opacity: 0.8; font-size: 0.9em; }
.footer a { color: white; text-decoration: underline; }
.error { color: #dc2626; font-size: 0.85em; }
.success { color: #16a34a; font-size: 0.85em; }
.pending { color: #ea580c; font-size: 0.85em; }
.code { background: #f3f4f6; padding: 2px 6px; border-radius: 3px; font-family: 'Monaco', 'Courier New', monospace; font-size: 0.85em; }
.loading { display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: #667eea; animation: pulse 1.5s infinite; }
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.3; } } </style></head><body> <div class="container"> <div class="header"> <h1>π HuggingClip</h1> <p>Paperclip AI Agent Orchestration on Hugging Face Spaces</p> </div>
<div class="grid"> <!-- Paperclip Status Card --> <div class="card"> <h2> <span class="status-indicator running"></span> Paperclip Service </h2> <div class="stat"> <span class="stat-label">Status</span> <span class="stat-value" id="paperclip-status"> <span class="loading"></span> Checking... </span> </div> <div class="stat"> <span class="stat-label">Port</span> <span class="stat-value">3100</span> </div> <div class="stat"> <span class="stat-label">UI URL</span> <span class="stat-value"><span class="code">/app/</span></span> </div> <div class="button-group"> <a href="/app/" class="button button-primary" target="_blank">Open Paperclip UI</a> </div> </div>
<!-- Database Status Card --> <div class="card"> <h2> <span class="status-indicator running"></span> Database </h2> <div class="stat"> <span class="stat-label">Status</span> <span class="stat-value" id="db-status">PostgreSQL</span> </div> <div class="stat"> <span class="stat-label">Location</span> <span class="stat-value"><span class="code">/paperclip</span></span> </div> <div class="stat"> <span class="stat-label">Last Backup</span> <span class="stat-value" id="last-backup">Never</span> </div> <div class="stat"> <span class="stat-label">Backup Status</span> <span class="stat-value" id="backup-status"> <span class="loading"></span> Checking... </span> </div> </div>
<!-- System Health Card --> <div class="card"> <h2> <span class="status-indicator running"></span> System Health </h2> <div class="stat"> <span class="stat-label">Uptime</span> <span class="stat-value" id="uptime">Calculating...</span> </div> <div class="stat"> <span class="stat-label">Start Time</span> <span class="stat-value" id="start-time">Calculating...</span> </div> <div class="stat"> <span class="stat-label">Health Server</span> <span class="stat-value success">Running</span> </div> <div class="stat"> <span class="stat-label">API Port</span> <span class="stat-value"><span class="code">7861</span></span> </div> </div>
<!-- Quick Links Card --> <div class="card"> <h2>π Resources</h2> <div class="button-group" style="flex-direction: column;"> <a href="/app/" class="button button-primary" target="_blank">Paperclip Dashboard</a> <a href="/api/" class="button button-secondary" target="_blank">API Reference</a> </div> <div class="stat" style="margin-top: 16px;"> <span class="stat-label">Documentation</span> <span class="stat-value"><a href="https://docs.paperclip.ing" target="_blank" style="color: #667eea; text-decoration: underline;">paperclip.ing</a></span> </div> <div class="stat"> <span class="stat-label">GitHub</span> <span class="stat-value"><a href="https://github.com/paperclipai/paperclip" target="_blank" style="color: #667eea; text-decoration: underline;">paperclipai/paperclip</a></span> </div> </div> </div>
<div class="footer"> <p>HuggingClip v1.0 β’ Running on Hugging Face Spaces</p> <p style="margin-top: 10px; opacity: 0.6;">Last updated: <span id="footer-time">loading...</span></p> </div> </div>
<script> // Update status every 5 seconds async function updateStatus() { try { const response = await fetch('/health'); const data = await response.json();
// Update Paperclip status const paperclipEl = document.getElementById('paperclip-status'); if (data.services.paperclip.status === 'running') { paperclipEl.innerHTML = '<span class="success">Running β</span>'; } else { paperclipEl.innerHTML = '<span class="error">Unreachable</span>'; }
// Update DB status const dbEl = document.getElementById('db-status'); if (data.services.database.status === 'connected') { dbEl.innerHTML = '<span class="success">Connected β</span>'; } else { dbEl.innerHTML = '<span class="pending">PostgreSQL</span>'; }
// Update last backup const lastBackupEl = document.getElementById('last-backup'); if (data.services.database.lastSync) { const lastSync = new Date(data.services.database.lastSync).toLocaleString(); lastBackupEl.textContent = lastSync; } else { lastBackupEl.textContent = 'Never'; }
// Update backup status const backupStatusEl = document.getElementById('backup-status'); if (data.backup.enabled) { const errorMsg = data.services.database.lastSyncError; if (errorMsg) { backupStatusEl.innerHTML = '<span class="error">Error</span>'; } else { backupStatusEl.innerHTML = '<span class="success">Enabled β</span>'; } } else { backupStatusEl.innerHTML = '<span class="pending">Disabled</span>'; }
// Update uptime const uptimeEl = document.getElementById('uptime'); const uptime = data.uptime; const hours = Math.floor(uptime / 3600); const minutes = Math.floor((uptime % 3600) / 60); const seconds = Math.floor(uptime % 60); uptimeEl.textContent = \`\${hours}h \${minutes}m \${seconds}s\`;
// Update start time const startTimeEl = document.getElementById('start-time'); const startTime = new Date(data.startTime).toLocaleString(); startTimeEl.textContent = startTime;
// Update footer time document.getElementById('footer-time').textContent = new Date().toLocaleString(); } catch (error) { console.error('Status update failed:', error); } }
// Initial update updateStatus();
// Update every 5 seconds setInterval(updateStatus, 5000); </script></body></html>`;}
// ============================================================================// Start Server// ============================================================================app.listen(PORT, '0.0.0.0', () => { console.log(`β Health server listening on port ${PORT}`); console.log(`β Dashboard: http://localhost:${PORT}/`); console.log(`β API proxy: http://localhost:${PORT}/api/*`); console.log(`β App proxy: http://localhost:${PORT}/app/`);});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494#!/usr/bin/env python3"""HuggingClip Database Sync - PostgreSQL Backup/Restore to Hugging Face DatasetSyncs Paperclip's PostgreSQL database to HF Dataset for persistence across restarts."""
import osimport sysimport jsonimport tarfileimport tempfileimport subprocessimport loggingfrom datetime import datetimefrom pathlib import Path
from huggingface_hub import HfApi, HfFolderfrom huggingface_hub.utils import RepositoryNotFoundError
# ============================================================================# Configuration# ============================================================================
# Logging setuplogging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)
# Environment variablesHF_TOKEN = os.environ.get('HF_TOKEN')HF_USERNAME = os.environ.get('HF_USERNAME')DATABASE_URL = os.environ.get('DATABASE_URL', 'postgres://postgres:paperclip@localhost:5432/paperclip')BACKUP_DATASET_NAME = os.environ.get('BACKUP_DATASET_NAME', 'paperclip-backup')SYNC_MAX_FILE_BYTES = int(os.environ.get('SYNC_MAX_FILE_BYTES', '52428800')) # 50MBPAPERCLIP_HOME = os.environ.get('PAPERCLIP_HOME', '/paperclip')
# Status file for dashboardSTATUS_FILE = Path('/tmp/sync-status.json')
# ============================================================================# Helper Functions# ============================================================================
def parse_db_url(db_url: str) -> dict: """Parse PostgreSQL connection URL""" # Format: postgres://user:password@host:port/database try: # Remove protocol connection_str = db_url.replace('postgres://', '').replace('postgresql://', '')
# Parse credentials if '@' in connection_str: creds, host_db = connection_str.split('@') if ':' in creds: user, password = creds.split(':', 1) else: user = creds password = '' else: user = 'postgres' password = '' host_db = connection_str
# Parse host and database if ':' in host_db and '/' in host_db: host_port, database = host_db.rsplit('/', 1) if ':' in host_port: host, port = host_port.rsplit(':', 1) else: host = host_port port = '5432' else: host = host_db.split('/')[0] port = '5432' database = host_db.split('/')[-1] if '/' in host_db else 'paperclip'
return { 'user': user, 'password': password, 'host': host, 'port': port, 'database': database } except Exception as e: logger.error(f'Failed to parse DATABASE_URL: {e}') return None
def write_status(status: dict): """Write sync status to file for dashboard""" try: STATUS_FILE.write_text(json.dumps(status, indent=2)) except Exception as e: logger.error(f'Failed to write status file: {e}')
def read_status() -> dict: """Read current sync status""" if STATUS_FILE.exists(): try: return json.loads(STATUS_FILE.read_text()) except Exception as e: logger.error(f'Failed to read status file: {e}')
return { 'db_status': 'unknown', 'last_sync_time': None, 'last_error': None, 'sync_count': 0 }
def backup_database() -> tuple[str, bool]: """ Backup PostgreSQL database to SQL dump. Returns (filepath, success) """ logger.info('Starting database backup...')
db_config = parse_db_url(DATABASE_URL) if not db_config: return None, False
temp_dir = tempfile.mkdtemp() dump_file = Path(temp_dir) / 'paperclip.sql'
try: # Build pg_dump command env = os.environ.copy() if db_config['password']: env['PGPASSWORD'] = db_config['password']
cmd = [ 'pg_dump', f'--host={db_config["host"]}', f'--port={db_config["port"]}', f'--username={db_config["user"]}', '--format=plain', '--verbose', db_config['database'] ]
# Execute pg_dump with open(dump_file, 'w') as f: result = subprocess.run(cmd, stdout=f, stderr=subprocess.PIPE, env=env, timeout=300)
if result.returncode != 0: error_msg = result.stderr.decode('utf-8', errors='ignore') logger.error(f'pg_dump failed: {error_msg}') return None, False
dump_size = dump_file.stat().st_size logger.info(f'Database dumped successfully ({dump_size / 1024 / 1024:.2f} MB)')
return str(dump_file), True
except subprocess.TimeoutExpired: logger.error('Database backup timed out (>300s)') return None, False except Exception as e: logger.error(f'Database backup error: {e}') return None, False
def create_backup_tarball(dump_file: str) -> tuple[str, bool]: """ Create tarball with database dump and Paperclip data files. Returns (tarball_path, success) """ logger.info('Creating backup tarball...')
temp_dir = tempfile.mkdtemp() tarball_file = Path(temp_dir) / 'paperclip-backup.tar.gz'
try: with tarfile.open(tarball_file, 'w:gz') as tar: # Add SQL dump tar.add(dump_file, arcname='paperclip.sql')
# Add Paperclip home directory if it exists if Path(PAPERCLIP_HOME).exists(): tar.add(PAPERCLIP_HOME, arcname='paperclip-data') else: logger.warning(f'PAPERCLIP_HOME not found: {PAPERCLIP_HOME}')
tarball_size = tarball_file.stat().st_size logger.info(f'Backup tarball created ({tarball_size / 1024 / 1024:.2f} MB)')
# Check size limit if tarball_size > SYNC_MAX_FILE_BYTES: logger.error(f'Backup too large ({tarball_size / SYNC_MAX_FILE_BYTES * 100:.0f}% of limit)') return None, False
return str(tarball_file), True
except Exception as e: logger.error(f'Failed to create tarball: {e}') return None, False
def sync_to_hf(backup_file: str) -> bool: """ Upload backup tarball to Hugging Face Dataset. """ if not HF_TOKEN: logger.warning('HF_TOKEN not set - skipping backup upload') return False
logger.info('Uploading backup to Hugging Face...')
try: api = HfApi(token=HF_TOKEN)
# Get username if not provided username = HF_USERNAME if not username: try: user_info = api.whoami() username = user_info['name'] except Exception: logger.error('Failed to get HF username') return False
dataset_id = f'{username}/{BACKUP_DATASET_NAME}'
# Create dataset if it doesn't exist try: logger.info(f'Using dataset: {dataset_id}') except RepositoryNotFoundError: logger.info(f'Creating dataset: {dataset_id}') api.create_repo(repo_id=dataset_id, repo_type='dataset', private=True, exist_ok=True)
# Upload file api.upload_file( path_or_fileobj=backup_file, path_in_repo='snapshots/latest.tar.gz', repo_id=dataset_id, repo_type='dataset' )
logger.info(f'Backup uploaded to {dataset_id}') return True
except Exception as e: logger.error(f'Failed to upload to HF: {e}') return False
def restore_database(restore_file: str) -> bool: """ Restore PostgreSQL database from SQL dump. """ logger.info('Restoring database from backup...')
db_config = parse_db_url(DATABASE_URL) if not db_config: return False
try: # Ensure database exists admin_cmd = [ 'psql', f'--host={db_config["host"]}', f'--port={db_config["port"]}', f'--username={db_config["user"]}', '--no-password', '-c', f'CREATE DATABASE IF NOT EXISTS {db_config["database"]};' ]
env = os.environ.copy() if db_config['password']: env['PGPASSWORD'] = db_config['password']
subprocess.run(admin_cmd, env=env, capture_output=True)
# Restore from dump restore_cmd = [ 'psql', f'--host={db_config["host"]}', f'--port={db_config["port"]}', f'--username={db_config["user"]}', '--no-password', db_config['database'] ]
with open(restore_file, 'r') as f: result = subprocess.run( restore_cmd, stdin=f, stderr=subprocess.PIPE, env=env, timeout=300 )
if result.returncode != 0: error_msg = result.stderr.decode('utf-8', errors='ignore') logger.error(f'Restore failed: {error_msg}') return False
logger.info('Database restored successfully') return True
except subprocess.TimeoutExpired: logger.error('Database restore timed out (>300s)') return False except Exception as e: logger.error(f'Database restore error: {e}') return False
def sync_from_hf() -> bool: """ Download backup from Hugging Face and restore database. """ if not HF_TOKEN: logger.warning('HF_TOKEN not set - skipping restore') return False
logger.info('Downloading backup from Hugging Face...')
try: api = HfApi(token=HF_TOKEN)
# Get username username = HF_USERNAME if not username: try: user_info = api.whoami() username = user_info['name'] except Exception: logger.warning('Failed to get HF username') return False
dataset_id = f'{username}/{BACKUP_DATASET_NAME}'
# Download latest backup temp_dir = tempfile.mkdtemp() backup_path = Path(temp_dir) / 'latest.tar.gz'
try: snapshot_path = api.hf_hub_download( repo_id=dataset_id, repo_type='dataset', filename='snapshots/latest.tar.gz', local_dir=temp_dir, local_dir_use_symlinks=False ) except RepositoryNotFoundError: logger.info(f'No backup found in {dataset_id}') return False
logger.info(f'Downloaded backup from {dataset_id}')
# Extract tarball logger.info('Extracting backup...') with tarfile.open(snapshot_path, 'r:gz') as tar: tar.extractall(temp_dir)
dump_file = Path(temp_dir) / 'paperclip.sql' if not dump_file.exists(): logger.error('SQL dump not found in backup') return False
# Restore database success = restore_database(str(dump_file))
# Restore Paperclip data files if present paperclip_data_dir = Path(temp_dir) / 'paperclip-data' if paperclip_data_dir.exists(): logger.info('Restoring Paperclip data files...') import shutil try: for item in paperclip_data_dir.iterdir(): target = Path(PAPERCLIP_HOME) / item.name if target.exists(): shutil.rmtree(target) if target.is_dir() else target.unlink() shutil.copytree(item, target) if item.is_dir() else shutil.copy2(item, target) logger.info('Data files restored') except Exception as e: logger.error(f'Failed to restore data files: {e}')
return success
except Exception as e: logger.error(f'Failed to restore from HF: {e}') return False
# ============================================================================# Main Sync Operations# ============================================================================
def sync_to_backup() -> bool: """Full backup operation: dump DB β create tarball β upload to HF""" logger.info('=' * 60) logger.info('Starting backup operation') logger.info('=' * 60)
status = read_status()
try: # Step 1: Backup database dump_file, success = backup_database() if not success or not dump_file: status['last_error'] = 'Database backup failed' status['db_status'] = 'error' write_status(status) return False
# Step 2: Create tarball tarball_file, success = create_backup_tarball(dump_file) if not success or not tarball_file: status['last_error'] = 'Tarball creation failed' status['db_status'] = 'error' write_status(status) return False
# Step 3: Upload to HF success = sync_to_hf(tarball_file)
# Update status status['last_sync_time'] = datetime.utcnow().isoformat() + 'Z' status['db_status'] = 'connected' if success else 'error' status['last_error'] = None if success else 'Upload failed' status['sync_count'] = status.get('sync_count', 0) + 1
write_status(status)
if success: logger.info('Backup operation completed successfully') else: logger.warning('Backup operation completed with errors')
return success
except Exception as e: logger.error(f'Backup operation failed: {e}') status['last_error'] = str(e) status['db_status'] = 'error' write_status(status) return False
def sync_from_backup() -> bool: """Full restore operation: download from HF β extract β restore DB""" logger.info('=' * 60) logger.info('Starting restore operation') logger.info('=' * 60)
status = read_status()
try: success = sync_from_hf()
# Update status status['db_status'] = 'connected' if success else 'error' status['last_error'] = None if success else 'Restore failed'
write_status(status)
if success: logger.info('Restore operation completed successfully') else: logger.warning('Restore operation completed (no backup or error)')
return success
except Exception as e: logger.error(f'Restore operation failed: {e}') status['last_error'] = str(e) status['db_status'] = 'error' write_status(status) return False
# ============================================================================# CLI# ============================================================================
def main(): if len(sys.argv) < 2: print('Usage: python3 paperclip-sync.py <command>') print('Commands:') print(' sync - Backup database to HF Dataset') print(' restore - Restore database from HF Dataset backup') sys.exit(1)
command = sys.argv[1]
if command == 'sync': success = sync_to_backup() sys.exit(0 if success else 1) elif command == 'restore': success = sync_from_backup() sys.exit(0 if success else 1) else: print(f'Unknown command: {command}') sys.exit(1)
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384#!/bin/bashset -euo pipefail
# Create or update a UptimeRobot monitor for this Hugging Face Space.## Requirements:# - UPTIMEROBOT_API_KEY: Main API key from UptimeRobot# - SPACE_HOST or first CLI arg: your HF Space host, e.g. "user-space.hf.space"## Optional:# - UPTIMEROBOT_MONITOR_NAME: friendly name for the monitor# - UPTIMEROBOT_ALERT_CONTACTS: dash-separated alert contact IDs, e.g. "123456-789012"# - UPTIMEROBOT_INTERVAL: monitoring interval in minutes (subject to account limits)
API_URL="https://api.uptimerobot.com/v2"API_KEY="${UPTIMEROBOT_API_KEY:-}"SPACE_HOST_INPUT="${1:-${SPACE_HOST:-}}"
if [ -z "$API_KEY" ]; then echo "Missing UPTIMEROBOT_API_KEY." echo "Use the Main API key from UptimeRobot -> Integrations." echo "Do not use the Read-only API key or a Monitor-specific API key." exit 1fi
if [ -z "$SPACE_HOST_INPUT" ]; then echo "Missing Space host." echo "Usage: UPTIMEROBOT_API_KEY=... ./setup-uptimerobot.sh your-space.hf.space" exit 1fi
SPACE_HOST_CLEAN="${SPACE_HOST_INPUT#https://}"SPACE_HOST_CLEAN="${SPACE_HOST_CLEAN#http://}"SPACE_HOST_CLEAN="${SPACE_HOST_CLEAN%%/*}"
MONITOR_URL="https://${SPACE_HOST_CLEAN}/health"MONITOR_NAME="${UPTIMEROBOT_MONITOR_NAME:-HuggingClaw ${SPACE_HOST_CLEAN}}"INTERVAL="${UPTIMEROBOT_INTERVAL:-5}"
echo "Checking existing UptimeRobot monitors for ${MONITOR_URL}..."MONITORS_RESPONSE=$(curl -sS -X POST "${API_URL}/getMonitors" \ -d "api_key=${API_KEY}" \ -d "format=json" \ -d "logs=0" \ -d "response_times=0" \ -d "response_times_limit=1")
MONITOR_ID=$(printf '%s' "$MONITORS_RESPONSE" | jq -r --arg url "$MONITOR_URL" ' (.monitors // []) | map(select(.url == $url)) | first | .id // empty')
if [ -n "$MONITOR_ID" ]; then echo "Monitor already exists (id=${MONITOR_ID}) for ${MONITOR_URL}" exit 0fi
echo "Creating new UptimeRobot monitor for ${MONITOR_URL}..."
CURL_ARGS=( -sS -X POST "${API_URL}/newMonitor" -d "api_key=${API_KEY}" -d "format=json" -d "type=1" -d "friendly_name=${MONITOR_NAME}" -d "url=${MONITOR_URL}" -d "interval=${INTERVAL}")
if [ -n "${UPTIMEROBOT_ALERT_CONTACTS:-}" ]; then CURL_ARGS+=(-d "alert_contacts=${UPTIMEROBOT_ALERT_CONTACTS}")fi
CREATE_RESPONSE=$(curl "${CURL_ARGS[@]}")CREATE_STATUS=$(printf '%s' "$CREATE_RESPONSE" | jq -r '.stat // "fail"')
if [ "$CREATE_STATUS" != "ok" ]; then echo "Failed to create monitor." printf '%s\n' "$CREATE_RESPONSE" exit 1fi
NEW_ID=$(printf '%s' "$CREATE_RESPONSE" | jq -r '.monitor.id // empty')echo "Created UptimeRobot monitor ${NEW_ID:-"(id unavailable)"} for ${MONITOR_URL}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202#!/bin/bashset -e
umask 0077
# Colors for outputRED='\033[0;31m'GREEN='\033[0;32m'YELLOW='\033[1;33m'BLUE='\033[0;34m'NC='\033[0m' # No Color
# Bannerecho -e "${BLUE}"cat << 'EOF' ___ ___ _____ _ _ / _ \/ _ \___ __________/ ___/| (_)____ / ___/ ___/ _ `/ ___/ ___/\__ \ | | / __ \/ / / / / /_/ / / / /__/__/ / | | / /_/ /\_/ \_/ \__,_/_/ \___/____/ |_|_/ .___/ /_/EOFecho -e "${NC}${GREEN}Starting HuggingClip (Paperclip on HF Spaces)${NC}\n"
# ============================================================================# 1. Validate Environment Variables# ============================================================================echo -e "${BLUE}[1/8] Validating environment variables...${NC}"
REQUIRED_VARS=("HF_TOKEN")MISSING_VARS=()
for var in "${REQUIRED_VARS[@]}"; do if [ -z "${!var}" ]; then MISSING_VARS+=("$var") fidone
if [ ${#MISSING_VARS[@]} -gt 0 ]; then echo -e "${YELLOW}Warning: Missing env vars: ${MISSING_VARS[*]}${NC}" echo -e "${YELLOW}Backup to HF Dataset will be disabled${NC}" SYNC_DISABLED=trueelse SYNC_DISABLED=falsefi
# Default valuesexport DATABASE_URL="${DATABASE_URL:-postgres://postgres:paperclip@localhost:5432/paperclip}"export PORT="${PORT:-3100}"export SERVE_UI="${SERVE_UI:-true}"export NODE_ENV="${NODE_ENV:-production}"export HOST="${HOST:-0.0.0.0}"export PAPERCLIP_HOME="${PAPERCLIP_HOME:-/paperclip}"export PAPERCLIP_DEPLOYMENT_MODE="${PAPERCLIP_DEPLOYMENT_MODE:-authenticated}"export SYNC_INTERVAL="${SYNC_INTERVAL:-180}"export SYNC_MAX_FILE_BYTES="${SYNC_MAX_FILE_BYTES:-52428800}"export BACKUP_DATASET_NAME="${BACKUP_DATASET_NAME:-paperclip-backup}"export PAPERCLIP_TELEMETRY_DISABLED="${PAPERCLIP_TELEMETRY_DISABLED:-1}"export DO_NOT_TRACK="${DO_NOT_TRACK:-1}"
echo -e "${GREEN}β Environment validated${NC}\n"
# ============================================================================# 2. Initialize PostgreSQL# ============================================================================echo -e "${BLUE}[2/8] Setting up PostgreSQL database...${NC}"
# Start PostgreSQL if not runningif ! pgrep -x "postgres" > /dev/null; then echo "Starting PostgreSQL daemon..." su - postgres -c "/usr/lib/postgresql/*/bin/postgres -D /var/lib/postgresql/data" & POSTGRES_PID=$!
# Wait for PostgreSQL to start sleep 3 until pg_isready -h localhost -U postgres 2>/dev/null; do sleep 1 donefi
# Create paperclip user and database if they don't existpsql -U postgres -tc "SELECT 1 FROM pg_user WHERE usename = 'postgres'" | grep -q 1 || \ psql -U postgres -c "CREATE USER postgres WITH PASSWORD 'paperclip' CREATEDB;" 2>/dev/null || true
psql -U postgres -tc "SELECT 1 FROM pg_database WHERE datname = 'paperclip'" | grep -q 1 || \ psql -U postgres -c "CREATE DATABASE paperclip OWNER postgres;" 2>/dev/null || true
echo -e "${GREEN}β PostgreSQL ready${NC}\n"
# ============================================================================# 3. Restore from HF Dataset Backup# ============================================================================echo -e "${BLUE}[3/8] Restoring database from HF Dataset backup...${NC}"
if [ "$SYNC_DISABLED" = false ]; then python3 /app/paperclip-sync.py restore 2>&1 || true echo -e "${GREEN}β Restore attempt completed${NC}\n"else echo -e "${YELLOW}Skipping restore (no HF_TOKEN)${NC}\n"fi
# ============================================================================# 4. Setup Cloudflare Proxy (if token provided)# ============================================================================if [ -n "$CLOUDFLARE_WORKERS_TOKEN" ] && [ -n "$CLOUDFLARE_ACCOUNT_ID" ]; then echo -e "${BLUE}[4/8] Setting up Cloudflare proxy...${NC}" python3 /app/cloudflare-proxy-setup.py 2>&1 || echo -e "${YELLOW}Cloudflare setup failed, continuing without proxy${NC}" echo ""else echo -e "${BLUE}[4/8] Cloudflare proxy (skipped - no credentials)${NC}\n"fi
# ============================================================================# 5. Start Background Sync Loop# ============================================================================echo -e "${BLUE}[5/8] Starting database sync loop...${NC}"
if [ "$SYNC_DISABLED" = false ]; then # Start sync in background ( while true; do sleep "$SYNC_INTERVAL" python3 /app/paperclip-sync.py sync 2>&1 || true done ) & SYNC_PID=$! echo -e "${GREEN}β Sync loop started (PID: $SYNC_PID)${NC}\n"else echo -e "${YELLOW}Sync disabled (no HF_TOKEN)${NC}\n"fi
# ============================================================================# 6. Start Health Server# ============================================================================echo -e "${BLUE}[6/8] Starting health server on port 7861...${NC}"
# Load Cloudflare proxy if availableif [ -f /app/cloudflare-proxy.js ]; then export NODE_OPTIONS="--require /app/cloudflare-proxy.js"fi
node /app/health-server.js &HEALTH_PID=$!echo -e "${GREEN}β Health server started (PID: $HEALTH_PID)${NC}\n"
# Wait for health server to startsleep 2
# ============================================================================# 7. Launch Paperclip# ============================================================================echo -e "${BLUE}[7/8] Launching Paperclip application...${NC}"
cd /app/paperclip
# Install Paperclip dependencies if neededif [ ! -d "node_modules" ]; then echo "Installing Paperclip dependencies..." pnpm install 2>&1 | tail -5 || npm install 2>&1 | tail -5fi
# Run Paperclipexport DATABASE_URLexport PORTexport SERVE_UIexport NODE_ENVexport HOSTexport PAPERCLIP_HOMEexport PAPERCLIP_DEPLOYMENT_MODEexport PAPERCLIP_TELEMETRY_DISABLEDexport DO_NOT_TRACK
echo -e "${GREEN}β All systems ready${NC}"echo -e "${GREEN}βββββββββββββββββββββββββββββββββββββββββββ${NC}"echo -e " Health Dashboard: http://localhost:7861/"echo -e " Paperclip UI: http://localhost:7861/app/"echo -e " API Endpoint: http://localhost:7861/api/*"echo -e "${GREEN}βββββββββββββββββββββββββββββββββββββββββββ${NC}\n"
# ============================================================================# 8. Graceful Shutdown Handler# ============================================================================cleanup() { echo -e "\n${YELLOW}[SHUTDOWN] Received termination signal...${NC}" echo "Syncing data to HF Dataset..."
if [ "$SYNC_DISABLED" = false ]; then python3 /app/paperclip-sync.py sync 2>&1 || true fi
echo "Stopping services..." [ -n "$HEALTH_PID" ] && kill $HEALTH_PID 2>/dev/null || true [ -n "$SYNC_PID" ] && kill $SYNC_PID 2>/dev/null || true
echo -e "${GREEN}Shutdown complete${NC}" exit 0}
trap cleanup SIGTERM SIGINT
# Start Paperclip in foregroundexec node server.js.env.exampleAdded+127
CHANGELOG.mdAdded+57
CODE_OF_CONDUCT.mdAdded+30
CONTRIBUTING.mdAdded+67
DockerfileAdded+80
LICENSEAdded+28
README.mdAdded+407
SECURITY.mdAdded+62
cloudflare-proxy-setup.pyAdded+253
cloudflare-proxy.jsAdded+375
cloudflare-worker.jsAdded+103
docker-compose.ymlAdded+91
health-server.jsAdded+683
paperclip-sync.pyAdded+494
setup-uptimerobot.shAdded+84
start.shAdded+202