602 lines
17 KiB
TypeScript
Raw Normal View History

2024-05-13 23:22:06 -07:00
import os from "os";
import path from "path";
import cors from "cors";
import express, { Express } from "express";
import dotenv from "dotenv";
import { createServer } from "http";
import { Server } from "socket.io";
import { z } from "zod";
import { User } from "./types";
2024-04-30 01:56:43 -04:00
import {
createFile,
deleteFile,
2024-05-11 17:23:45 -07:00
getFolder,
2024-05-09 22:32:21 -07:00
getProjectSize,
2024-04-30 01:56:43 -04:00
getSandboxFiles,
renameFile,
saveFile,
} from "./fileoperations";
import { LockManager } from "./utils";
import { Sandbox, Terminal, FilesystemManager } from "e2b";
2024-05-05 12:55:34 -07:00
import {
2024-05-05 12:58:45 -07:00
MAX_BODY_SIZE,
2024-05-05 12:55:34 -07:00
createFileRL,
2024-05-11 18:03:42 -07:00
createFolderRL,
2024-05-05 12:55:34 -07:00
deleteFileRL,
renameFileRL,
saveFileRL,
2024-05-13 23:22:06 -07:00
} from "./ratelimit";
2024-04-18 16:40:08 -04:00
2024-05-13 23:22:06 -07:00
dotenv.config();
2024-04-18 16:40:08 -04:00
2024-05-13 23:22:06 -07:00
const app: Express = express();
const port = process.env.PORT || 4000;
app.use(cors());
const httpServer = createServer(app);
2024-04-18 16:40:08 -04:00
const io = new Server(httpServer, {
cors: {
origin: "*",
},
2024-05-13 23:22:06 -07:00
});
2024-04-18 16:40:08 -04:00
let inactivityTimeout: NodeJS.Timeout | null = null;
let isOwnerConnected = false;
const containers: Record<string, Sandbox> = {};
const connections: Record<string, number> = {};
const terminals: Record<string, Terminal> = {};
2024-04-28 20:06:47 -04:00
const dirName = "/home/user";
const moveFile = async (
filesystem: FilesystemManager,
filePath: string,
newFilePath: string
) => {
const fileContents = await filesystem.readBytes(filePath);
await filesystem.writeBytes(newFilePath, fileContents);
await filesystem.remove(filePath);
};
2024-04-29 00:50:25 -04:00
2024-04-18 16:40:08 -04:00
io.use(async (socket, next) => {
2024-05-25 20:13:31 -07:00
const handshakeSchema = z.object({
userId: z.string(),
sandboxId: z.string(),
EIO: z.string(),
transport: z.string(),
});
2024-05-13 23:22:06 -07:00
const q = socket.handshake.query;
const parseQuery = handshakeSchema.safeParse(q);
2024-04-21 22:55:49 -04:00
if (!parseQuery.success) {
2024-05-13 23:22:06 -07:00
next(new Error("Invalid request."));
return;
2024-04-21 22:55:49 -04:00
}
2024-05-13 23:22:06 -07:00
const { sandboxId, userId } = parseQuery.data;
const dbUser = await fetch(
2024-05-26 18:37:36 -07:00
`${process.env.DATABASE_WORKER_URL}/api/user?id=${userId}`,
{
headers: {
Authorization: `${process.env.WORKERS_KEY}`,
},
}
2024-05-13 23:22:06 -07:00
);
const dbUserJSON = (await dbUser.json()) as User;
2024-04-21 22:55:49 -04:00
if (!dbUserJSON) {
2024-05-13 23:22:06 -07:00
next(new Error("DB error."));
return;
2024-04-18 16:40:08 -04:00
}
2024-05-13 23:22:06 -07:00
const sandbox = dbUserJSON.sandbox.find((s) => s.id === sandboxId);
2024-05-03 14:58:56 -07:00
const sharedSandboxes = dbUserJSON.usersToSandboxes.find(
(uts) => uts.sandboxId === sandboxId
2024-05-13 23:22:06 -07:00
);
2024-04-18 16:40:08 -04:00
2024-05-03 14:58:56 -07:00
if (!sandbox && !sharedSandboxes) {
2024-05-13 23:22:06 -07:00
next(new Error("Invalid credentials."));
return;
2024-04-21 22:55:49 -04:00
}
2024-04-26 02:10:37 -04:00
socket.data = {
userId,
sandboxId: sandboxId,
isOwner: sandbox !== undefined,
2024-05-13 23:22:06 -07:00
};
2024-04-18 16:40:08 -04:00
2024-05-13 23:22:06 -07:00
next();
});
2024-04-18 16:40:08 -04:00
const lockManager = new LockManager();
2024-04-18 16:40:08 -04:00
io.on("connection", async (socket) => {
try {
if (inactivityTimeout) clearTimeout(inactivityTimeout);
const data = socket.data as {
userId: string;
sandboxId: string;
isOwner: boolean;
};
2024-04-21 22:55:49 -04:00
if (data.isOwner) {
isOwnerConnected = true;
connections[data.sandboxId] = (connections[data.sandboxId] ?? 0) + 1;
} else {
if (!isOwnerConnected) {
socket.emit("disableAccess", "The sandbox owner is not connected.");
return;
}
}
await lockManager.acquireLock(data.sandboxId, async () => {
try {
if (!containers[data.sandboxId]) {
containers[data.sandboxId] = await Sandbox.create();
console.log("Created container ", data.sandboxId);
io.emit(
"previewURL",
"https://" + containers[data.sandboxId].getHostname(5173)
);
}
} catch (e: any) {
console.error(`Error creating container ${data.sandboxId}:`, e);
io.emit("error", `Error: container creation. ${e.message ?? e}`);
}
2024-05-13 23:22:06 -07:00
});
2024-04-27 19:12:25 -04:00
// Change the owner of the project directory to user
const fixPermissions = async () => {
await containers[data.sandboxId].process.startAndWait(
`sudo chown -R user "${path.join(dirName, "projects", data.sandboxId)}"`
);
};
2024-04-27 00:20:17 -04:00
const sandboxFiles = await getSandboxFiles(data.sandboxId);
sandboxFiles.fileData.forEach(async (file) => {
const filePath = path.join(dirName, file.id);
await containers[data.sandboxId].filesystem.makeDir(
path.dirname(filePath)
);
await containers[data.sandboxId].filesystem.write(filePath, file.data);
});
fixPermissions();
2024-04-27 19:12:25 -04:00
socket.emit("loaded", sandboxFiles.files);
2024-05-11 17:23:45 -07:00
socket.on("getFile", (fileId: string, callback) => {
console.log(fileId);
try {
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
if (!file) return;
2024-04-27 19:12:25 -04:00
callback(file.data);
} catch (e: any) {
console.error("Error getting file:", e);
io.emit("error", `Error: get file. ${e.message ?? e}`);
2024-05-05 12:58:45 -07:00
}
});
2024-05-05 12:58:45 -07:00
socket.on("getFolder", async (folderId: string, callback) => {
try {
const files = await getFolder(folderId);
callback(files);
} catch (e: any) {
console.error("Error getting folder:", e);
io.emit("error", `Error: get folder. ${e.message ?? e}`);
}
});
2024-05-05 12:55:34 -07:00
// todo: send diffs + debounce for efficiency
socket.on("saveFile", async (fileId: string, body: string) => {
try {
if (Buffer.byteLength(body, "utf-8") > MAX_BODY_SIZE) {
socket.emit(
"error",
"Error: file size too large. Please reduce the file size."
);
return;
}
try {
await saveFileRL.consume(data.userId, 1);
await saveFile(fileId, body);
} catch (e) {
io.emit("error", "Rate limited: file saving. Please slow down.");
return;
}
2024-04-27 19:12:25 -04:00
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
if (!file) return;
file.data = body;
2024-05-10 00:12:41 -07:00
await containers[data.sandboxId].filesystem.write(
path.join(dirName, file.id),
body
);
fixPermissions();
} catch (e: any) {
console.error("Error saving file:", e);
io.emit("error", `Error: file saving. ${e.message ?? e}`);
}
});
2024-05-10 00:12:41 -07:00
socket.on(
"moveFile",
async (fileId: string, folderId: string, callback) => {
try {
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
if (!file) return;
const parts = fileId.split("/");
const newFileId = folderId + "/" + parts.pop();
await moveFile(
containers[data.sandboxId].filesystem,
path.join(dirName, fileId),
path.join(dirName, newFileId)
);
fixPermissions();
file.id = newFileId;
await renameFile(fileId, newFileId, file.data);
const newFiles = await getSandboxFiles(data.sandboxId);
callback(newFiles.files);
} catch (e: any) {
console.error("Error moving file:", e);
io.emit("error", `Error: file moving. ${e.message ?? e}`);
}
2024-05-10 00:12:41 -07:00
}
2024-05-13 23:22:06 -07:00
);
2024-05-10 00:12:41 -07:00
socket.on("createFile", async (name: string, callback) => {
try {
const size: number = await getProjectSize(data.sandboxId);
// limit is 200mb
if (size > 200 * 1024 * 1024) {
io.emit(
"error",
"Rate limited: project size exceeded. Please delete some files."
);
callback({ success: false });
return;
}
2024-05-10 00:12:41 -07:00
try {
await createFileRL.consume(data.userId, 1);
} catch (e) {
io.emit("error", "Rate limited: file creation. Please slow down.");
return;
}
2024-05-10 00:12:41 -07:00
const id = `projects/${data.sandboxId}/${name}`;
2024-05-10 00:12:41 -07:00
await containers[data.sandboxId].filesystem.write(
path.join(dirName, id),
""
2024-05-13 23:22:06 -07:00
);
fixPermissions();
2024-04-29 00:50:25 -04:00
sandboxFiles.files.push({
id,
name,
type: "file",
});
2024-04-29 00:50:25 -04:00
sandboxFiles.fileData.push({
id,
data: "",
});
2024-05-05 12:55:34 -07:00
await createFile(id);
2024-04-29 00:50:25 -04:00
callback({ success: true });
} catch (e: any) {
console.error("Error creating file:", e);
io.emit("error", `Error: file creation. ${e.message ?? e}`);
}
});
2024-05-09 22:32:21 -07:00
socket.on("createFolder", async (name: string, callback) => {
try {
try {
await createFolderRL.consume(data.userId, 1);
} catch (e) {
io.emit("error", "Rate limited: folder creation. Please slow down.");
return;
}
2024-04-29 00:50:25 -04:00
const id = `projects/${data.sandboxId}/${name}`;
2024-05-11 18:03:42 -07:00
await containers[data.sandboxId].filesystem.makeDir(
path.join(dirName, id)
);
2024-05-11 18:03:42 -07:00
callback();
} catch (e: any) {
console.error("Error creating folder:", e);
io.emit("error", `Error: folder creation. ${e.message ?? e}`);
}
});
2024-05-11 18:03:42 -07:00
socket.on("renameFile", async (fileId: string, newName: string) => {
try {
try {
await renameFileRL.consume(data.userId, 1);
} catch (e) {
io.emit("error", "Rate limited: file renaming. Please slow down.");
return;
}
2024-05-11 18:03:42 -07:00
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
if (!file) return;
file.id = newName;
2024-05-05 12:55:34 -07:00
const parts = fileId.split("/");
const newFileId =
parts.slice(0, parts.length - 1).join("/") + "/" + newName;
2024-05-05 12:55:34 -07:00
await moveFile(
containers[data.sandboxId].filesystem,
path.join(dirName, fileId),
path.join(dirName, newFileId)
);
fixPermissions();
await renameFile(fileId, newFileId, file.data);
} catch (e: any) {
console.error("Error renaming folder:", e);
io.emit("error", `Error: folder renaming. ${e.message ?? e}`);
}
});
2024-05-05 12:55:34 -07:00
socket.on("deleteFile", async (fileId: string, callback) => {
try {
try {
await deleteFileRL.consume(data.userId, 1);
} catch (e) {
io.emit("error", "Rate limited: file deletion. Please slow down.");
2024-05-05 12:55:34 -07:00
}
2024-04-28 20:06:47 -04:00
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
if (!file) return;
2024-04-30 01:56:43 -04:00
await containers[data.sandboxId].filesystem.remove(
path.join(dirName, fileId)
);
sandboxFiles.fileData = sandboxFiles.fileData.filter(
(f) => f.id !== fileId
);
2024-04-30 01:56:43 -04:00
await deleteFile(fileId);
2024-05-11 17:23:45 -07:00
const newFiles = await getSandboxFiles(data.sandboxId);
callback(newFiles.files);
} catch (e: any) {
console.error("Error deleting file:", e);
io.emit("error", `Error: file deletion. ${e.message ?? e}`);
}
});
2024-05-11 17:23:45 -07:00
// todo
// socket.on("renameFolder", async (folderId: string, newName: string) => {
// });
2024-05-11 17:23:45 -07:00
socket.on("deleteFolder", async (folderId: string, callback) => {
try {
const files = await getFolder(folderId);
2024-05-11 17:23:45 -07:00
await Promise.all(
files.map(async (file) => {
await containers[data.sandboxId].filesystem.remove(
path.join(dirName, file)
);
2024-05-11 17:23:45 -07:00
sandboxFiles.fileData = sandboxFiles.fileData.filter(
(f) => f.id !== file
);
2024-05-11 17:23:45 -07:00
await deleteFile(file);
})
);
2024-05-11 17:23:45 -07:00
const newFiles = await getSandboxFiles(data.sandboxId);
2024-05-05 12:55:34 -07:00
callback(newFiles.files);
} catch (e: any) {
console.error("Error deleting folder:", e);
io.emit("error", `Error: folder deletion. ${e.message ?? e}`);
}
2024-05-13 23:22:06 -07:00
});
2024-04-29 02:19:27 -04:00
socket.on("createTerminal", async (id: string, callback) => {
try {
if (terminals[id] || Object.keys(terminals).length >= 4) {
return;
}
2024-04-29 02:19:27 -04:00
await lockManager.acquireLock(data.sandboxId, async () => {
try {
terminals[id] = await containers[data.sandboxId].terminal.start({
onData: (data: string) => {
io.emit("terminalResponse", { id, data });
},
size: { cols: 80, rows: 20 },
onExit: () => console.log("Terminal exited", id),
});
await terminals[id].sendData(
`cd "${path.join(dirName, "projects", data.sandboxId)}"\r`
);
await terminals[id].sendData("export PS1='user> '\rclear\r");
console.log("Created terminal", id);
} catch (e: any) {
console.error(`Error creating terminal ${id}:`, e);
io.emit("error", `Error: terminal creation. ${e.message ?? e}`);
}
});
2024-04-29 02:19:27 -04:00
callback();
} catch (e: any) {
console.error(`Error creating terminal ${id}:`, e);
io.emit("error", `Error: terminal creation. ${e.message ?? e}`);
}
});
2024-04-30 22:48:36 -04:00
socket.on(
"resizeTerminal",
(dimensions: { cols: number; rows: number }) => {
try {
Object.values(terminals).forEach((t) => {
t.resize(dimensions);
});
} catch (e: any) {
console.error("Error resizing terminal:", e);
io.emit("error", `Error: terminal resizing. ${e.message ?? e}`);
}
}
);
2024-05-06 23:34:45 -07:00
socket.on("terminalData", (id: string, data: string) => {
try {
if (!terminals[id]) {
return;
}
2024-04-28 20:06:47 -04:00
terminals[id].sendData(data);
} catch (e: any) {
console.error("Error writing to terminal:", e);
io.emit("error", `Error: writing to terminal. ${e.message ?? e}`);
}
2024-05-13 23:22:06 -07:00
});
2024-04-28 20:06:47 -04:00
socket.on("closeTerminal", async (id: string, callback) => {
try {
if (!terminals[id]) {
return;
}
2024-05-06 23:34:45 -07:00
await terminals[id].kill();
delete terminals[id];
2024-05-06 23:34:45 -07:00
callback();
} catch (e: any) {
console.error("Error closing terminal:", e);
io.emit("error", `Error: closing terminal. ${e.message ?? e}`);
}
});
2024-05-06 23:34:45 -07:00
socket.on(
"generateCode",
async (
fileName: string,
code: string,
line: number,
instructions: string,
callback
) => {
try {
const fetchPromise = fetch(
`${process.env.DATABASE_WORKER_URL}/api/sandbox/generate`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `${process.env.WORKERS_KEY}`,
},
body: JSON.stringify({
userId: data.userId,
}),
}
);
// Generate code from cloudflare workers AI
const generateCodePromise = fetch(
`${process.env.AI_WORKER_URL}/api?fileName=${fileName}&code=${code}&line=${line}&instructions=${instructions}`,
{
headers: {
"Content-Type": "application/json",
Authorization: `${process.env.CF_AI_KEY}`,
},
}
);
const [fetchResponse, generateCodeResponse] = await Promise.all([
fetchPromise,
generateCodePromise,
]);
const json = await generateCodeResponse.json();
callback({ response: json.response, success: true });
} catch (e: any) {
console.error("Error generating code:", e);
io.emit("error", `Error: code generation. ${e.message ?? e}`);
2024-05-13 23:22:06 -07:00
}
}
);
2024-05-13 23:22:06 -07:00
socket.on("disconnect", async () => {
try {
if (data.isOwner) {
connections[data.sandboxId]--;
2024-05-13 23:22:06 -07:00
}
2024-05-03 00:52:01 -07:00
if (data.isOwner && connections[data.sandboxId] <= 0) {
await Promise.all(
Object.entries(terminals).map(async ([key, terminal]) => {
await terminal.kill();
delete terminals[key];
})
);
await lockManager.acquireLock(data.sandboxId, async () => {
try {
if (containers[data.sandboxId]) {
await containers[data.sandboxId].close();
delete containers[data.sandboxId];
console.log("Closed container", data.sandboxId);
}
} catch (error) {
console.error("Error closing container ", data.sandboxId, error);
}
});
socket.broadcast.emit(
"disableAccess",
"The sandbox owner has disconnected."
);
}
// const sockets = await io.fetchSockets();
// if (inactivityTimeout) {
// clearTimeout(inactivityTimeout);
// }
// if (sockets.length === 0) {
// console.log("STARTING TIMER");
// inactivityTimeout = setTimeout(() => {
// io.fetchSockets().then(async (sockets) => {
// if (sockets.length === 0) {
// console.log("Server stopped", res);
// }
// });
// }, 20000);
// } else {
// console.log("number of sockets", sockets.length);
// }
} catch (e: any) {
console.log("Error disconnecting:", e);
io.emit("error", `Error: disconnecting. ${e.message ?? e}`);
}
});
} catch (e: any) {
console.error("Error connecting:", e);
io.emit("error", `Error: connection. ${e.message ?? e}`);
}
2024-05-13 23:22:06 -07:00
});
2024-04-18 16:40:08 -04:00
httpServer.listen(port, () => {
2024-05-26 21:41:20 -07:00
console.log(`Server running on port ${port}`);
2024-05-13 23:22:06 -07:00
});