Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## Unreleased

- added: Added change-server subscription timeout fallback.
- added: New `privacy` option argument to EdgeIo fetch function for NYM support.

## 2.39.0 (2026-01-16)

Expand Down
304 changes: 304 additions & 0 deletions android/src/main/java/app/edge/reactnative/core/BundleHTTPServer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,304 @@
package app.edge.reactnative.core;

import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

/**
* A simple HTTP server that serves files from the Android assets folder.
* Includes Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers
* required for SharedArrayBuffer support (needed by mixFetch web workers).
*/
class BundleHTTPServer {
private static final String TAG = "BundleHTTPServer";
private static final int DEFAULT_PORT = 3693;

private final Context mContext;
private final int mPort;
private final String mSecurityToken;
private ServerSocket mServerSocket;
private ExecutorService mExecutor;
private final AtomicBoolean mRunning = new AtomicBoolean(false);

public BundleHTTPServer(Context context, int port, String securityToken) {
mContext = context;
mPort = port;
mSecurityToken = securityToken;
}

public void start() {
if (mRunning.get()) {
return;
}

mExecutor = Executors.newCachedThreadPool();
mRunning.set(true);

new Thread(() -> {
try {
mServerSocket = new ServerSocket(mPort);
Log.d(TAG, "HTTP Server ready on localhost:" + mPort);

while (mRunning.get()) {
try {
Socket clientSocket = mServerSocket.accept();
mExecutor.execute(() -> handleConnection(clientSocket));
} catch (IOException e) {
if (mRunning.get()) {
Log.e(TAG, "Error accepting connection: " + e.getMessage());
}
}
}
} catch (IOException e) {
Log.e(TAG, "Failed to start HTTP server: " + e.getMessage());
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HTTP server port conflicts cause silent failures

Medium Severity

The BundleHTTPServer starts on hardcoded port 3693 without checking if the port is already in use. If the port is unavailable (another WebView instance, another app, etc.), the server fails silently. The WebView still attempts to load from localhost:3693, resulting in a broken app state with no recovery mechanism.

Fix in Cursor Fix in Web

}).start();
}

public void stop() {
mRunning.set(false);

if (mServerSocket != null) {
try {
mServerSocket.close();
} catch (IOException e) {
Log.e(TAG, "Error closing server socket: " + e.getMessage());
}
mServerSocket = null;
}

if (mExecutor != null) {
mExecutor.shutdown();
mExecutor = null;
}

Log.d(TAG, "HTTP Server stopped");
}

private void handleConnection(Socket clientSocket) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
OutputStream output = clientSocket.getOutputStream();

// Read the request line
String requestLine = reader.readLine();
if (requestLine == null || requestLine.isEmpty()) {
clientSocket.close();
return;
}

// Parse method and path
String[] parts = requestLine.split(" ");
if (parts.length < 2) {
sendResponse(output, 400, "Bad Request", "text/plain", "Bad Request".getBytes());
clientSocket.close();
return;
}

String method = parts[0];
String path = parts[1];

// Read and discard headers
String line;
while ((line = reader.readLine()) != null && !line.isEmpty()) {
// Just consume headers
}

// Only support GET
if (!method.equals("GET")) {
sendResponse(output, 405, "Method Not Allowed", "text/plain", "Method Not Allowed".getBytes());
clientSocket.close();
return;
}

// Remove query parameters
int queryIndex = path.indexOf('?');
if (queryIndex > 0) {
path = path.substring(0, queryIndex);
}

// Serve index.html for root path
if (path.equals("/")) {
path = "/index.html";
}

// Handle plugin bundle requests (e.g., /plugin/edge-currency-accountbased.bundle/edge-currency-accountbased.js)
if (path.startsWith("/plugin/")) {
String pluginPath = path.substring("/plugin/".length());
servePluginFile(output, pluginPath);
clientSocket.close();
return;
}

// Remove leading slash and prepend assets path
String assetPath = "edge-core-js" + path;

// Try to read the asset
try {
AssetManager assetManager = mContext.getAssets();
InputStream inputStream = assetManager.open(assetPath);
byte[] data = readAllBytes(inputStream);
inputStream.close();

// For index.html, inject the security token so the page can verify itself
if (path.equals("/index.html")) {
String html = new String(data, "UTF-8");
String tokenScript = "<script>window.__EDGE_BUNDLE_SECURITY_TOKEN__=\"" + mSecurityToken + "\";</script>";
html = html.replace("<head>", "<head>\n " + tokenScript);
data = html.getBytes("UTF-8");
}

String mimeType = getMimeType(path);
sendResponse(output, 200, "OK", mimeType, data);
} catch (IOException e) {
Log.d(TAG, "File not found: " + assetPath);
sendResponse(output, 404, "Not Found", "text/plain", "Not Found".getBytes());
}

clientSocket.close();
} catch (IOException e) {
Log.e(TAG, "Error handling connection: " + e.getMessage());
try {
clientSocket.close();
} catch (IOException ignored) {
}
}
}

