# Ignite OS Proxy System - Deployment Guide

This guide explains how to deploy the comprehensive reverse proxy system to bypass school network filters (iBoss, Lightspeed) and make games accessible on CDN platforms.

## 🎯 Overview

The proxy system includes:
- **Service Worker**: Client-side request interception
- **Multiple Serverless Functions**: Vercel, Netlify, Cloudflare Workers
- **URL Obfuscation**: Multiple encoding methods to evade filters
- **Automatic Failover**: Health checking and proxy rotation
- **CDN Compatibility**: Works on unpkg.com and other CDN platforms

## 🚀 Quick Deploy (All Platforms)

### 1. Deploy to Vercel

[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/YOUR-USERNAME/ignitetnt)

**Manual Deployment:**
```bash
# Install Vercel CLI
npm i -g vercel

# Deploy
vercel --prod

# Custom domain (optional)
vercel domains add proxy1.ignite-os.vercel.app
```

**Configuration:**
- The `api/proxy.js` file will be automatically deployed as a serverless function
- Access URL: `https://your-project.vercel.app/api/proxy`
- Add to `config/proxy-domains.js` primary list

### 2. Deploy to Netlify

[![Deploy to Netlify](https://www.netlify.com/img/deploy/button.svg)](https://app.netlify.com/start/deploy?repository=https://github.com/YOUR-USERNAME/ignitetnt)

**Manual Deployment:**
```bash
# Install Netlify CLI
npm install -g netlify-cli

# Login and deploy
netlify login
netlify deploy --prod --dir=.

# Custom domain (optional)
netlify domains:add proxy2.ignite-os.netlify.app
```

**Configuration:**
- The `netlify/functions/proxy.js` will be deployed automatically
- Access URL: `https://your-site.netlify.app/.netlify/functions/proxy`
- Add to `config/proxy-domains.js` primary list

### 3. Deploy to Cloudflare Workers

**Setup:**
```bash
# Install Wrangler CLI
npm install -g wrangler

# Authenticate
wrangler login

# Create worker
wrangler publish cloudflare-worker.js --name ignite-proxy

# Custom domain (optional)
wrangler route add "proxy3.ignite-os.workers.dev/*" ignite-proxy
```

**Configuration:**
- Copy `cloudflare-worker.js` content to Cloudflare Workers dashboard
- Access URL: `https://ignite-proxy.your-subdomain.workers.dev`
- Update the worker URL in the script itself
- Add to `config/proxy-domains.js` primary list

### 4. Deploy to Heroku

**Setup:**
```bash
# Install Heroku CLI
npm install -g heroku

# Create app
heroku create ignite-proxy-app

# Deploy
git push heroku main
```

**Heroku Configuration (`package.json`):**
```json
{
  "scripts": {
    "start": "node server.js"
  },
  "engines": {
    "node": "18.x"
  }
}
```

**Server file (`server.js`):**
```javascript
const express = require('express');
const cors = require('cors');
const app = express();
const PORT = process.env.PORT || 3000;

app.use(cors());
app.use(express.json());

// Import and use the proxy function
const proxyHandler = require('./api/proxy.js');
app.use('/proxy', proxyHandler);

app.listen(PORT, () => {
  console.log(`Proxy server running on port ${PORT}`);
});
```

### 5. Deploy to Railway

**Setup:**
```bash
# Install Railway CLI
npm install -g @railway/cli

# Login and deploy
railway login
railway init
railway up
```

## 📦 CDN Deployment (unpkg.com)

### Update package.json
```json
{
  "name": "ignitetnt",
  "version": "1.0.4",
  "main": "index.html",
  "files": [
    "index.html",
    "play.html",
    "config/",
    "sw.js",
    "api/",
    "netlify/"
  ]
}
```

### Publish to NPM
```bash
npm login
npm publish
```

### Access via CDN
- **unpkg.com**: `https://unpkg.com/ignitetnt@1.0.4/index.html`
- **jsdelivr**: `https://cdn.jsdelivr.net/npm/ignitetnt@1.0.4/index.html`
- **skypack**: `https://cdn.skypack.dev/ignitetnt@1.0.4/index.html`

## ⚙️ Configuration

### 1. Update Proxy Endpoints

Edit `config/proxy-domains.js`:
```javascript
export const PROXY_DOMAINS = {
  primary: [
    'https://your-vercel-app.vercel.app/api/proxy',
    'https://your-netlify-site.netlify.app/.netlify/functions/proxy',
    'https://your-worker.workers.dev',
    'https://your-heroku-app.herokuapp.com/proxy'
  ],
  // ... rest of configuration
};
```

### 2. Service Worker Registration

Add to your main HTML files:
```html
<script>
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('./sw.js')
      .then(reg => console.log('SW registered'))
      .catch(err => console.log('SW registration failed'));
  }
</script>
```

### 3. Environment Variables

**Vercel (vercel.json):**
```json
{
  "functions": {
    "api/proxy.js": {
      "maxDuration": 30
    }
  },
  "headers": [
    {
      "source": "/api/(.*)",
      "headers": [
        { "key": "Access-Control-Allow-Origin", "value": "*" },
        { "key": "Access-Control-Allow-Methods", "value": "GET,POST,PUT,DELETE,OPTIONS" },
        { "key": "Access-Control-Allow-Headers", "value": "*" }
      ]
    }
  ]
}
```

**Netlify (netlify.toml):**
```toml
[build]
  functions = "netlify/functions"

[[headers]]
  for = "/.netlify/functions/*"
  [headers.values]
    Access-Control-Allow-Origin = "*"
    Access-Control-Allow-Methods = "GET,POST,PUT,DELETE,OPTIONS"
    Access-Control-Allow-Headers = "*"

[[redirects]]
  from = "/proxy/*"
  to = "/.netlify/functions/proxy"
  status = 200
```

**Cloudflare Workers (wrangler.toml):**
```toml
name = "ignite-proxy"
type = "javascript"
compatibility_date = "2023-12-01"

[env.production]
route = "proxy1.ignite-os.workers.dev/*"
```

## 🔒 Security Configuration

### 1. Rate Limiting
Add to your proxy functions:
```javascript
// Simple rate limiting
const rateLimiter = new Map();
const RATE_LIMIT = 100; // requests per minute
const WINDOW = 60000; // 1 minute

function checkRateLimit(ip) {
  const now = Date.now();
  const userRequests = rateLimiter.get(ip) || [];
  
  // Remove old requests
  const recentRequests = userRequests.filter(time => now - time < WINDOW);
  
  if (recentRequests.length >= RATE_LIMIT) {
    return false; // Rate limited
  }
  
  recentRequests.push(now);
  rateLimiter.set(ip, recentRequests);
  return true; // Allow request
}
```

### 2. Domain Restrictions
```javascript
const ALLOWED_DOMAINS = [
  'unpkg.com',
  'cdn.jsdelivr.net',
  'your-domain.com'
];

function isAllowedOrigin(origin) {
  return ALLOWED_DOMAINS.some(domain => origin.includes(domain));
}
```

## 🧪 Testing

### 1. Test Proxy Endpoints
```javascript
// Run in browser console
window.proxyManager.testProxies().then(working => {
  console.log('Working proxies:', working);
});
```

### 2. Test Game Loading
```javascript
// Test specific game
const testUrl = 'https://gms.parcoil.com/1v1lol/';
window.proxyManager.createProxyUrl(testUrl).then(proxyUrl => {
  console.log('Proxy URL:', proxyUrl);
  fetch(proxyUrl).then(r => console.log('Status:', r.status));
});
```

### 3. Health Check
```javascript
// Check proxy health
console.log('Proxy stats:', window.proxyManager.getStats());
```

## 🚨 Troubleshooting

### Common Issues

1. **CORS Errors**
   - Ensure all proxy functions return proper CORS headers
   - Check `Access-Control-Allow-Origin: *` is set

2. **Service Worker Not Loading**
   - Serve files over HTTPS (required for service workers)
   - Check browser console for registration errors

3. **Proxy Timeouts**
   - Increase timeout values in serverless functions
   - Add retry logic with exponential backoff

4. **Games Not Loading**
   - Check if game URLs are properly encoded/decoded
   - Verify proxy endpoints are accessible
   - Test with direct URLs first

### Debug Mode
Enable debug mode by adding to localStorage:
```javascript
localStorage.setItem('debug-proxy', 'true');
```

## 🔄 Maintenance

### Regular Updates
1. Monitor proxy endpoint health
2. Rotate encoding keys monthly
3. Update backup domains quarterly
4. Check for new public proxy services

### Monitoring Script
```javascript
// Add to your site for monitoring
setInterval(async () => {
  const stats = window.proxyManager.getStats();
  if (stats.healthRatio < 0.5) {
    console.warn('Low proxy health:', stats);
    // Optionally send to monitoring service
  }
}, 300000); // Check every 5 minutes
```

## 📝 Notes

- **Legal**: Only use for educational purposes and legitimate content
- **Performance**: CDN deployment may have slight latency
- **Reliability**: Multiple backup endpoints ensure high availability
- **Updates**: Keep proxy endpoints and encoding methods updated

## 🆘 Support

If you encounter issues:
1. Check browser console for errors
2. Test proxy endpoints individually
3. Verify service worker is registered
4. Check network tab for failed requests

For additional support, create an issue in the repository.