mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 08:23:34 +00:00
CF worker setup + iframe domain to env
This commit is contained in:
1 parent
ba251d57eb
commit
3898681d97
6 files changed
+604
-8
No files matched your search
@@ -0,0 +1,185 @@
|
||||
# Shakespeare Iframe Proxy - Cloudflare Worker Setup
|
||||
|
||||
This Cloudflare Worker acts as a reverse proxy for the Shakespeare iframe-fetch-client, removing restrictive headers and adding CORS support to enable iframe embedding.
|
||||
|
||||
## Quick Setup
|
||||
|
||||
### Step 1: Deploy iframe-fetch-client to Surge
|
||||
|
||||
First, deploy your iframe-fetch-client files to Surge:
|
||||
|
||||
```bash
|
||||
cd ../iframe-fetch-client
|
||||
npx -y surge . your-unique-name.surge.sh
|
||||
```
|
||||
|
||||
Replace `your-unique-name` with something unique.
|
||||
|
||||
### Step 2: Update Worker Configuration
|
||||
|
||||
Edit `worker.js` and update the `surgeDomain` variable:
|
||||
|
||||
```javascript
|
||||
// Change this line
|
||||
const surgeDomain = 'your-unique-name.surge.sh'; // TODO: Update this!
|
||||
```
|
||||
|
||||
Use the same Surge domain you deployed to in Step 1.
|
||||
|
||||
### Step 3: Deploy the Cloudflare Worker
|
||||
|
||||
#### Option A: Quick Setup (via Dashboard)
|
||||
|
||||
1. Go to [Cloudflare Dashboard](https://dash.cloudflare.com/)
|
||||
2. Navigate to Workers & Pages → Create application
|
||||
3. Select "Create Worker"
|
||||
4. Copy the contents of `worker.js` into the editor
|
||||
5. Click "Save and Deploy"
|
||||
6. Note your worker's URL (e.g., `shakespeare-iframe-proxy.your-account.workers.dev`)
|
||||
|
||||
#### Option B: Using Wrangler CLI
|
||||
|
||||
1. Install Wrangler:
|
||||
```bash
|
||||
npm install -g wrangler
|
||||
```
|
||||
|
||||
2. Login to Cloudflare:
|
||||
```bash
|
||||
wrangler login
|
||||
```
|
||||
|
||||
3. Deploy from this directory:
|
||||
```bash
|
||||
cd cloudflare-worker
|
||||
wrangler deploy
|
||||
```
|
||||
|
||||
### Step 4: Set Up Custom Domain (Optional but Recommended)
|
||||
|
||||
#### Using Cloudflare Dashboard:
|
||||
|
||||
1. Go to your domain in Cloudflare DNS
|
||||
2. Create a wildcard CNAME record:
|
||||
- Type: `CNAME`
|
||||
- Name: `*` (or a specific subdomain like `iframe`)
|
||||
- Target: Your worker URL (e.g., `shakespeare-iframe-proxy.your-account.workers.dev`)
|
||||
- Proxy status: Enabled (orange cloud)
|
||||
|
||||
3. Add a route to your worker:
|
||||
- In Workers & Pages, select your worker
|
||||
- Go to Settings → Triggers → Routes
|
||||
- Add route: `*.your-domain.com/*`
|
||||
|
||||
#### Using Wrangler:
|
||||
|
||||
Update your `wrangler.toml`:
|
||||
|
||||
```toml
|
||||
[env.production]
|
||||
vars = { ENVIRONMENT = "production" }
|
||||
|
||||
[[env.production.routes]]
|
||||
pattern = "*.your-domain.com/*"
|
||||
zone_name = "your-domain.com"
|
||||
```
|
||||
|
||||
Then deploy:
|
||||
```bash
|
||||
wrangler deploy --env production
|
||||
```
|
||||
|
||||
### Step 5: Update Your Environment
|
||||
|
||||
Update your `.env` file in the main project:
|
||||
|
||||
```bash
|
||||
# Change from:
|
||||
VITE_IFRAME_DOMAIN=local-shakespeare.dev
|
||||
|
||||
# To (using your custom domain):
|
||||
VITE_IFRAME_DOMAIN=your-domain.com
|
||||
|
||||
# Or (using worker subdomain):
|
||||
VITE_IFRAME_DOMAIN=your-account.workers.dev
|
||||
```
|
||||
|
||||
### Step 6: Test the Setup
|
||||
|
||||
1. Rebuild your main project:
|
||||
```bash
|
||||
cd ..
|
||||
npm run build
|
||||
# Or start development server
|
||||
npm run dev
|
||||
```
|
||||
|
||||
2. Open Shakespeare and create/load a project
|
||||
3. Build the project
|
||||
4. Switch to preview tab
|
||||
5. Open browser console to see:
|
||||
- Successful iframe loading
|
||||
- Console messages being forwarded
|
||||
- No CORS or security errors
|
||||
|
||||
## Local Development
|
||||
|
||||
### Test Worker Locally:
|
||||
|
||||
```bash
|
||||
cd cloudflare-worker
|
||||
wrangler dev --local-port 8787
|
||||
```
|
||||
|
||||
Test with curl:
|
||||
```bash
|
||||
curl http://localhost:8787
|
||||
```
|
||||
|
||||
### Test with Local Shakespeare:
|
||||
|
||||
Update your `.env` temporarily:
|
||||
```bash
|
||||
VITE_IFRAME_DOMAIN=localhost:8787
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues:
|
||||
|
||||
1. **CORS Errors**: Make sure CORS headers are properly set in the worker
|
||||
2. **X-Frame-Options Blocked**: Ensure these headers are removed in the worker
|
||||
3. **Mixed Content**: Use HTTPS everywhere
|
||||
4. **Service Worker Registration**: Check MIME types for `.js` files
|
||||
|
||||
### Debug Headers:
|
||||
|
||||
You can test what headers are being sent/received:
|
||||
|
||||
```bash
|
||||
curl -I https://project123.your-domain.com/
|
||||
```
|
||||
|
||||
### Check Worker Logs:
|
||||
|
||||
Use Cloudflare Dashboard to view worker logs and debug requests.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
|
||||
│ Shakespeare App │ │ Cloudflare │ │ Surge.sh │
|
||||
│ (Parent Window) │ │ Worker Proxy │ │ (File Hosting) │
|
||||
│ │ │ │ │ │
|
||||
│ - PreviewPane │───▶│ - Remove │───▶│ - iframe- │
|
||||
│ - JSON-RPC │ │ X-Frame-Opt │ │ fetch-client │
|
||||
│ - Console UI │ │ - Add CORS │ │ - sw.js │
|
||||
│ │ │ - Route │ │ - index.html │
|
||||
└─────────────────┘ └─────────────────┘ └─────────────────┘
|
||||
```
|
||||
|
||||
The worker enables secure iframe embedding by:
|
||||
1. Removing headers that prevent iframe embedding
|
||||
2. Adding appropriate CORS headers for cross-origin communication
|
||||
3. Providing a stable domain for project subdomains
|
||||
4. Handling SSL/TLS automatically
|
||||
Executable
+137
@@ -0,0 +1,137 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Shakespeare Iframe Proxy Setup Script
|
||||
# This script helps you set up the Cloudflare Worker for iframe proxying
|
||||
|
||||
set -e
|
||||
|
||||
echo "🚀 Shakespeare Iframe Proxy Setup"
|
||||
echo "=================================="
|
||||
|
||||
# Check if surge is installed
|
||||
if ! command -v surge &> /dev/null; then
|
||||
echo "❌ Surge is not installed. Installing..."
|
||||
npm install -g surge
|
||||
fi
|
||||
|
||||
# Check if wrangler is installed
|
||||
if ! command -v wrangler &> /dev/null; then
|
||||
echo "❌ Wrangler is not installed. Installing..."
|
||||
npm install -g wrangler
|
||||
fi
|
||||
|
||||
# Ask for surge domain
|
||||
read -p "📦 Enter a unique name for your Surge deployment (e.g., shakespeare-iframe-123): " SURGE_DOMAIN
|
||||
|
||||
# Deploy to surge
|
||||
echo "📤 Deploying iframe-fetch-client to Surge..."
|
||||
cd ../iframe-fetch-client
|
||||
surge . "${SURGE_DOMAIN}.surge.sh"
|
||||
cd ../cloudflare-worker
|
||||
|
||||
# Update worker configuration
|
||||
echo "⚙️ Updating worker configuration..."
|
||||
sed -i "s/your-unique-name.surge.sh/${SURGE_DOMAIN}.surge.sh/g" worker.js
|
||||
|
||||
# Ask for Cloudflare setup
|
||||
echo ""
|
||||
echo "🌐 Cloudflare Worker Setup"
|
||||
echo "------------------------"
|
||||
echo "Choose your setup method:"
|
||||
echo "1) Quick setup (via Cloudflare Dashboard - recommended for beginners)"
|
||||
echo "2) Advanced setup (using Wrangler CLI - recommended for developers)"
|
||||
read -p "Enter your choice (1 or 2): " SETUP_CHOICE
|
||||
|
||||
if [ "$SETUP_CHOICE" = "1" ]; then
|
||||
echo ""
|
||||
echo "📋 Quick Setup Instructions:"
|
||||
echo "============================"
|
||||
echo "1. Go to https://dash.cloudflare.com/"
|
||||
echo "2. Navigate to Workers & Pages → Create application"
|
||||
echo "3. Select 'Create Worker'"
|
||||
echo "4. Copy the contents of worker.js into the editor"
|
||||
echo "5. Click 'Save and Deploy'"
|
||||
echo "6. Note your worker's URL (e.g., shakespeare-iframe-proxy.your-account.workers.dev)"
|
||||
echo ""
|
||||
read -p "🔗 Enter your worker URL (e.g., shakespeare-iframe-proxy.your-account.workers.dev): " WORKER_URL
|
||||
|
||||
# Update environment variable
|
||||
echo ""
|
||||
echo "🔧 Updating environment configuration..."
|
||||
cd ..
|
||||
|
||||
# Extract domain from worker URL
|
||||
if [[ $WORKER_URL == *workers.dev ]]; then
|
||||
IFRAME_DOMAIN=$(echo $WORKER_URL | sed 's|https://||' | sed 's|/.*||')
|
||||
else
|
||||
echo "❌ Invalid worker URL format. Please enter a valid workers.dev URL."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
sed -i "s/VITE_IFRAME_DOMAIN=.*/VITE_IFRAME_DOMAIN=${IFRAME_DOMAIN}/" .env
|
||||
|
||||
echo "✅ Setup complete!"
|
||||
echo ""
|
||||
echo "Next steps:"
|
||||
echo "1. Run: npm run dev (or npm run build)"
|
||||
echo "2. Open Shakespeare and test the preview"
|
||||
echo "3. Check browser console for any errors"
|
||||
|
||||
else
|
||||
echo ""
|
||||
echo "🔧 Advanced Setup with Wrangler"
|
||||
echo "================================"
|
||||
|
||||
# Check if logged in
|
||||
if ! wrangler whoami &> /dev/null; then
|
||||
echo "🔐 Logging in to Cloudflare..."
|
||||
wrangler login
|
||||
fi
|
||||
|
||||
# Deploy worker
|
||||
echo "📤 Deploying Cloudflare Worker..."
|
||||
WORKER_URL=$(wrangler deploy --json | jq -r '.workers_dev.url')
|
||||
|
||||
if [ -z "$WORKER_URL" ]; then
|
||||
echo "❌ Failed to deploy worker. Please check the error messages above."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "✅ Worker deployed to: $WORKER_URL"
|
||||
|
||||
# Update environment variable
|
||||
echo ""
|
||||
echo "🔧 Updating environment configuration..."
|
||||
cd ..
|
||||
|
||||
# Extract domain from worker URL
|
||||
IFRAME_DOMAIN=$(echo $WORKER_URL | sed 's|https://||' | sed 's|/.*||')
|
||||
|
||||
sed -i "s/VITE_IFRAME_DOMAIN=.*/VITE_IFRAME_DOMAIN=${IFRAME_DOMAIN}/" .env
|
||||
|
||||
echo "✅ Setup complete!"
|
||||
echo ""
|
||||
echo "Next steps:"
|
||||
echo "1. Run: npm run dev (or npm run build)"
|
||||
echo "2. Open Shakespeare and test the preview"
|
||||
echo "3. Check browser console for any errors"
|
||||
echo ""
|
||||
echo "🎉 For production use, consider setting up a custom domain."
|
||||
echo " See cloudflare-worker/README.md for instructions."
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "🧪 Testing Instructions"
|
||||
echo "======================"
|
||||
echo "To test your setup:"
|
||||
echo "1. Start Shakespeare: npm run dev"
|
||||
echo "2. Create or open a project"
|
||||
echo "3. Build the project"
|
||||
echo "4. Switch to preview tab"
|
||||
echo "5. Open browser console (F12)"
|
||||
echo "6. Look for successful iframe loading and console messages"
|
||||
echo ""
|
||||
echo "If you see any errors, check:"
|
||||
echo "- Browser console for CORS or security errors"
|
||||
echo "- Network tab for failed requests"
|
||||
echo "- Cloudflare Worker logs (in dashboard)"
|
||||
Executable
+138
@@ -0,0 +1,138 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Test script for Shakespeare Iframe Proxy
|
||||
# This script helps verify that your Cloudflare Worker setup is working
|
||||
|
||||
echo "🧪 Shakespeare Iframe Proxy Test"
|
||||
echo "================================"
|
||||
|
||||
# Get current IFRAME_DOMAIN from .env
|
||||
if [ -f "../.env" ]; then
|
||||
IFRAME_DOMAIN=$(grep VITE_IFRAME_DOMAIN ../.env | cut -d'=' -f2)
|
||||
else
|
||||
echo "❌ .env file not found. Please run setup first."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$IFRAME_DOMAIN" ]; then
|
||||
echo "❌ VITE_IFRAME_DOMAIN not set in .env file."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "📡 Testing iframe domain: ${IFRAME_DOMAIN}"
|
||||
echo ""
|
||||
|
||||
# Test 1: Basic connectivity
|
||||
echo "Test 1: Basic connectivity"
|
||||
echo "--------------------------"
|
||||
TEST_URL="https://${IFRAME_DOMAIN}"
|
||||
echo "🔗 Testing: ${TEST_URL}"
|
||||
|
||||
if command -v curl &> /dev/null; then
|
||||
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "${TEST_URL}" 2>/dev/null || echo "000")
|
||||
|
||||
if [ "$HTTP_CODE" = "200" ]; then
|
||||
echo "✅ Successfully connected (HTTP 200)"
|
||||
elif [ "$HTTP_CODE" = "000" ]; then
|
||||
echo "❌ Connection failed - check domain and network"
|
||||
else
|
||||
echo "⚠️ Connected but got HTTP ${HTTP_CODE}"
|
||||
fi
|
||||
else
|
||||
echo "❌ curl not available. Please install curl to run tests."
|
||||
fi
|
||||
|
||||
echo ""
|
||||
|
||||
# Test 2: CORS headers
|
||||
echo "Test 2: CORS Headers"
|
||||
echo "--------------------"
|
||||
if command -v curl &> /dev/null; then
|
||||
CORS_HEADER=$(curl -s -I "${TEST_URL}" 2>/dev/null | grep -i "access-control-allow-origin" || echo "")
|
||||
|
||||
if [ -n "$CORS_HEADER" ]; then
|
||||
echo "✅ CORS headers present:"
|
||||
echo " ${CORS_HEADER}"
|
||||
else
|
||||
echo "❌ No CORS headers found"
|
||||
fi
|
||||
else
|
||||
echo "❌ curl not available. Skip CORS test."
|
||||
fi
|
||||
|
||||
echo ""
|
||||
|
||||
# Test 3: X-Frame-Options (should be absent)
|
||||
echo "Test 3: X-Frame-Options Check"
|
||||
echo "------------------------------"
|
||||
if command -v curl &> /dev/null; then
|
||||
X_FRAME_HEADER=$(curl -s -I "${TEST_URL}" 2>/dev/null | grep -i "x-frame-options" || echo "")
|
||||
|
||||
if [ -z "$X_FRAME_HEADER" ]; then
|
||||
echo "✅ X-Frame-Options header correctly removed"
|
||||
else
|
||||
echo "❌ X-Frame-Options header still present:"
|
||||
echo " ${X_FRAME_HEADER}"
|
||||
fi
|
||||
else
|
||||
echo "❌ curl not available. Skip X-Frame-Options test."
|
||||
fi
|
||||
|
||||
echo ""
|
||||
|
||||
# Test 4: Content-Type for JavaScript
|
||||
echo "Test 4: JavaScript Content-Type"
|
||||
echo "-------------------------------"
|
||||
JS_URL="https://${IFRAME_DOMAIN}/_iframe-client.js"
|
||||
|
||||
if command -v curl &> /dev/null; then
|
||||
CONTENT_TYPE=$(curl -s -I "${JS_URL}" 2>/dev/null | grep -i "content-type" || echo "")
|
||||
|
||||
if [[ $CONTENT_TYPE == *"application/javascript"* ]]; then
|
||||
echo "✅ JavaScript files have correct Content-Type"
|
||||
echo " ${CONTENT_TYPE}"
|
||||
else
|
||||
echo "❌ JavaScript Content-Type may be incorrect:"
|
||||
echo " ${CONTENT_TYPE}"
|
||||
fi
|
||||
else
|
||||
echo "❌ curl not available. Skip Content-Type test."
|
||||
fi
|
||||
|
||||
echo ""
|
||||
|
||||
# Test 5: Service Worker
|
||||
echo "Test 5: Service Worker Accessibility"
|
||||
echo "-----------------------------------"
|
||||
SW_URL="https://${IFRAME_DOMAIN}/sw.js"
|
||||
|
||||
if command -v curl &> /dev/null; then
|
||||
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "${SW_URL}" 2>/dev/null || echo "000")
|
||||
|
||||
if [ "$HTTP_CODE" = "200" ]; then
|
||||
echo "✅ Service Worker accessible (HTTP 200)"
|
||||
else
|
||||
echo "❌ Service Worker not accessible (HTTP ${HTTP_CODE})"
|
||||
fi
|
||||
else
|
||||
echo "❌ curl not available. Skip Service Worker test."
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "🎯 Next Steps"
|
||||
echo "============="
|
||||
echo "If all tests pass, your setup should be working!"
|
||||
echo ""
|
||||
echo "To test in Shakespeare:"
|
||||
echo "1. cd .."
|
||||
echo "2. npm run dev"
|
||||
echo "3. Open a project in Shakespeare"
|
||||
echo "4. Build the project"
|
||||
echo "5. Switch to preview tab"
|
||||
echo "6. Check browser console for any errors"
|
||||
echo ""
|
||||
echo "If you encounter issues:"
|
||||
echo "- Check browser console for CORS errors"
|
||||
echo "- Check Network tab for failed requests"
|
||||
echo "- Verify Cloudflare Worker logs in dashboard"
|
||||
echo "- Ensure .env has correct IFRAME_DOMAIN"
|
||||
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* Cloudflare Worker for Shakespeare iframe-fetch-client proxy
|
||||
*
|
||||
* This worker acts as a reverse proxy that:
|
||||
* 1. Removes X-Frame-Options and other headers that prevent iframe embedding
|
||||
* 2. Adds CORS headers for communication between iframe and parent
|
||||
* 3. Routes all subdomain requests to the deployed iframe-fetch-client
|
||||
*/
|
||||
|
||||
export default {
|
||||
async fetch(request, env, ctx) {
|
||||
const url = new URL(request.url);
|
||||
const { pathname, hostname, method } = url;
|
||||
|
||||
// Handle OPTIONS preflight requests for CORS
|
||||
if (method === 'OPTIONS') {
|
||||
return new Response(null, {
|
||||
headers: {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
||||
'Access-Control-Allow-Headers': '*',
|
||||
'Access-Control-Max-Age': '86400',
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Extract project ID from subdomain (e.g., project123.your-domain.com)
|
||||
const subdomain = hostname.split('.')[0];
|
||||
console.log(`[${new Date().toISOString()}] Request for project: ${subdomain}, path: ${pathname}, method: ${method}`);
|
||||
|
||||
// Route to your surge deployment (update this URL to your surge deployment)
|
||||
const surgeDomain = 'your-unique-name.surge.sh'; // TODO: Update this!
|
||||
const targetUrl = new URL(pathname, `https://${surgeDomain}`);
|
||||
|
||||
// Copy request headers, excluding problematic ones
|
||||
const headers = new Headers();
|
||||
for (const [key, value] of request.headers.entries()) {
|
||||
// Skip headers that might cause issues
|
||||
if (!['host', 'origin', 'referer'].includes(key.toLowerCase())) {
|
||||
headers.set(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// Forward the request to surge
|
||||
const response = await fetch(targetUrl, {
|
||||
method: method,
|
||||
headers: headers,
|
||||
body: request.body,
|
||||
redirect: 'follow',
|
||||
});
|
||||
|
||||
// Copy response headers but remove problematic ones
|
||||
const newHeaders = new Headers(response.headers);
|
||||
|
||||
// Remove headers that prevent iframe embedding
|
||||
newHeaders.delete('X-Frame-Options');
|
||||
newHeaders.delete('Content-Security-Policy');
|
||||
newHeaders.delete('X-Content-Type-Options');
|
||||
newHeaders.delete('Strict-Transport-Security');
|
||||
|
||||
// Add CORS headers for communication between iframe and parent
|
||||
newHeaders.set('Access-Control-Allow-Origin', '*');
|
||||
newHeaders.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
|
||||
newHeaders.set('Access-Control-Allow-Headers', '*');
|
||||
newHeaders.set('Access-Control-Allow-Credentials', 'false');
|
||||
|
||||
// Ensure correct content types for specific file extensions
|
||||
if (pathname.endsWith('.js')) {
|
||||
newHeaders.set('Content-Type', 'application/javascript; charset=utf-8');
|
||||
} else if (pathname.endsWith('.mjs')) {
|
||||
newHeaders.set('Content-Type', 'application/javascript; charset=utf-8');
|
||||
} else if (pathname.endsWith('.css')) {
|
||||
newHeaders.set('Content-Type', 'text/css; charset=utf-8');
|
||||
} else if (pathname.endsWith('.html')) {
|
||||
newHeaders.set('Content-Type', 'text/html; charset=utf-8');
|
||||
} else if (pathname.endsWith('.json')) {
|
||||
newHeaders.set('Content-Type', 'application/json; charset=utf-8');
|
||||
} else if (pathname.endsWith('.svg')) {
|
||||
newHeaders.set('Content-Type', 'image/svg+xml');
|
||||
} else if (pathname.endsWith('.png')) {
|
||||
newHeaders.set('Content-Type', 'image/png');
|
||||
} else if (pathname.endsWith('.jpg') || pathname.endsWith('.jpeg')) {
|
||||
newHeaders.set('Content-Type', 'image/jpeg');
|
||||
}
|
||||
|
||||
// Add security headers that are iframe-friendly
|
||||
newHeaders.set('X-Content-Type-Options', 'nosniff');
|
||||
|
||||
// Log successful proxy
|
||||
console.log(`[${new Date().toISOString()}] Successfully proxied: ${response.status} ${response.statusText}`);
|
||||
|
||||
return new Response(response.body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: newHeaders
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error(`[${new Date().toISOString()}] Proxy error for ${targetUrl}:`, error);
|
||||
|
||||
return new Response(JSON.stringify({
|
||||
error: 'Proxy error',
|
||||
message: error.message,
|
||||
url: targetUrl.toString(),
|
||||
timestamp: new Date().toISOString()
|
||||
}), {
|
||||
status: 502,
|
||||
statusText: 'Bad Gateway',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,16 @@
|
||||
name = "shakespeare-iframe-proxy"
|
||||
main = "worker.js"
|
||||
compatibility_date = "2023-10-30"
|
||||
|
||||
# Development environment
|
||||
[env.development]
|
||||
vars = { ENVIRONMENT = "development" }
|
||||
|
||||
# Production environment
|
||||
[env.production]
|
||||
vars = { ENVIRONMENT = "production" }
|
||||
|
||||
# Optional: Add custom domains for production
|
||||
# [env.production.routes]
|
||||
# pattern = "your-domain.com/*"
|
||||
# zone_name = "your-domain.com"
|
||||
@@ -19,6 +19,9 @@ import {
|
||||
import { FileTree } from './FileTree';
|
||||
import { FileEditor } from './FileEditor';
|
||||
|
||||
// Get iframe domain from environment variable
|
||||
const IFRAME_DOMAIN = import.meta.env.VITE_IFRAME_DOMAIN || 'local-shakespeare.dev';
|
||||
|
||||
interface PreviewPaneProps {
|
||||
projectId: string;
|
||||
activeTab: 'preview' | 'code';
|
||||
@@ -143,7 +146,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
|
||||
const navigateToPath = useCallback((path: string) => {
|
||||
if (iframeRef.current) {
|
||||
const baseUrl = `https://${projectId}.local-shakespeare.dev`;
|
||||
const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`;
|
||||
const newUrl = `${baseUrl}${path}`;
|
||||
iframeRef.current.src = newUrl;
|
||||
setCurrentPath(path);
|
||||
@@ -164,7 +167,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
setCurrentPath(path);
|
||||
|
||||
if (iframeRef.current) {
|
||||
const baseUrl = `https://${projectId}.local-shakespeare.dev`;
|
||||
const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`;
|
||||
const newUrl = `${baseUrl}${path}`;
|
||||
iframeRef.current.src = newUrl;
|
||||
}
|
||||
@@ -179,7 +182,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
setCurrentPath(path);
|
||||
|
||||
if (iframeRef.current) {
|
||||
const baseUrl = `https://${projectId}.local-shakespeare.dev`;
|
||||
const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`;
|
||||
const newUrl = `${baseUrl}${path}`;
|
||||
iframeRef.current.src = newUrl;
|
||||
}
|
||||
@@ -189,14 +192,14 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
const sendResponse = useCallback((message: JSONRPCResponse) => {
|
||||
if (iframeRef.current?.contentWindow) {
|
||||
console.log(`Sending response to iframe:`, message);
|
||||
const targetOrigin = `https://${projectId}.local-shakespeare.dev`;
|
||||
const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
|
||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
const sendError = useCallback((message: JSONRPCResponse) => {
|
||||
if (iframeRef.current?.contentWindow) {
|
||||
const targetOrigin = `https://${projectId}.local-shakespeare.dev`;
|
||||
const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
|
||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
||||
}
|
||||
}, [projectId]);
|
||||
@@ -235,7 +238,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
try {
|
||||
// Parse the URL and validate origin
|
||||
const url = new URL(fetchRequest.url);
|
||||
const expectedOrigin = `https://${projectId}.local-shakespeare.dev`;
|
||||
const expectedOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
|
||||
|
||||
if (url.origin !== expectedOrigin) {
|
||||
console.log(`Invalid origin: ${url.origin}, expected: ${expectedOrigin}`);
|
||||
@@ -331,7 +334,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
useEffect(() => {
|
||||
const handleMessage = (event: MessageEvent) => {
|
||||
// Verify origin for security
|
||||
const expectedOrigin = `https://${projectId}.local-shakespeare.dev`;
|
||||
const expectedOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
|
||||
if (event.origin !== expectedOrigin) {
|
||||
console.log(`Ignoring message from unexpected origin: ${event.origin}, expected: ${expectedOrigin}`);
|
||||
return;
|
||||
@@ -492,7 +495,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
</div>
|
||||
<iframe
|
||||
ref={iframeRef}
|
||||
src={`https://${projectId}.local-shakespeare.dev${currentPath}`}
|
||||
src={`https://${projectId}.${IFRAME_DOMAIN}${currentPath}`}
|
||||
className="w-full flex-1 border-0"
|
||||
title="Project Preview"
|
||||
sandbox="allow-scripts allow-same-origin"
|
||||
|
||||
Reference in new issue
Block a user