private void servePluginFile(OutputStream output, String pluginPath) throws IOException {
AssetManager assetManager = mContext.getAssets();
byte[] data = null;

// Plugin path format: "edge-currency-accountbased.bundle/edge-currency-accountbased.js"
// or just: "plugin-bundle.js"
// Try multiple asset path patterns
String[] pathsToTry;

if (pluginPath.contains(".bundle/")) {
// Extract bundle name and file name
String[] parts = pluginPath.split("\\.bundle/");
if (parts.length >= 2) {
String bundleName = parts[0];
String fileName = parts[1];
pathsToTry = new String[] {
pluginPath, // As-is
bundleName + "/" + fileName, // Without .bundle
bundleName + ".bundle/" + fileName, // With .bundle as folder
fileName // Just the filename
};
} else {
pathsToTry = new String[] { pluginPath };
}
} else {
// Just a filename like "plugin-bundle.js"
// Try to find it in a corresponding .bundle folder first
String fileName = pluginPath;
int dotIndex = fileName.lastIndexOf('.');
if (dotIndex > 0) {
String baseName = fileName.substring(0, dotIndex);
pathsToTry = new String[] {
baseName + ".bundle/" + fileName, // e.g., plugin-bundle.bundle/plugin-bundle.js
baseName + "/" + fileName, // e.g., plugin-bundle/plugin-bundle.js
pluginPath // Just the filename
};
} else {
pathsToTry = new String[] { pluginPath };
}
}

for (String assetPath : pathsToTry) {
try {
InputStream inputStream = assetManager.open(assetPath);
data = readAllBytes(inputStream);
inputStream.close();
Log.d(TAG, "Found plugin at: " + assetPath);
break;
} catch (IOException e) {
// Try next path
Log.d(TAG, "Plugin not found at: " + assetPath);
}
}

if (data != null) {
String mimeType = getMimeType(pluginPath);
sendResponse(output, 200, "OK", mimeType, data);
} else {
Log.e(TAG, "Plugin file not found: " + pluginPath);
sendResponse(output, 404, "Not Found", "text/plain", ("Not Found: " + pluginPath).getBytes());
}
}

private void sendResponse(OutputStream output, int code, String status, String contentType, byte[] body)
throws IOException {
StringBuilder headers = new StringBuilder();
headers.append("HTTP/1.1 ").append(code).append(" ").append(status).append("\r\n");
headers.append("Content-Type: ").append(contentType).append("\r\n");
headers.append("Content-Length: ").append(body.length).append("\r\n");
headers.append("Connection: close\r\n");
headers.append("Server: EdgeCoreBundleServer/1.0\r\n");
// Cross-origin isolation headers required for SharedArrayBuffer (needed by mixFetch web workers)
headers.append("Cross-Origin-Opener-Policy: same-origin\r\n");
headers.append("Cross-Origin-Embedder-Policy: require-corp\r\n");
headers.append("\r\n");

output.write(headers.toString().getBytes("UTF-8"));
output.write(body);
output.flush();
}

private byte[] readAllBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
byte[] chunk = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(chunk)) != -1) {
buffer.write(chunk, 0, bytesRead);
}
return buffer.toByteArray();
}

private String getMimeType(String path) {
String lowerPath = path.toLowerCase();
if (lowerPath.endsWith(".html") || lowerPath.endsWith(".htm")) {
return "text/html";
} else if (lowerPath.endsWith(".js")) {
return "application/javascript";
} else if (lowerPath.endsWith(".css")) {
return "text/css";
} else if (lowerPath.endsWith(".json")) {
return "application/json";
} else if (lowerPath.endsWith(".png")) {
return "image/png";
} else if (lowerPath.endsWith(".jpg") || lowerPath.endsWith(".jpeg")) {
return "image/jpeg";
} else if (lowerPath.endsWith(".gif")) {
return "image/gif";
} else if (lowerPath.endsWith(".svg")) {
return "image/svg+xml";
} else if (lowerPath.endsWith(".woff")) {
return "font/woff";
} else if (lowerPath.endsWith(".woff2")) {
return "font/woff2";
} else if (lowerPath.endsWith(".ttf")) {
return "font/ttf";
} else if (lowerPath.endsWith(".wasm")) {
return "application/wasm";
} else if (lowerPath.endsWith(".xml")) {
return "application/xml";
} else if (lowerPath.endsWith(".txt")) {
return "text/plain";
}
return "application/octet-stream";
}
}
Loading
Loading