https://github.com/lifeart/revamp
A Node.js SOCKS5/HTTP proxy that intercepts web traffic and transforms modern JavaScript, CSS, and HTML for legacy browsers like Safari 9 on iPad 2, iPod Touch, and iPad Mini (iOS 9+).
https://github.com/lifeart/revamp
babel compatibility http-proxy ios ipad ipod legacy-browser mitm nodejs polyfill postcss proxy safari socks5 ssl-interception transpiler typescript
Last synced: about 2 months ago
JSON representation
A Node.js SOCKS5/HTTP proxy that intercepts web traffic and transforms modern JavaScript, CSS, and HTML for legacy browsers like Safari 9 on iPad 2, iPod Touch, and iPad Mini (iOS 9+).
- Host: GitHub
- URL: https://github.com/lifeart/revamp
- Owner: lifeart
- License: mit
- Created: 2025-11-27T13:16:18.000Z (7 months ago)
- Default Branch: master
- Last Pushed: 2026-01-30T15:39:49.000Z (5 months ago)
- Last Synced: 2026-01-31T08:37:42.725Z (5 months ago)
- Topics: babel, compatibility, http-proxy, ios, ipad, ipod, legacy-browser, mitm, nodejs, polyfill, postcss, proxy, safari, socks5, ssl-interception, transpiler, typescript
- Language: TypeScript
- Homepage:
- Size: 712 KB
- Stars: 3
- Watchers: 0
- Forks: 0
- Open Issues: 15
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: CONTRIBUTING.md
- Funding: .github/FUNDING.yml
- License: LICENSE
- Code of conduct: CODE_OF_CONDUCT.md
- Security: .github/SECURITY.md
- Agents: .github/AGENTS.md
Awesome Lists containing this project
README
# Re:Vamp
[](https://github.com/lifeart/revamp/actions/workflows/ci.yml) [](https://github.com/lifeart/revamp/actions/workflows/docker.yml)
[](https://codecov.io/gh/lifeart/revamp)
[](https://opensource.org/licenses/MIT)
[](https://nodejs.org)
[](https://www.typescriptlang.org/)
[](https://ghcr.io/lifeart/revamp)

**Legacy Browser Compatibility Proxy** β Transform modern web content for older devices like iPads and iPods running iOS 9+.
Give your old iPad 2, iPad Mini, or iPod Touch a second life by making modern websites work again!
## β¨ Features
### Core Proxy Features
- **π§ JavaScript Transpilation** β Babel transforms modern JS (optional chaining, nullish coalescing, async/await) to ES5/ES6
- **π¨ CSS Transformation** β PostCSS adds vendor prefixes and transforms modern CSS features
- **π HTML Modification** β Injects polyfills and can remove ads/tracking scripts
- **πΌοΈ Image Optimization** β Converts WebP/AVIF to JPEG/PNG for legacy browser support
- **π¦ ES Module Bundling** β esbuild-based bundler converts ES modules to legacy-compatible bundles
- **π HTTPS Interception** β Transparent SSL/TLS interception with auto-generated certificates
- **𧦠SOCKS5 Proxy** β Device-wide traffic routing (recommended for iOS)
- **π HTTP Proxy** β Alternative proxy method
- **πΎ Smart Caching** β Memory + disk caching for faster repeat visits
- **π User-Agent Spoofing** β Bypass browser detection (optional)
- **π« Ad & Tracking Removal** β Block common ad networks and trackers
- **π± Easy Setup** β Built-in captive portal for certificate installation
- **π Remote Service Workers** β Bridge server for Service Worker emulation on legacy devices
- **π± Multi-Device Support** β Per-client configuration with IP-based settings
- **π― Domain Profiles** β Per-domain filtering rules with pattern matching (exact, wildcard, regex)
### Polyfills for Legacy Browsers (30+)
- **Promise.finally, Promise.allSettled** β Modern Promise methods
- **fetch API** β Full fetch/Headers/Response polyfill
- **IntersectionObserver** β Lazy loading support
- **ResizeObserver** β Element resize detection
- **MutationObserver** β DOM mutation detection (enhanced)
- **WeakMap/WeakSet** β Weak reference collections
- **Web Components** β Custom Elements v1 and basic Shadow DOM
- **Intl API** β Basic DateTimeFormat and NumberFormat
- **Service Worker Bypass** β Disables SW registration for compatibility
- **Lazy Loading** β Polyfill for `loading="lazy"` attribute
- **AbortController** β Request cancellation support
- **Array methods** β flat, flatMap, from, includes, and more
- **Object methods** β entries, values, fromEntries
- **String methods** β padStart, padEnd, replaceAll
- **CustomEvent** β Custom event creation and dispatch
### CSS Enhancements
- **CSS Grid β Flexbox Fallback** β Auto-generate flexbox fallbacks for CSS Grid
- **Dark Mode Stripping** β Remove `prefers-color-scheme` media queries
- **Vendor Prefixes** β Automatic -webkit- prefixes for Safari 9
### DevOps & Monitoring
- **ποΈ Admin Panel** β Full-featured web UI at `/__revamp__/admin` for managing profiles and configuration
- **π Metrics Dashboard** β Real-time web UI at `/__revamp__/metrics`
- **π³ Docker Support** β Production and development Dockerfiles
- **π PAC File Generation** β Auto-generate proxy config files
- **βοΈ External Config** β JSON config for blocked domains
- **π Plugin System** β Extensible architecture with hooks for request/response lifecycle, transforms, and filtering
### Performance Optimizations
- **π§΅ Babel Worker Pool** β JavaScript transforms run in parallel worker threads via [tinypool](https://github.com/tinylibs/tinypool)
- **β‘ Async Compression** β Non-blocking gzip compression/decompression
- **ποΈ Configurable Compression** β Adjustable gzip level (1-9) for speed vs size tradeoff
- **π Up to 9x speedup** β Parallel compression achieves significant performance gains
## π Quick Start
### Installation
```bash
# Clone the repository
git clone https://github.com/lifeart/revamp.git
cd revamp
# Install dependencies (pnpm recommended)
pnpm install
# Start the proxy
pnpm start
# Or in development mode (auto-reload)
pnpm dev
```
### Docker Installation
```bash
# Build and run with Docker
docker build -t revamp .
docker run -p 1080:1080 -p 8080:8080 -p 8888:8888 revamp
# Or use Docker Compose
docker-compose up -d
# Development mode with hot-reload
docker-compose --profile dev up revamp-dev
```
### Device Setup
1. **Start Revamp** on your computer
2. **Open the setup page** on your legacy device:
- Navigate to `http://YOUR_COMPUTER_IP:8888`
3. **Install the certificate** and enable trust (see detailed instructions below)
4. **Configure proxy** in Wi-Fi settings
## π± Detailed Setup
### Installing the CA Certificate
When you start Revamp, a CA certificate is generated at `.revamp-certs/ca.crt`.
**On iOS:**
1. Open `http://YOUR_COMPUTER_IP:8888` in Safari
2. Tap "Download Certificate"
3. Go to **Settings β General β VPN & Device Management**
4. Install the downloaded profile
5. Go to **Settings β General β About β Certificate Trust Settings**
6. Enable full trust for "Revamp Proxy CA"
**On macOS:**
1. Open the `.revamp-certs/ca.crt` file
2. Add to Keychain Access
3. Find "Revamp Proxy CA", double-click, expand Trust
4. Set "When using this certificate" to "Always Trust"
### Configuring the Proxy
**SOCKS5 (Recommended for iOS):**
- **Settings β Wi-Fi β [Your Network] β Configure Proxy**
- Select **Manual**
- Server: `YOUR_COMPUTER_IP`
- Port: `1080`
**HTTP Proxy (Alternative):**
- Server: `YOUR_COMPUTER_IP`
- Port: `8080`
## βοΈ Configuration
Edit `src/config/index.ts` or pass options when creating the server:
```typescript
import { createRevampServer } from "revamp";
const server = createRevampServer({
// Server ports
socks5Port: 1080,
httpProxyPort: 8080,
captivePortalPort: 8888,
// Target browsers (Browserslist format)
targets: ["safari 9", "ios 9"],
// Feature toggles
transformJs: true, // Babel transpilation
transformCss: true, // PostCSS transformation
transformHtml: true, // HTML polyfill injection
bundleEsModules: true, // Bundle ES modules for legacy browsers
emulateServiceWorkers: true, // Service Worker bypass/emulation
remoteServiceWorkers: true, // Remote Service Worker bridge
removeAds: true, // Block ad domains
removeTracking: true, // Block tracking domains
injectPolyfills: true, // Add polyfills for missing APIs
spoofUserAgent: true, // Send modern User-Agent to servers
spoofUserAgentInJs: true, // Override navigator.userAgent
// Cache settings
cacheEnabled: true,
cacheTTL: 3600, // seconds
// Performance tuning
compressionLevel: 4, // gzip level 1-9 (1=fastest, 9=smallest)
});
server.start();
```
### Runtime Configuration API
You can change settings at runtime via the config API:
```javascript
// From your legacy device's browser console or code:
fetch("http://any-proxied-site/__revamp__/config", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
transformJs: false, // Disable JS transformation
removeAds: false, // Allow ads
}),
});
```
## ποΈ Architecture
```
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β Legacy Device ββββββΆβ SOCKS5 Proxy ββββββΆβ Target Server β
β (iOS 9+) β β (port 1080) β β β
βββββββββββββββββββ ββββββββββ¬βββββββββ βββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββ
β Transformation Pipeline β
βββββββββββββββββββββββββββββββββββββββββββ€
β 1. Intercept request β
β 2. Check cache β
β 3. Fetch from origin server β
β 4. Transform content: β
β β’ JS β Babel (ES5/ES6) β
β β’ CSS β PostCSS (prefixes) β
β β’ HTML β Cheerio (polyfills) β
β 5. Cache transformed result β
β 6. Return to client β
βββββββββββββββββββββββββββββββββββββββββββ
```
### Request Flow (Admin Panel vs Proxied Content)
```
βββββββββββββββββββββββ
β Incoming Request β
ββββββββββββ¬βββββββββββ
β
βΌ
βββββββββββββββββββββββ
β Is /__revamp__/* ? β
ββββββββββββ¬βββββββββββ
β
ββββββββββββββββββββββΌβββββββββββββββββββββ
β YES β β NO
βΌ β βΌ
ββββββββββββββββββββββ β ββββββββββββββββββββββ
β Revamp API β β β Normal Proxy β
β (Direct serve) β β β Pipeline β
ββββββββββββββββββββββ€ β ββββββββββββββββββββββ€
β β’ Admin panel β β β β’ Domain blocking β
β β’ Config API β β β β’ URL filtering β
β β’ Domain API β β β β’ JS transform β
β β’ Metrics β β β β’ CSS transform β
β β’ PAC files β β β β’ HTML transform β
β β’ SW endpoints β β β β’ Image convert β
ββββββββββββββββββββββ€ β β β’ Caching β
β NO transformations β β β β’ Compression β
β NO caching β β ββββββββββββββββββββββ
β NO filtering β β
ββββββββββββββββββββββ β
```
This design ensures the admin panel always works correctly, even when aggressive filtering or transformation options are enabled.
## π Project Structure
```
src/
βββ index.ts # Main entry point
βββ config/ # Configuration management
β βββ index.ts # Config defaults and getters
β βββ client-options.ts # Single source of truth for client options
β βββ domain-rules.ts # Domain profile types
β βββ domain-manager.ts # Profile CRUD and matching
β βββ storage.ts # File persistence utilities
βββ filters/ # Modular filtering system
β βββ index.ts # Ad/tracking pattern management
βββ plugins/ # Plugin system
β βββ index.ts # Public API exports
β βββ types.ts # Core types (PluginManifest, RevampPlugin, etc.)
β βββ hooks.ts # Hook type definitions
β βββ registry.ts # Plugin registry (singleton)
β βββ loader.ts # Plugin discovery & lifecycle
β βββ context.ts # Sandboxed plugin context API
β βββ hook-executor.ts # Interceptor chain execution
β βββ validation.ts # Manifest validation
β βββ api.ts # REST endpoints for plugin management
βββ proxy/ # Proxy servers
β βββ http-proxy.ts # HTTP/HTTPS proxy
β βββ socks5.ts # SOCKS5 proxy
β βββ socks5-protocol.ts # SOCKS5 protocol implementation
β βββ http-client.ts # HTTP request utilities
β βββ shared.ts # Shared utilities
β βββ revamp-api.ts # API endpoint handler
β βββ domain-rules-api.ts # Domain profiles REST API
β βββ remote-sw-server.ts # Remote Service Worker bridge
β βββ types.ts # Type definitions
βββ transformers/ # Content transformation
β βββ js.ts # JavaScript (Babel worker pool)
β βββ js-worker.ts # Babel worker thread
β βββ css.ts # CSS (PostCSS)
β βββ css-grid-fallback.ts # CSS Grid β Flexbox
β βββ dark-mode-strip.ts # Dark mode CSS removal
β βββ html.ts # HTML (Cheerio)
β βββ image.ts # Image optimization
β βββ esm-bundler.ts # ES module bundler
β βββ sw-bundler.ts # Service Worker bundler
β βββ polyfills/ # 30+ polyfill scripts
βββ metrics/ # Metrics collection
βββ pac/ # PAC file generation
βββ cache/ # Caching system
βββ certs/ # Certificate generation
βββ portal/ # Captive portal
βββ benchmarks/ # Performance benchmarks
public/
βββ revamp-logo.png # Logo asset
βββ admin/ # Admin panel web UI
βββ index.html # Dashboard
βββ domains.html # Domain profiles management
βββ config.html # Configuration page
βββ plugins.html # Plugin management
βββ sw.html # Service Workers status
βββ css/admin.css # Shared styles
βββ js/ # JavaScript modules
.revamp-plugins/ # Plugin installation directory
βββ plugins.json # Global plugin config
βββ com-example-plugin/ # Individual plugin
βββ plugin.json # Plugin manifest
βββ index.js # Entry point
tests/ # E2E tests (Playwright)
config/ # External configuration (blocked domains)
```
## π API Endpoints
All API endpoints are available on any proxied domain at `/__revamp__/*`:
| Endpoint | Description |
| --------------------------------- | ------------------------------------- |
| `/__revamp__/admin` | Admin panel web UI |
| `/__revamp__/config` | GET/POST/DELETE proxy configuration |
| `/__revamp__/domains` | GET/POST domain profiles |
| `/__revamp__/domains/:id` | GET/PUT/DELETE specific profile |
| `/__revamp__/domains/match/:host` | GET test which profile matches a host |
| `/__revamp__/metrics` | HTML metrics dashboard |
| `/__revamp__/metrics/json` | JSON metrics data |
| `/__revamp__/pac/socks5` | SOCKS5 PAC file download |
| `/__revamp__/pac/http` | HTTP PAC file download |
| `/__revamp__/pac/combined` | Combined PAC file download |
| `/__revamp__/sw/bundle` | GET Service Worker bundling (URL-based) |
| `/__revamp__/sw/inline` | POST Service Worker transformation |
| `/__revamp__/sw/remote` | WebSocket for remote SW execution |
| `/__revamp__/sw/remote/status` | GET remote SW server status |
| `/__revamp__/plugins` | GET all plugins, POST load all |
| `/__revamp__/plugins/discover` | GET available plugins in directory |
| `/__revamp__/plugins/load-all` | POST load and activate all plugins |
| `/__revamp__/plugins/:id` | GET plugin info, DELETE unload |
| `/__revamp__/plugins/:id/activate`| POST activate a plugin |
| `/__revamp__/plugins/:id/deactivate`| POST deactivate a plugin |
| `/__revamp__/plugins/:id/reload` | POST reload a plugin |
| `/__revamp__/plugins/:id/config` | PUT update plugin configuration |
| `/__revamp__/plugins/metrics` | GET all plugin metrics, DELETE reset |
| `/__revamp__/plugins/:id/metrics` | GET/DELETE plugin-specific metrics |
### Admin Panel
Access the full-featured admin panel at `http://any-proxied-site/__revamp__/admin`:
- **Dashboard** - System status, metrics overview, and quick actions
- **Domain Profiles** - Create, edit, and delete domain-specific filtering rules
- **Configuration** - Toggle transformation and filtering options
- **Service Workers** - Monitor remote SW server status
The admin panel is designed to work on legacy browsers (Safari 9+, iOS 9+) with vanilla JavaScript.
**Bypass Guarantees**: All `/__revamp__/*` endpoints (including the admin panel) are handled **before** the proxy transformation pipeline runs. This ensures:
| Feature | Admin Panel Status |
|---------|-------------------|
| JavaScript transpilation (Babel) | Bypassed |
| CSS transformation (PostCSS) | Bypassed |
| HTML modification (polyfills) | Bypassed |
| Ad blocking | Bypassed |
| Tracking removal | Bypassed |
| Proxy-level caching | Bypassed |
| User-Agent spoofing | Bypassed |
The admin panel files are served directly from disk without any modifications, ensuring the UI always works correctly regardless of proxy configuration.
### Metrics Dashboard
Access real-time statistics at `http://any-proxied-site/__revamp__/metrics`:
- Uptime and connection stats
- Cache hit rate
- Transformation counts (JS/CSS/HTML/Images)
- Bandwidth usage
- Blocked requests count
### PAC Files
PAC (Proxy Auto-Config) files make device setup easier:
```bash
# Get PAC file URL for iOS configuration
http://YOUR_COMPUTER_IP:8888/__revamp__/pac/socks5
```
Configure iOS: **Settings β Wi-Fi β [Network] β Configure Proxy β Automatic** β Enter PAC URL
### Domain Profiles
Domain profiles allow per-domain configuration of filtering rules and transformations. This enables fine-grained control over ad blocking, tracking removal, and content transformation for specific websites.
**Create a profile:**
```bash
curl -X POST http://any-proxied-site/__revamp__/domains \
-H "Content-Type: application/json" \
-d '{
"name": "YouTube Optimization",
"patterns": [
{ "type": "suffix", "pattern": "*.youtube.com" },
{ "type": "suffix", "pattern": "*.googlevideo.com" }
],
"priority": 100,
"transforms": {
"transformJs": true,
"bundleEsModules": true
},
"removeAds": true,
"removeTracking": true,
"customAdPatterns": ["ad_break", "adPlacements"],
"customAdSelectors": [".video-ads", ".ytp-ad-module"],
"enabled": true
}'
```
**Pattern types:**
- `exact` - Exact domain match (e.g., `example.com`)
- `suffix` - Wildcard suffix match (e.g., `*.google.com` matches `www.google.com`, `mail.google.com`)
- `regex` - Regular expression match (e.g., `^.*\.example\.(com|org)$`)
**List all profiles:**
```bash
curl http://any-proxied-site/__revamp__/domains
```
**Get a specific profile:**
```bash
curl http://any-proxied-site/__revamp__/domains/youtube-profile-id
```
**Update a profile:**
```bash
curl -X PUT http://any-proxied-site/__revamp__/domains/youtube-profile-id \
-H "Content-Type: application/json" \
-d '{ "removeAds": false }'
```
**Delete a profile:**
```bash
curl -X DELETE http://any-proxied-site/__revamp__/domains/youtube-profile-id
```
**Test which profile matches a domain:**
```bash
curl http://any-proxied-site/__revamp__/domains/match/www.youtube.com
```
**Example profiles:**
Social Media (Facebook, Twitter, Instagram)
```bash
curl -X POST http://any-proxied-site/__revamp__/domains \
-H "Content-Type: application/json" \
-d '{
"name": "Social Media",
"patterns": [
{ "type": "suffix", "pattern": "*.facebook.com" },
{ "type": "suffix", "pattern": "*.twitter.com" },
{ "type": "suffix", "pattern": "*.x.com" },
{ "type": "suffix", "pattern": "*.instagram.com" }
],
"priority": 90,
"transforms": {
"transformJs": true,
"transformCss": true
},
"removeAds": true,
"removeTracking": true,
"customAdSelectors": [
"[data-testid=\"placementTracking\"]",
"[data-ad-preview]",
".sponsored-post"
],
"enabled": true
}'
```
News Sites (lightweight mode)
```bash
curl -X POST http://any-proxied-site/__revamp__/domains \
-H "Content-Type: application/json" \
-d '{
"name": "News Sites",
"patterns": [
{ "type": "suffix", "pattern": "*.cnn.com" },
{ "type": "suffix", "pattern": "*.bbc.com" },
{ "type": "suffix", "pattern": "*.nytimes.com" }
],
"priority": 80,
"transforms": {
"transformJs": true,
"transformCss": true,
"transformHtml": true
},
"removeAds": true,
"removeTracking": true,
"customAdSelectors": [
".ad-container",
".advertisement",
"[data-ad-unit]"
],
"enabled": true
}'
```
Disable transformations for specific site
```bash
curl -X POST http://any-proxied-site/__revamp__/domains \
-H "Content-Type: application/json" \
-d '{
"name": "Banking (no transforms)",
"patterns": [
{ "type": "suffix", "pattern": "*.mybank.com" }
],
"priority": 200,
"transforms": {
"transformJs": false,
"transformCss": false,
"transformHtml": false
},
"removeAds": false,
"removeTracking": false,
"enabled": true
}'
```
**Configuration hierarchy:**
```
Domain Profile (highest priority)
β
Client Defaults (per-IP settings)
β
Global Defaults (server-wide fallback)
```
**Profile fields:**
| Field | Type | Description |
|-------|------|-------------|
| `name` | string | Human-readable profile name |
| `patterns` | array | Domain matching patterns |
| `priority` | number | Higher = matched first (default: 0) |
| `transforms` | object | Override transform settings |
| `removeAds` | boolean | Enable ad blocking for this domain |
| `removeTracking` | boolean | Enable tracking removal |
| `customAdPatterns` | array | Additional script patterns to block |
| `customAdSelectors` | array | CSS selectors for ad containers |
| `customTrackingPatterns` | array | Additional tracking script patterns |
| `customTrackingSelectors` | array | CSS selectors for tracking elements |
| `enabled` | boolean | Enable/disable this profile |
### Multi-Device Support
Revamp supports multiple devices connecting simultaneously, each with their own configuration:
**Per-client settings** are automatically managed based on the device's IP address. Each device can have different transformation and filtering settings.
**View current client config:**
```bash
curl http://any-proxied-site/__revamp__/config
```
**Update settings for current device:**
```bash
curl -X POST http://any-proxied-site/__revamp__/config \
-H "Content-Type: application/json" \
-d '{
"transformJs": true,
"removeAds": true,
"spoofUserAgent": false
}'
```
**Reset to defaults:**
```bash
curl -X DELETE http://any-proxied-site/__revamp__/config
```
### Plugin System
Revamp includes a powerful plugin system that allows you to extend functionality through hooks into the request/response lifecycle.
**Plugin Directory:**
Plugins are installed in the `.revamp-plugins/` directory. Each plugin has its own subdirectory containing a `plugin.json` manifest and entry point.
```
.revamp-plugins/
βββ plugins.json # Global plugin configuration
βββ com-example-my-plugin/
βββ plugin.json # Plugin manifest
βββ index.js # Entry point
```
**Plugin Manifest (plugin.json):**
```json
{
"id": "com.example.my-plugin",
"name": "My Plugin",
"version": "1.0.0",
"description": "A sample plugin",
"author": "Your Name",
"revampVersion": "1.0.0",
"main": "index.js",
"hooks": ["request:pre", "response:post"],
"permissions": ["request:read", "request:modify", "storage:read", "storage:write"]
}
```
**Available Hooks:**
| Hook | Purpose | Can Modify |
|------|---------|------------|
| `request:pre` | Before upstream request | URL, headers, block |
| `response:post` | After response received | Body, headers, status |
| `transform:pre` | Before content transform | Content, skip transform |
| `transform:post` | After content transform | Transformed content |
| `filter:decision` | Custom blocking logic | Block decision |
| `config:resolution` | Inject config overrides | Config values |
| `domain:lifecycle` | Profile CRUD events | (notify only) |
| `cache:get` | Custom cache backend | Cached data |
| `cache:set` | Custom cache backend | (notify only) |
| `metrics:record` | Custom metrics | (notify only) |
**Available Permissions:**
| Permission | Description |
|------------|-------------|
| `request:read` | Read request data |
| `request:modify` | Modify requests |
| `response:read` | Read response data |
| `response:modify` | Modify responses |
| `config:read` | Read configuration |
| `config:write` | Write configuration |
| `cache:read` | Read from cache |
| `cache:write` | Write to cache |
| `metrics:read` | Read metrics |
| `metrics:write` | Record metrics |
| `network:fetch` | Make network requests |
| `storage:read` | Read plugin storage |
| `storage:write` | Write plugin storage |
| `api:register` | Register API endpoints |
**Plugin Entry Point (index.js):**
```javascript
module.exports = {
manifest: require('./plugin.json'),
async initialize(context) {
// Called when plugin is loaded
context.log('info', 'Plugin initializing...');
},
async activate(context) {
// Register hooks when plugin is activated
context.registerHook('request:pre', async (request) => {
// Example: Block requests to specific domains
if (request.hostname.includes('blocked.com')) {
return { continue: false, value: { blocked: true, reason: 'Custom block' } };
}
return { continue: true };
}, 100); // Priority: higher = runs first
context.registerHook('response:post', async (response) => {
// Example: Add custom header
response.headers['x-plugin-processed'] = 'true';
return { continue: true, value: response };
});
},
async deactivate(context) {
// Clean up when plugin is deactivated
context.unregisterHook('request:pre');
context.unregisterHook('response:post');
},
async shutdown(context) {
// Called when plugin is unloaded
context.log('info', 'Plugin shutting down...');
}
};
```
**Plugin Context API:**
The `context` object provides a sandboxed API for plugins:
```typescript
interface PluginContext {
// Hook registration
registerHook(hookName, handler, priority?): void;
unregisterHook(hookName): void;
// Configuration (requires permissions)
getGlobalConfig(): Readonly;
getEffectiveConfig(clientIp?, domain?): Readonly;
getPluginConfig(): T;
updatePluginConfig(updates): Promise;
// Storage (sandboxed per-plugin)
readStorage(key): Promise;
writeStorage(key, data): Promise;
// Cache
getCached(url, contentType, clientIp?): Promise;
setCache(url, contentType, data, clientIp?): Promise;
// Metrics
getMetrics(): Metrics;
recordMetric(name, value, tags?): void;
// Network
fetch(url, options?): Promise;
// API endpoints (at /__revamp__/plugins/{pluginId}/{path})
registerEndpoint(path, handler): void;
unregisterEndpoint(path): void;
// Logging
log(level, message, ...args): void;
}
```
**Managing Plugins via API:**
```bash
# List all plugins
curl http://any-proxied-site/__revamp__/plugins
# Discover available plugins
curl http://any-proxied-site/__revamp__/plugins/discover
# Load all plugins
curl -X POST http://any-proxied-site/__revamp__/plugins/load-all
# Activate a plugin
curl -X POST http://any-proxied-site/__revamp__/plugins/my-plugin-id/activate
# Deactivate a plugin
curl -X POST http://any-proxied-site/__revamp__/plugins/my-plugin-id/deactivate
# Update plugin configuration
curl -X PUT http://any-proxied-site/__revamp__/plugins/my-plugin-id/config \
-H "Content-Type: application/json" \
-d '{ "customSetting": "value" }'
# Unload a plugin
curl -X DELETE http://any-proxied-site/__revamp__/plugins/my-plugin-id
```
**Plugin Metrics & Observability:**
Revamp tracks per-plugin execution statistics for monitoring and debugging:
```bash
# Get metrics for all plugins
curl http://any-proxied-site/__revamp__/plugins/metrics
# Get metrics for a specific plugin
curl http://any-proxied-site/__revamp__/plugins/my-plugin-id/metrics
# Reset metrics for all plugins
curl -X DELETE http://any-proxied-site/__revamp__/plugins/metrics
# Reset metrics for a specific plugin
curl -X DELETE http://any-proxied-site/__revamp__/plugins/my-plugin-id/metrics
```
Metrics include:
- Total hook executions, successes, failures, and timeouts
- Average execution time per plugin and per hook
- Last execution timestamp
- Per-hook breakdown (e.g., `request:pre` vs `response:post`)
**Configuration Schema Validation:**
Plugins can define a JSON Schema for their configuration to ensure type safety:
```json
{
"id": "com.example.my-plugin",
"name": "My Plugin",
"version": "1.0.0",
"main": "index.js",
"configSchema": {
"type": "object",
"required": ["apiKey"],
"properties": {
"apiKey": {
"type": "string",
"minLength": 10,
"description": "API key for external service"
},
"timeout": {
"type": "integer",
"minimum": 0,
"maximum": 60000,
"default": 5000
},
"enableFeature": {
"type": "boolean",
"default": true
},
"allowedDomains": {
"type": "array",
"items": { "type": "string" },
"uniqueItems": true
}
}
}
}
```
When `updatePluginConfig()` is called, the configuration is validated against the schema. Invalid configurations will throw an error with details about which fields failed validation.
Supported JSON Schema features:
- Types: `string`, `number`, `integer`, `boolean`, `array`, `object`, `null`
- String constraints: `minLength`, `maxLength`, `pattern`
- Number constraints: `minimum`, `maximum`
- Array constraints: `minItems`, `maxItems`, `uniqueItems`, `items`
- Object constraints: `required`, `properties`, `additionalProperties`
- Composition: `oneOf`, `anyOf`, `allOf`
- Enums: `enum`
**Hook Execution Modes:**
Hooks can be executed in different modes:
- **Sequential** (default): Hooks execute one after another in priority order. Earlier hooks can stop the chain.
- **Parallel**: All hooks execute concurrently. Results are collected from all plugins.
The hook executor automatically uses sequential mode for modifying hooks (`request:pre`, `response:post`, etc.) and parallel mode for notification hooks (`domain:lifecycle`, `cache:set`, `metrics:record`).
**Hook Result Types:**
```typescript
// Continue to next hook
{ continue: true, value?: T }
// Stop the chain and return this value
{ continue: false, value: T }
// Stop the chain with an error
{ continue: false, error: Error }
```
**Plugin Testing Framework:**
Revamp provides testing utilities for plugin developers:
```typescript
import {
createTestContext,
createMockRequest,
createMockResponse,
createTestPlugin,
runPluginLifecycle,
assertContinues,
assertStops,
} from 'revamp/plugins/testing';
// Create a test context with mocked dependencies
const context = createTestContext({
pluginId: 'com.test.my-plugin',
config: { mySetting: 'value' },
});
// Create realistic request/response contexts
const request = createMockRequest({
url: 'https://example.com/api',
method: 'POST',
headers: { 'content-type': 'application/json' },
});
const response = createMockResponse({
statusCode: 200,
body: Buffer.from('{"success": true}'),
});
// Test hook behavior
const result = await myHook(request);
assertContinues(result); // Passes if hook returns { continue: true }
assertStops(result); // Passes if hook returns { continue: false }
```
**Plugin Lifecycle:**
```
unloaded β loaded β initializing β initialized β activating β active
β
deactivating β deactivated
```
**Configuration Hierarchy (with plugins):**
```
Plugin Hooks (highest priority)
β
Domain Profile
β
Client Config
β
Global Defaults (lowest)
```
**Available client options:**
| Option | Default | Description |
|--------|---------|-------------|
| `transformJs` | true | Babel JS transpilation |
| `transformCss` | true | PostCSS CSS transformation |
| `transformHtml` | true | HTML polyfill injection |
| `bundleEsModules` | true | Bundle ES modules |
| `emulateServiceWorkers` | true | SW bypass/emulation |
| `remoteServiceWorkers` | true | Remote SW bridge |
| `removeAds` | true | Block ad domains |
| `removeTracking` | true | Block tracking domains |
| `injectPolyfills` | true | Add polyfills |
| `spoofUserAgent` | true | Spoof User-Agent header |
| `spoofUserAgentInJs` | true | Override navigator.userAgent |
## π§ͺ Testing
```bash
# Unit tests
pnpm test:unit # Watch mode
pnpm test:unit:run # Single run
# E2E tests
pnpm test # Run all
pnpm test:headed # With browser
pnpm test:ui # Interactive mode
# Type checking
pnpm typecheck
# Performance benchmarks
pnpm build && pnpm tsx src/benchmarks/parallel-transform.ts
```
### Benchmark Results
On a typical machine (8-core CPU), parallel performance improvements:
| Operation | Sequential | Parallel | Speedup |
| --------------- | ---------- | -------- | --------- |
| JS Transform | ~42ms | ~40ms | 1.05x |
| CSS Transform | ~5ms | ~4ms | 1.37x |
| Gzip Compress | ~0.4ms | ~0.04ms | **9.36x** |
| Gzip Decompress | ~0.06ms | ~0.04ms | 1.52x |
The worker pool's main benefit is **keeping the main event loop responsive** during heavy concurrent load, preventing request queuing and latency spikes.
## π§ Troubleshooting
### Certificate Issues
**"Not Trusted" warning:**
- Ensure you've enabled trust in **Settings β General β About β Certificate Trust Settings**
- Try regenerating certificates: delete `.revamp-certs/` and restart
**Certificate won't install:**
- Make sure you're using Safari (not Chrome) on iOS
- The certificate must be downloaded via HTTP, not HTTPS
### Connection Issues
**Can't connect to proxy:**
- Verify your computer's IP address
- Check firewall settings (ports 1080, 8080, 8888)
- Ensure both devices are on the same network
**Websites not loading:**
- Check the Revamp console for errors
- Some sites may have additional protections
- Try disabling transformations to isolate issues
### Performance Issues
**Slow page loads:**
- Enable caching if disabled
- Consider disabling transformations for specific sites
- Check available disk space for cache
## π¦ Dependencies
| Package | Purpose |
| ------------- | ------------------------------------------ |
| `@babel/core` | JavaScript transpilation |
| `postcss` | CSS transformation |
| `cheerio` | HTML parsing/manipulation |
| `node-forge` | Certificate generation |
| `sharp` | Image optimization |
| `esbuild` | ES module bundling for legacy browsers |
| `tinypool` | Worker thread pool for parallel transforms |
| `ws` | WebSocket for Remote Service Worker bridge |
## π€ Contributing
Contributions are welcome! Please read our [Contributing Guide](CONTRIBUTING.md) for details.
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Run tests
5. Submit a pull request
## π License
[MIT](LICENSE) Β© Alex Kanunnikov
## π Acknowledgments
- Babel team for the amazing transpiler
- PostCSS team for CSS tooling
- node-forge for certificate generation
- All contributors and users!
---
**Give your old devices new life! π**