Browse Source
Remove CORS headers to enable universal image support and fix local API server settings. ## Changes **Remove CORS Headers** - Remove Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers - Enables images from any domain (Facebook, Medium, arbitrary websites) - Database falls back to IndexedDB mode (minimal performance impact) **Fix Local Development Configuration** - Set LOCAL_ENDORSER_API_SERVER to http://127.0.0.1:3000 (was "/api") - Create .env.development with local API server config - Fix ensureCorrectApiServer() method in HomeView.vue - "Use Local" button now sets proper localhost address **Fix Settings Cache Issues** - Add PlatformServiceMixin to AccountViewView.vue - Disable settings caching to prevent stale data - Settings changes now apply immediately without browser refresh ## Impact **Tradeoffs:** - Lost: ~2x SharedArrayBuffer database performance - Gained: Universal image support from any domain - Result: Better user experience, database still fast via IndexedDB **Files Modified:** - Configuration: vite.config.*.mts, index.html, .env.development - Source: constants/app.ts, libs/util.ts, views/*.vue, utils/PlatformServiceMixin.ts ## Rationale For a community platform, universal image support is more critical than marginal database performance gains. Users share images from arbitrary websites, making CORS restrictions incompatible with Time Safari's core mission.pull/142/head
13 changed files with 589 additions and 223 deletions
@ -1,13 +1 @@ |
|||
# Only the variables that start with VITE_ are seen in the application import.meta.env in Vue. |
|||
|
|||
# iOS doesn't like spaces in the app title. |
|||
TIME_SAFARI_APP_TITLE="TimeSafari_Dev" |
|||
VITE_APP_SERVER=http://localhost:8080 |
|||
# This is the claim ID for actions in the BVC project, with the JWT ID on this environment (not production). |
|||
VITE_BVC_MEETUPS_PROJECT_CLAIM_ID=https://endorser.ch/entity/01HWE8FWHQ1YGP7GFZYYPS272F |
|||
VITE_DEFAULT_ENDORSER_API_SERVER=http://localhost:3000 |
|||
# Using shared server by default to ease setup, which works for shared test users. |
|||
VITE_DEFAULT_IMAGE_API_SERVER=https://test-image-api.timesafari.app |
|||
VITE_DEFAULT_PARTNER_API_SERVER=http://localhost:3000 |
|||
#VITE_DEFAULT_PUSH_SERVER... can't be set up with localhost domain |
|||
VITE_PASSKEYS_ENABLED=true |
|||
VITE_DEFAULT_ENDORSER_API_SERVER=http://127.0.0.1:3000 |
|||
|
@ -0,0 +1,116 @@ |
|||
# CORS Disabled for Universal Image Support |
|||
|
|||
## Decision Summary |
|||
|
|||
CORS headers have been **disabled** to support Time Safari's core mission: enabling users to share images from any domain without restrictions. |
|||
|
|||
## What Changed |
|||
|
|||
### ❌ Removed CORS Headers |
|||
- `Cross-Origin-Opener-Policy: same-origin` |
|||
- `Cross-Origin-Embedder-Policy: require-corp` |
|||
|
|||
### ✅ Results |
|||
- Images from **any domain** now work in development and production |
|||
- No proxy configuration needed |
|||
- No whitelist of supported image hosts |
|||
- True community-driven image sharing |
|||
|
|||
## Technical Tradeoffs |
|||
|
|||
### 🔻 Lost: SharedArrayBuffer Performance |
|||
- **Before**: Fast SQLite operations via SharedArrayBuffer |
|||
- **After**: Slightly slower IndexedDB fallback mode |
|||
- **Impact**: Minimal for typical usage - absurd-sql automatically falls back |
|||
|
|||
### 🔺 Gained: Universal Image Support |
|||
- **Before**: Only specific domains worked (TimeSafari, Flickr, Imgur, etc.) |
|||
- **After**: Any image URL works immediately |
|||
- **Impact**: Massive improvement for user experience |
|||
|
|||
## Architecture Impact |
|||
|
|||
### Database Operations |
|||
```typescript |
|||
// absurd-sql automatically detects SharedArrayBuffer availability |
|||
if (typeof SharedArrayBuffer === "undefined") { |
|||
// Uses IndexedDB backend (current state) |
|||
console.log("Using IndexedDB fallback mode"); |
|||
} else { |
|||
// Uses SharedArrayBuffer (not available due to disabled CORS) |
|||
console.log("Using SharedArrayBuffer mode"); |
|||
} |
|||
``` |
|||
|
|||
### Image Loading |
|||
```typescript |
|||
// All images load directly now |
|||
export function transformImageUrlForCors(imageUrl: string): string { |
|||
return imageUrl; // No transformation needed |
|||
} |
|||
``` |
|||
|
|||
## Why This Was The Right Choice |
|||
|
|||
### Time Safari's Use Case |
|||
- **Community platform** where users share content from anywhere |
|||
- **User-generated content** includes images from arbitrary websites |
|||
- **Flexibility** is more important than marginal performance gains |
|||
|
|||
### Alternative Would Require |
|||
- Pre-configuring proxies for every possible image hosting service |
|||
- Constantly updating proxy list as users find new sources |
|||
- Poor user experience when images fail to load |
|||
- Impossible to support the "any domain" requirement |
|||
|
|||
## Performance Comparison |
|||
|
|||
### Database Operations |
|||
- **SharedArrayBuffer**: ~2x faster for large operations |
|||
- **IndexedDB**: Still very fast for typical Time Safari usage |
|||
- **Real Impact**: Negligible for typical user operations |
|||
|
|||
### Image Loading |
|||
- **With CORS**: Many images failed to load in development |
|||
- **Without CORS**: All images load immediately |
|||
- **Real Impact**: Massive improvement in user experience |
|||
|
|||
## Browser Compatibility |
|||
|
|||
| Browser | SharedArrayBuffer | IndexedDB | Image Loading | |
|||
|---------|------------------|-----------|---------------| |
|||
| Chrome | ❌ (CORS disabled) | ✅ Works | ✅ Any domain | |
|||
| Firefox | ❌ (CORS disabled) | ✅ Works | ✅ Any domain | |
|||
| Safari | ❌ (CORS disabled) | ✅ Works | ✅ Any domain | |
|||
| Edge | ❌ (CORS disabled) | ✅ Works | ✅ Any domain | |
|||
|
|||
## Migration Notes |
|||
|
|||
### For Developers |
|||
- No code changes needed |
|||
- `transformImageUrlForCors()` still exists but returns original URL |
|||
- All existing image references work without modification |
|||
|
|||
### For Users |
|||
- Images from any website now work immediately |
|||
- No more "image failed to load" issues in development |
|||
- Consistent behavior between development and production |
|||
|
|||
## Future Considerations |
|||
|
|||
### If Performance Becomes Critical |
|||
1. **Selective CORS**: Enable only for specific operations |
|||
2. **Service Worker**: Handle image proxying at service worker level |
|||
3. **Build-time Processing**: Pre-process images during build |
|||
4. **User Education**: Guide users toward optimized image hosting |
|||
|
|||
### Monitoring |
|||
- Track database operation performance |
|||
- Monitor for any user-reported slowness |
|||
- Consider re-enabling SharedArrayBuffer if usage patterns change |
|||
|
|||
## Conclusion |
|||
|
|||
This change prioritizes **user experience** and **community functionality** over marginal performance gains. The database still works efficiently via IndexedDB, while images now work universally without configuration. |
|||
|
|||
For a community platform like Time Safari, the ability to share images from any domain is fundamental to the user experience and mission. |
@ -0,0 +1,240 @@ |
|||
# CORS Image Loading Solution |
|||
|
|||
## Overview |
|||
|
|||
This document describes the implementation of a comprehensive image loading solution that works in a cross-origin isolated environment (required for SharedArrayBuffer support) while accepting images from any domain. |
|||
|
|||
## Problem Statement |
|||
|
|||
When using SharedArrayBuffer (required for absurd-sql), browsers enforce a cross-origin isolated environment with these headers: |
|||
- `Cross-Origin-Opener-Policy: same-origin` |
|||
- `Cross-Origin-Embedder-Policy: require-corp` |
|||
|
|||
This isolation prevents loading external resources (including images) unless they have proper CORS headers, which most image hosting services don't provide. |
|||
|
|||
## Solution Architecture |
|||
|
|||
### 1. Multi-Tier Proxy System |
|||
|
|||
The solution uses a multi-tier approach to handle images from various sources: |
|||
|
|||
#### Tier 1: Specific Domain Proxies (Development Only) |
|||
- **TimeSafari Images**: `/image-proxy/` → `https://image.timesafari.app/` |
|||
- **Flickr Images**: `/flickr-proxy/` → `https://live.staticflickr.com/` |
|||
- **Imgur Images**: `/imgur-proxy/` → `https://i.imgur.com/` |
|||
- **GitHub Raw**: `/github-proxy/` → `https://raw.githubusercontent.com/` |
|||
- **Unsplash**: `/unsplash-proxy/` → `https://images.unsplash.com/` |
|||
|
|||
#### Tier 2: Universal CORS Proxy (Development Only) |
|||
- **Any External Domain**: Uses `https://api.allorigins.win/raw?url=` for arbitrary domains |
|||
|
|||
#### Tier 3: Direct Loading (Production) |
|||
- **Production Mode**: All images load directly without proxying |
|||
|
|||
### 2. Smart URL Transformation |
|||
|
|||
The `transformImageUrlForCors` function automatically: |
|||
- Detects the image source domain |
|||
- Routes through appropriate proxy in development |
|||
- Preserves original URLs in production |
|||
- Handles edge cases (data URLs, relative paths, etc.) |
|||
|
|||
## Implementation Details |
|||
|
|||
### Configuration Files |
|||
|
|||
#### `vite.config.common.mts` |
|||
```typescript |
|||
server: { |
|||
headers: { |
|||
// Required for SharedArrayBuffer support |
|||
'Cross-Origin-Opener-Policy': 'same-origin', |
|||
'Cross-Origin-Embedder-Policy': 'require-corp' |
|||
}, |
|||
proxy: { |
|||
// Specific domain proxies with CORS headers |
|||
'/image-proxy': { /* TimeSafari images */ }, |
|||
'/flickr-proxy': { /* Flickr images */ }, |
|||
'/imgur-proxy': { /* Imgur images */ }, |
|||
'/github-proxy': { /* GitHub raw images */ }, |
|||
'/unsplash-proxy': { /* Unsplash images */ } |
|||
} |
|||
} |
|||
``` |
|||
|
|||
#### `src/libs/util.ts` |
|||
```typescript |
|||
export function transformImageUrlForCors(imageUrl: string): string { |
|||
// Development mode: Transform URLs to use proxies |
|||
// Production mode: Return original URLs |
|||
|
|||
// Handle specific domains with dedicated proxies |
|||
// Fall back to universal CORS proxy for arbitrary domains |
|||
} |
|||
``` |
|||
|
|||
### Usage in Components |
|||
|
|||
All image loading in components uses the transformation function: |
|||
|
|||
```typescript |
|||
// In Vue components |
|||
import { transformImageUrlForCors } from "../libs/util"; |
|||
|
|||
// Transform image URL before using |
|||
const imageUrl = transformImageUrlForCors(originalImageUrl); |
|||
``` |
|||
|
|||
```html |
|||
<!-- In templates --> |
|||
<img :src="transformImageUrlForCors(imageUrl)" alt="Description" /> |
|||
``` |
|||
|
|||
## Benefits |
|||
|
|||
### ✅ SharedArrayBuffer Support |
|||
- Maintains cross-origin isolation required for SharedArrayBuffer |
|||
- Enables fast SQLite database operations via absurd-sql |
|||
- Provides better performance than IndexedDB fallback |
|||
|
|||
### ✅ Universal Image Support |
|||
- Handles images from any domain |
|||
- No need to pre-configure every possible image source |
|||
- Graceful fallback for unknown domains |
|||
|
|||
### ✅ Development/Production Flexibility |
|||
- Proxy system only active in development |
|||
- Production uses direct URLs for maximum performance |
|||
- No proxy server required in production |
|||
|
|||
### ✅ Automatic Detection |
|||
- Smart URL transformation based on domain patterns |
|||
- Preserves relative URLs and data URLs |
|||
- Handles edge cases gracefully |
|||
|
|||
## Testing |
|||
|
|||
### Automated Testing |
|||
Run the test suite to verify URL transformation: |
|||
|
|||
```typescript |
|||
import { testCorsImageTransformation } from './libs/test-cors-images'; |
|||
|
|||
// Console output shows transformation results |
|||
testCorsImageTransformation(); |
|||
``` |
|||
|
|||
### Visual Testing |
|||
Create test image elements to verify loading: |
|||
|
|||
```typescript |
|||
import { createTestImageElements } from './libs/test-cors-images'; |
|||
|
|||
// Creates visual test panel in browser |
|||
createTestImageElements(); |
|||
``` |
|||
|
|||
### Manual Testing |
|||
1. Start development server: `npm run dev` |
|||
2. Open browser console to see transformation logs |
|||
3. Check Network tab for proxy requests |
|||
4. Verify images load correctly from various domains |
|||
|
|||
## Security Considerations |
|||
|
|||
### Development Environment |
|||
- CORS proxies are only used in development |
|||
- External proxy services (allorigins.win) are used for testing |
|||
- No sensitive data is exposed through proxies |
|||
|
|||
### Production Environment |
|||
- All images load directly without proxying |
|||
- No dependency on external proxy services |
|||
- Original security model maintained |
|||
|
|||
### Privacy |
|||
- Image URLs are not logged or stored by proxy services |
|||
- Proxy requests are only made during development |
|||
- No tracking or analytics in proxy chain |
|||
|
|||
## Performance Impact |
|||
|
|||
### Development |
|||
- Slight latency from proxy requests |
|||
- Additional network hops for external domains |
|||
- More verbose logging for debugging |
|||
|
|||
### Production |
|||
- No performance impact |
|||
- Direct image loading as before |
|||
- No proxy overhead |
|||
|
|||
## Troubleshooting |
|||
|
|||
### Common Issues |
|||
|
|||
#### Images Not Loading in Development |
|||
1. Check console for proxy errors |
|||
2. Verify CORS headers are set |
|||
3. Test with different image URLs |
|||
4. Check network connectivity to proxy services |
|||
|
|||
#### SharedArrayBuffer Not Available |
|||
1. Verify CORS headers are set in server configuration |
|||
2. Check that site is served over HTTPS (or localhost) |
|||
3. Ensure browser supports SharedArrayBuffer |
|||
|
|||
#### Proxy Service Unavailable |
|||
1. Check if allorigins.win is accessible |
|||
2. Consider using alternative CORS proxy services |
|||
3. Temporarily disable CORS headers for testing |
|||
|
|||
### Debug Commands |
|||
|
|||
```bash |
|||
# Check if SharedArrayBuffer is available |
|||
console.log(typeof SharedArrayBuffer !== 'undefined'); |
|||
|
|||
# Test URL transformation |
|||
import { transformImageUrlForCors } from './libs/util'; |
|||
console.log(transformImageUrlForCors('https://example.com/image.jpg')); |
|||
|
|||
# Run comprehensive tests |
|||
import { testCorsImageTransformation } from './libs/test-cors-images'; |
|||
testCorsImageTransformation(); |
|||
``` |
|||
|
|||
## Migration Guide |
|||
|
|||
### From Previous Implementation |
|||
1. CORS headers are now required for SharedArrayBuffer |
|||
2. Image URLs automatically transformed in development |
|||
3. No changes needed to existing image loading code |
|||
4. Test thoroughly in both development and production |
|||
|
|||
### Adding New Image Sources |
|||
1. Add specific proxy for frequently used domains |
|||
2. Update `transformImageUrlForCors` function |
|||
3. Add CORS headers to proxy configuration |
|||
4. Test with sample images |
|||
|
|||
## Future Enhancements |
|||
|
|||
### Possible Improvements |
|||
1. **Local Proxy Server**: Run dedicated proxy server for development |
|||
2. **Caching**: Cache proxy responses for better performance |
|||
3. **Fallback Chain**: Multiple proxy services for reliability |
|||
4. **Image Optimization**: Compress/resize images through proxy |
|||
5. **Analytics**: Track image loading success/failure rates |
|||
|
|||
### Alternative Approaches |
|||
1. **Service Worker**: Intercept image requests at service worker level |
|||
2. **Build-time Processing**: Pre-process images during build |
|||
3. **CDN Integration**: Use CDN with proper CORS headers |
|||
4. **Local Storage**: Cache images in browser storage |
|||
|
|||
## Conclusion |
|||
|
|||
This solution provides a robust, scalable approach to image loading in a cross-origin isolated environment while maintaining the benefits of SharedArrayBuffer support. The multi-tier proxy system ensures compatibility with any image source while optimizing for performance and security. |
|||
|
|||
For questions or issues, refer to the troubleshooting section or consult the development team. |
@ -0,0 +1,180 @@ |
|||
# Image Hosting Guide for Cross-Origin Isolated Environment |
|||
|
|||
## Quick Reference |
|||
|
|||
### ✅ Supported Image Sources (Work in Development) |
|||
|
|||
| Service | Proxy Endpoint | Example URL | |
|||
|---------|---------------|-------------| |
|||
| TimeSafari | `/image-proxy/` | `https://image.timesafari.app/abc123.jpg` | |
|||
| Flickr | `/flickr-proxy/` | `https://live.staticflickr.com/123/456.jpg` | |
|||
| Imgur | `/imgur-proxy/` | `https://i.imgur.com/example.jpg` | |
|||
| GitHub Raw | `/github-proxy/` | `https://raw.githubusercontent.com/user/repo/main/image.png` | |
|||
| Unsplash | `/unsplash-proxy/` | `https://images.unsplash.com/photo-123456` | |
|||
| Facebook | `/facebook-proxy/` | `https://www.facebook.com/images/groups/...` | |
|||
| Medium | `/medium-proxy/` | `https://miro.medium.com/v2/resize:fit:180/...` | |
|||
| Meetup | `/meetup-proxy/` | `https://secure.meetupstatic.com/photos/...` | |
|||
|
|||
### ⚠️ Problematic Image Sources (May Not Work in Development) |
|||
|
|||
- Random external websites without CORS headers |
|||
- WordPress uploads from arbitrary domains |
|||
- Custom CDNs without proper CORS configuration |
|||
- Any service that doesn't send `Cross-Origin-Resource-Policy: cross-origin` |
|||
|
|||
## Why This Happens |
|||
|
|||
In development mode, we enable SharedArrayBuffer for fast SQLite operations, which requires: |
|||
- `Cross-Origin-Opener-Policy: same-origin` |
|||
- `Cross-Origin-Embedder-Policy: require-corp` |
|||
|
|||
These headers create a **cross-origin isolated environment** that blocks resources unless they have proper CORS headers. |
|||
|
|||
## Solutions |
|||
|
|||
### 1. Use Supported Image Hosting Services |
|||
|
|||
**Recommended services that work well:** |
|||
- **Imgur**: Free, no registration required, direct links |
|||
- **GitHub**: If you have images in repositories |
|||
- **Unsplash**: For stock photos |
|||
- **TimeSafari Image Server**: For app-specific images |
|||
|
|||
### 2. Add New Image Hosting Proxies |
|||
|
|||
If you frequently use images from a specific domain, add a proxy: |
|||
|
|||
#### Step 1: Add Proxy to `vite.config.common.mts` |
|||
```typescript |
|||
'/yourservice-proxy': { |
|||
target: 'https://yourservice.com', |
|||
changeOrigin: true, |
|||
secure: true, |
|||
followRedirects: true, |
|||
rewrite: (path) => path.replace(/^\/yourservice-proxy/, ''), |
|||
configure: (proxy) => { |
|||
proxy.on('proxyRes', (proxyRes, req, res) => { |
|||
proxyRes.headers['Access-Control-Allow-Origin'] = '*'; |
|||
proxyRes.headers['Access-Control-Allow-Methods'] = 'GET, OPTIONS'; |
|||
proxyRes.headers['Cross-Origin-Resource-Policy'] = 'cross-origin'; |
|||
}); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
#### Step 2: Update Transform Function in `src/libs/util.ts` |
|||
```typescript |
|||
// Transform YourService URLs to use proxy |
|||
if (imageUrl.startsWith("https://yourservice.com/")) { |
|||
const imagePath = imageUrl.replace("https://yourservice.com/", ""); |
|||
return `/yourservice-proxy/${imagePath}`; |
|||
} |
|||
``` |
|||
|
|||
### 3. Use Alternative Image Sources |
|||
|
|||
For frequently failing domains, consider: |
|||
- Upload images to Imgur or GitHub |
|||
- Use a CDN with proper CORS headers |
|||
- Host images on your own domain with CORS enabled |
|||
|
|||
## Development vs Production |
|||
|
|||
### Development Mode |
|||
- Images from supported services work through proxies |
|||
- Unsupported images may fail to load |
|||
- Console warnings show which images have issues |
|||
|
|||
### Production Mode |
|||
- All images load directly without proxies |
|||
- No CORS restrictions in production |
|||
- Better performance without proxy overhead |
|||
|
|||
## Testing Image Sources |
|||
|
|||
### Check if an Image Source Works |
|||
```bash |
|||
# Test in browser console: |
|||
fetch('https://example.com/image.jpg', { mode: 'cors' }) |
|||
.then(response => console.log('✅ Works:', response.status)) |
|||
.catch(error => console.log('❌ Blocked:', error)); |
|||
``` |
|||
|
|||
### Visual Testing |
|||
```typescript |
|||
import { createTestImageElements } from './libs/test-cors-images'; |
|||
createTestImageElements(); // Creates visual test panel |
|||
``` |
|||
|
|||
## Common Error Messages |
|||
|
|||
### `ERR_BLOCKED_BY_RESPONSE.NotSameOriginAfterDefaultedToSameOriginByCoep` |
|||
**Cause**: Image source doesn't send required CORS headers |
|||
**Solution**: Use a supported image hosting service or add a proxy |
|||
|
|||
### `ERR_NETWORK` or `ERR_INTERNET_DISCONNECTED` |
|||
**Cause**: Proxy service is unavailable |
|||
**Solution**: Check internet connection or use alternative image source |
|||
|
|||
### Images Load in Production but Not Development |
|||
**Cause**: Normal behavior - development has stricter CORS requirements |
|||
**Solution**: Use supported image sources for development testing |
|||
|
|||
## Best Practices |
|||
|
|||
### For New Projects |
|||
1. Use supported image hosting services from the start |
|||
2. Upload user images to Imgur or similar service |
|||
3. Host critical images on your own domain with CORS enabled |
|||
|
|||
### For Existing Projects |
|||
1. Identify frequently used image domains in console warnings |
|||
2. Add proxies for the most common domains |
|||
3. Gradually migrate to supported image hosting services |
|||
|
|||
### For User-Generated Content |
|||
1. Provide upload functionality to supported services |
|||
2. Validate image URLs against supported domains |
|||
3. Show helpful error messages for unsupported sources |
|||
|
|||
## Troubleshooting |
|||
|
|||
### Image Not Loading? |
|||
1. Check browser console for error messages |
|||
2. Verify the domain is in the supported list |
|||
3. Test if the image loads in production mode |
|||
4. Consider adding a proxy for that domain |
|||
|
|||
### Proxy Not Working? |
|||
1. Check if the target service allows proxying |
|||
2. Verify CORS headers are being set correctly |
|||
3. Test with a simpler image URL from the same domain |
|||
|
|||
### Performance Issues? |
|||
1. Proxies add latency in development only |
|||
2. Production uses direct image loading |
|||
3. Consider using a local image cache for development |
|||
|
|||
## Quick Fixes |
|||
|
|||
### For Immediate Issues |
|||
```typescript |
|||
// Temporary fallback: disable CORS headers for testing |
|||
// In vite.config.common.mts, comment out: |
|||
// headers: { |
|||
// 'Cross-Origin-Opener-Policy': 'same-origin', |
|||
// 'Cross-Origin-Embedder-Policy': 'require-corp' |
|||
// }, |
|||
``` |
|||
**Note**: This disables SharedArrayBuffer performance benefits. |
|||
|
|||
### For Long-term Solution |
|||
- Use supported image hosting services |
|||
- Add proxies for frequently used domains |
|||
- Migrate critical images to your own CORS-enabled CDN |
|||
|
|||
## Summary |
|||
|
|||
The cross-origin isolated environment is necessary for SharedArrayBuffer performance but requires careful image source management. Use the supported services, add proxies for common domains, and accept that some external images may not work in development mode. |
|||
|
|||
This is a development-only limitation - production deployments work with any image source. |
Loading…
Reference in new issue