mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
iframe-fetch-client: encode body as base64 text (to make binary files work)
This commit is contained in:
7 files changed
+101
-17
No files matched your search
@@ -41,7 +41,7 @@ All messages follow JSON-RPC 2.0 specification:
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "fetch",
|
||||
"params": {
|
||||
"params": {
|
||||
"request": {
|
||||
"url": "https://app123.example.com/assets/main.js",
|
||||
"method": "GET",
|
||||
@@ -54,6 +54,23 @@ All messages follow JSON-RPC 2.0 specification:
|
||||
"id": 123
|
||||
}
|
||||
|
||||
// POST Request with JSON body
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "fetch",
|
||||
"params": {
|
||||
"request": {
|
||||
"url": "https://app123.example.com/api/data",
|
||||
"method": "POST",
|
||||
"headers": {
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
"body": "eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9" // base64 of: {"name":"John","age":30}
|
||||
}
|
||||
},
|
||||
"id": 124
|
||||
}
|
||||
|
||||
// Success Response
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
@@ -64,7 +81,7 @@ All messages follow JSON-RPC 2.0 specification:
|
||||
"Content-Type": "application/javascript",
|
||||
"Cache-Control": "no-cache"
|
||||
},
|
||||
"body": "console.log('hello');"
|
||||
"body": "Y29uc29sZS5sb2coJ2hlbGxvJyk7"
|
||||
},
|
||||
"id": 123
|
||||
}
|
||||
@@ -94,14 +111,14 @@ full request body support
|
||||
- `url` (string): Full URL of the request
|
||||
- `method` (string): HTTP method (GET, POST, etc.)
|
||||
- `headers` (object): Request headers as key-value pairs
|
||||
- `body` (string|null): Request body as string, or null if no body
|
||||
- `body` (string|null): Request body as base64 encoded string, or null if no body
|
||||
|
||||
**Result:**
|
||||
|
||||
- `status` (number): HTTP status code (200, 404, etc.)
|
||||
- `statusText` (string): HTTP status text ("OK", "Not Found", etc.)
|
||||
- `headers` (object): Response headers as key-value pairs
|
||||
- `body` (string|null): Response body content (null if status is 204)
|
||||
- `body` (string|null): Response body content as base64 encoded string (null if status is 204)
|
||||
|
||||
**Error Codes:**
|
||||
|
||||
@@ -117,8 +134,8 @@ full request body support
|
||||
- File uploads (as base64 strings)
|
||||
- Any HTTP method with body content
|
||||
|
||||
Request bodies are serialized as strings, so binary data should be
|
||||
base64-encoded.
|
||||
Request bodies must be base64-encoded strings when not null. This ensures
|
||||
consistent handling of both text and binary data across the messaging protocol.
|
||||
|
||||
## Implementation
|
||||
|
||||
@@ -153,6 +170,9 @@ class FetchClientParent {
|
||||
const url = new URL(fetchRequest.url);
|
||||
const path = url.pathname;
|
||||
|
||||
// Decode request body if present
|
||||
const requestBody = fetchRequest.body ? atob(fetchRequest.body) : null;
|
||||
|
||||
const file = this.files.get(path);
|
||||
|
||||
if (file) {
|
||||
@@ -166,7 +186,7 @@ class FetchClientParent {
|
||||
"Content-Type": file.contentType,
|
||||
"Cache-Control": "no-cache",
|
||||
},
|
||||
body: file.content,
|
||||
body: btoa(file.content), // base64 encode the response body
|
||||
},
|
||||
});
|
||||
} else {
|
||||
@@ -180,7 +200,7 @@ class FetchClientParent {
|
||||
headers: {
|
||||
"Content-Type": "text/plain",
|
||||
},
|
||||
body: `File not found: ${path}`,
|
||||
body: btoa(`File not found: ${path}`), // base64 encode the error message
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -264,6 +284,23 @@ class JSONRPCClient {
|
||||
}
|
||||
```
|
||||
|
||||
## Base64 Encoding
|
||||
|
||||
All request and response bodies must be base64 encoded when not null. This ensures:
|
||||
|
||||
- **Consistent Data Handling:** Both text and binary data are handled uniformly
|
||||
- **JSON Compatibility:** Avoids issues with special characters in JSON messages
|
||||
- **Binary Data Support:** Enables transmission of images, files, and other binary content
|
||||
|
||||
**Encoding/Decoding:**
|
||||
```javascript
|
||||
// Encoding (before sending)
|
||||
const encodedBody = btoa(originalBody);
|
||||
|
||||
// Decoding (after receiving)
|
||||
const decodedBody = atob(encodedBody);
|
||||
```
|
||||
|
||||
## Security
|
||||
|
||||
- **Origin Validation:** Always verify message origin
|
||||
|
||||
@@ -180,8 +180,17 @@ class FetchClient {
|
||||
|
||||
const response = await this.rpcClient.fetch(serializedRequest);
|
||||
|
||||
if (response.status !== 200) {
|
||||
throw new Error(`Failed to fetch site index: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
if (response.headers["Content-Type"] !== "text/html") {
|
||||
throw new Error(`Unexpected Content-Type: ${response.headers["Content-Type"]}`);
|
||||
}
|
||||
|
||||
const decoded = atob(response.body);
|
||||
|
||||
// Replace current document with the site index content
|
||||
this.replaceDocument(response.body);
|
||||
this.replaceDocument(decoded);
|
||||
} catch (error) {
|
||||
this.showError("Failed to load site index", error);
|
||||
}
|
||||
|
||||
@@ -48,7 +48,14 @@ function handleJSONRPCResponse(message) {
|
||||
|
||||
// Create response from serialized response
|
||||
const { status, statusText, headers, body } = result;
|
||||
const response = new Response(body, {
|
||||
|
||||
// Decode base64 body if present
|
||||
let decoded = null;
|
||||
if (typeof body === "string") {
|
||||
decoded = new Uint8Array(atob(body).split('').map(c => c.charCodeAt(0)));
|
||||
}
|
||||
|
||||
const response = new Response(decoded, {
|
||||
status: status || 200,
|
||||
statusText: statusText || "OK",
|
||||
headers: headers || {},
|
||||
@@ -65,8 +72,9 @@ async function requestViaJSONRPC(request) {
|
||||
let body = null;
|
||||
if (request.body) {
|
||||
try {
|
||||
// Convert body to string (JSON-serializable)
|
||||
body = await request.text();
|
||||
// Convert body to Uint8Array then base64 encode
|
||||
const bytes = await request.bytes();
|
||||
body = btoa(String.fromCharCode(...bytes));
|
||||
} catch (error) {
|
||||
reject(new Error(`Failed to serialize request body: ${error.message}`));
|
||||
return;
|
||||
|
||||
Generated
+7
@@ -43,6 +43,7 @@
|
||||
"@radix-ui/react-toggle-group": "^1.1.0",
|
||||
"@radix-ui/react-tooltip": "^1.1.4",
|
||||
"@soapbox.pub/streamdown": "^1.0.11",
|
||||
"@std/encoding": "npm:@jsr/std__encoding@^1.0.10",
|
||||
"@std/path": "npm:@jsr/std__path@^1.1.1",
|
||||
"@tanstack/react-query": "^5.56.2",
|
||||
"@unhead/addons": "^2.0.10",
|
||||
@@ -3246,6 +3247,12 @@
|
||||
"url": "https://github.com/sponsors/dcastil"
|
||||
}
|
||||
},
|
||||
"node_modules/@std/encoding": {
|
||||
"name": "@jsr/std__encoding",
|
||||
"version": "1.0.10",
|
||||
"resolved": "https://npm.jsr.io/~/11/@jsr/std__encoding/1.0.10.tgz",
|
||||
"integrity": "sha512-WK2njnDTyKefroRNk2Ooq7GStp6Y0ccAvr4To+Z/zecRAGe7+OSvH9DbiaHpAKwEi2KQbmpWMOYsdNt+TsdmSw=="
|
||||
},
|
||||
"node_modules/@std/path": {
|
||||
"name": "@jsr/std__path",
|
||||
"version": "1.1.1",
|
||||
|
||||
@@ -45,6 +45,7 @@
|
||||
"@radix-ui/react-toggle-group": "^1.1.0",
|
||||
"@radix-ui/react-tooltip": "^1.1.4",
|
||||
"@soapbox.pub/streamdown": "^1.0.11",
|
||||
"@std/encoding": "npm:@jsr/std__encoding@^1.0.10",
|
||||
"@std/path": "npm:@jsr/std__path@^1.1.1",
|
||||
"@tanstack/react-query": "^5.56.2",
|
||||
"@unhead/addons": "^2.0.10",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { encodeBase64 } from '@std/encoding/base64';
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
@@ -214,8 +215,9 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
|
||||
// SPA routing: try to serve the exact file first
|
||||
try {
|
||||
const file = await projectsManager.readFile(projectId, 'dist' + filePath);
|
||||
const bytes = await projectsManager.readFileBytes(projectId, 'dist' + filePath);
|
||||
console.log(`Serving file: ${filePath}`);
|
||||
|
||||
sendResponse({
|
||||
jsonrpc: '2.0',
|
||||
result: {
|
||||
@@ -225,7 +227,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
'Content-Type': getContentType(filePath),
|
||||
'Cache-Control': 'no-cache',
|
||||
},
|
||||
body: file,
|
||||
body: encodeBase64(bytes),
|
||||
},
|
||||
id
|
||||
});
|
||||
@@ -237,8 +239,9 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
|
||||
// SPA fallback: serve index.html for non-file requests
|
||||
try {
|
||||
const indexFile = await projectsManager.readFile(projectId, 'dist/index.html');
|
||||
const bytes = await projectsManager.readFileBytes(projectId, 'dist/index.html');
|
||||
console.log(`Serving index.html fallback for: ${path}`);
|
||||
|
||||
sendResponse({
|
||||
jsonrpc: '2.0',
|
||||
result: {
|
||||
@@ -248,13 +251,14 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
'Content-Type': 'text/html',
|
||||
'Cache-Control': 'no-cache',
|
||||
},
|
||||
body: indexFile,
|
||||
body: encodeBase64(bytes),
|
||||
},
|
||||
id
|
||||
});
|
||||
} catch {
|
||||
// Even index.html doesn't exist
|
||||
console.log(`No files found, returning 404 for: ${path}`);
|
||||
|
||||
sendResponse({
|
||||
jsonrpc: '2.0',
|
||||
result: {
|
||||
@@ -263,7 +267,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
headers: {
|
||||
'Content-Type': 'text/plain',
|
||||
},
|
||||
body: `File not found: ${path}`,
|
||||
body: encodeBase64(`File not found: ${path}`),
|
||||
},
|
||||
id
|
||||
});
|
||||
|
||||
@@ -205,6 +205,24 @@ export class ProjectsManager {
|
||||
}
|
||||
}
|
||||
|
||||
async readFileBytes(projectId: string, filePath: string): Promise<Uint8Array> {
|
||||
const fullPath = `${this.dir}/${projectId}/${filePath}`;
|
||||
try {
|
||||
const stat = await this.fs.stat(fullPath);
|
||||
if (stat.isFile()) {
|
||||
return await this.fs.readFile(fullPath);
|
||||
} else {
|
||||
throw new Error(`Path is not a file: ${filePath}`);
|
||||
}
|
||||
} catch (error) {
|
||||
const fsError = error as NodeJS.ErrnoException;
|
||||
if (fsError.code === 'ENOENT') {
|
||||
throw new Error(`File not found: ${filePath}`);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async writeFile(projectId: string, filePath: string, content: string): Promise<void> {
|
||||
const fullPath = `${this.dir}/${projectId}/${filePath}`;
|
||||
const dir = fullPath.split('/').slice(0, -1).join('/');
|
||||
|
||||
Reference in new issue
Block a user