482 lines
12 KiB
TypeScript
Raw Normal View History

2024-05-13 23:22:06 -07:00
import fs from "fs";
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,
2024-05-13 23:22:06 -07:00
} from "./utils";
import { IDisposable, IPty, spawn } from "node-pty";
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;
2024-04-29 21:36:33 -04:00
const terminals: {
2024-05-13 23:22:06 -07:00
[id: string]: { terminal: IPty; onData: IDisposable; onExit: IDisposable };
} = {};
2024-04-28 20:06:47 -04:00
2024-05-13 23:22:06 -07:00
const dirName = path.join(__dirname, "..");
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
console.log("Middleware");
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-25 20:13:31 -07:00
console.log("Invalid request.");
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-25 20:13:31 -07:00
console.log("DB error.");
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-25 20:13:31 -07:00
console.log("Invalid credentials.");
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
io.on("connection", async (socket) => {
if (inactivityTimeout) clearTimeout(inactivityTimeout);
2024-04-21 22:55:49 -04:00
const data = socket.data as {
2024-05-13 23:22:06 -07:00
userId: string;
sandboxId: string;
isOwner: boolean;
};
2024-04-21 22:55:49 -04:00
if (data.isOwner) {
2024-05-13 23:22:06 -07:00
isOwnerConnected = true;
} else {
if (!isOwnerConnected) {
2024-05-13 23:22:06 -07:00
socket.emit("disableAccess", "The sandbox owner is not connected.");
return;
}
}
2024-05-24 18:18:00 -07:00
// console.log("describing service:");
// const describeService = await testDescribe();
// console.log(describeService);
2024-05-17 22:23:44 -07:00
2024-05-13 23:22:06 -07:00
const sandboxFiles = await getSandboxFiles(data.sandboxId);
2024-04-29 00:50:25 -04:00
sandboxFiles.fileData.forEach((file) => {
2024-05-13 23:22:06 -07:00
const filePath = path.join(dirName, file.id);
fs.mkdirSync(path.dirname(filePath), { recursive: true });
2024-04-29 00:50:25 -04:00
fs.writeFile(filePath, file.data, function (err) {
2024-05-13 23:22:06 -07:00
if (err) throw err;
});
});
2024-04-18 16:40:08 -04:00
2024-05-13 23:22:06 -07:00
socket.emit("loaded", sandboxFiles.files);
2024-04-27 19:12:25 -04:00
2024-04-27 00:20:17 -04:00
socket.on("getFile", (fileId: string, callback) => {
2024-05-13 23:22:06 -07:00
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
if (!file) return;
2024-04-27 00:20:17 -04:00
2024-05-13 23:22:06 -07:00
callback(file.data);
});
2024-04-27 19:12:25 -04:00
2024-05-11 17:23:45 -07:00
socket.on("getFolder", async (folderId: string, callback) => {
2024-05-13 23:22:06 -07:00
const files = await getFolder(folderId);
callback(files);
});
2024-05-11 17:23:45 -07:00
2024-04-27 19:12:25 -04:00
// todo: send diffs + debounce for efficiency
socket.on("saveFile", async (fileId: string, body: string) => {
2024-05-25 20:13:31 -07:00
console.log("save");
2024-05-05 12:55:34 -07:00
try {
2024-05-13 23:22:06 -07:00
await saveFileRL.consume(data.userId, 1);
2024-04-27 19:12:25 -04:00
2024-05-05 12:58:45 -07:00
if (Buffer.byteLength(body, "utf-8") > MAX_BODY_SIZE) {
socket.emit(
"rateLimit",
"Rate limited: file size too large. Please reduce the file size."
2024-05-13 23:22:06 -07:00
);
return;
2024-05-05 12:58:45 -07:00
}
2024-05-13 23:22:06 -07:00
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
if (!file) return;
file.data = body;
2024-05-05 12:55:34 -07:00
fs.writeFile(path.join(dirName, file.id), body, function (err) {
2024-05-13 23:22:06 -07:00
if (err) throw err;
});
await saveFile(fileId, body);
2024-05-05 12:55:34 -07:00
} catch (e) {
2024-05-13 23:22:06 -07:00
io.emit("rateLimit", "Rate limited: file saving. Please slow down.");
2024-05-05 12:55:34 -07:00
}
2024-05-13 23:22:06 -07:00
});
2024-04-27 19:12:25 -04:00
2024-05-10 00:12:41 -07:00
socket.on("moveFile", async (fileId: string, folderId: string, callback) => {
2024-05-13 23:22:06 -07:00
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
if (!file) return;
2024-05-10 00:12:41 -07:00
2024-05-13 23:22:06 -07:00
const parts = fileId.split("/");
const newFileId = folderId + "/" + parts.pop();
2024-05-10 00:12:41 -07:00
fs.rename(
path.join(dirName, fileId),
path.join(dirName, newFileId),
function (err) {
2024-05-13 23:22:06 -07:00
if (err) throw err;
2024-05-10 00:12:41 -07:00
}
2024-05-13 23:22:06 -07:00
);
2024-05-10 00:12:41 -07:00
2024-05-13 23:22:06 -07:00
file.id = newFileId;
2024-05-10 00:12:41 -07:00
2024-05-13 23:22:06 -07:00
await renameFile(fileId, newFileId, file.data);
const newFiles = await getSandboxFiles(data.sandboxId);
2024-05-10 00:12:41 -07:00
2024-05-13 23:22:06 -07:00
callback(newFiles.files);
});
2024-05-10 00:12:41 -07:00
2024-05-09 22:32:21 -07:00
socket.on("createFile", async (name: string, callback) => {
2024-05-05 12:55:34 -07:00
try {
2024-05-13 23:22:06 -07:00
const size: number = await getProjectSize(data.sandboxId);
2024-05-09 22:32:21 -07:00
// limit is 200mb
if (size > 200 * 1024 * 1024) {
2024-05-13 23:22:06 -07:00
io.emit(
"rateLimit",
"Rate limited: project size exceeded. Please delete some files."
);
callback({ success: false });
2024-05-09 22:32:21 -07:00
}
2024-05-13 23:22:06 -07:00
await createFileRL.consume(data.userId, 1);
2024-04-29 00:50:25 -04:00
2024-05-13 23:22:06 -07:00
const id = `projects/${data.sandboxId}/${name}`;
2024-04-29 00:50:25 -04:00
2024-05-05 12:55:34 -07:00
fs.writeFile(path.join(dirName, id), "", function (err) {
2024-05-13 23:22:06 -07:00
if (err) throw err;
});
2024-04-29 00:50:25 -04:00
2024-05-05 12:55:34 -07:00
sandboxFiles.files.push({
id,
name,
type: "file",
2024-05-13 23:22:06 -07:00
});
2024-05-05 12:55:34 -07:00
sandboxFiles.fileData.push({
id,
data: "",
2024-05-13 23:22:06 -07:00
});
2024-04-29 00:50:25 -04:00
2024-05-13 23:22:06 -07:00
await createFile(id);
2024-05-09 22:32:21 -07:00
2024-05-13 23:22:06 -07:00
callback({ success: true });
2024-05-05 12:55:34 -07:00
} catch (e) {
2024-05-13 23:22:06 -07:00
io.emit("rateLimit", "Rate limited: file creation. Please slow down.");
2024-05-05 12:55:34 -07:00
}
2024-05-13 23:22:06 -07:00
});
2024-04-29 00:50:25 -04:00
2024-05-11 18:03:42 -07:00
socket.on("createFolder", async (name: string, callback) => {
try {
2024-05-13 23:22:06 -07:00
await createFolderRL.consume(data.userId, 1);
2024-05-11 18:03:42 -07:00
2024-05-13 23:22:06 -07:00
const id = `projects/${data.sandboxId}/${name}`;
2024-05-11 18:03:42 -07:00
fs.mkdir(path.join(dirName, id), { recursive: true }, function (err) {
2024-05-13 23:22:06 -07:00
if (err) throw err;
});
2024-05-11 18:03:42 -07:00
2024-05-13 23:22:06 -07:00
callback();
2024-05-11 18:03:42 -07:00
} catch (e) {
2024-05-13 23:22:06 -07:00
io.emit("rateLimit", "Rate limited: folder creation. Please slow down.");
2024-05-11 18:03:42 -07:00
}
2024-05-13 23:22:06 -07:00
});
2024-05-11 18:03:42 -07:00
2024-04-27 14:23:09 -04:00
socket.on("renameFile", async (fileId: string, newName: string) => {
2024-05-05 12:55:34 -07:00
try {
2024-05-13 23:22:06 -07:00
await renameFileRL.consume(data.userId, 1);
2024-05-05 12:55:34 -07:00
2024-05-13 23:22:06 -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
2024-05-13 23:22:06 -07:00
const parts = fileId.split("/");
2024-05-05 12:55:34 -07:00
const newFileId =
2024-05-13 23:22:06 -07:00
parts.slice(0, parts.length - 1).join("/") + "/" + newName;
2024-05-05 12:55:34 -07:00
fs.rename(
path.join(dirName, fileId),
path.join(dirName, newFileId),
function (err) {
2024-05-13 23:22:06 -07:00
if (err) throw err;
2024-05-05 12:55:34 -07:00
}
2024-05-13 23:22:06 -07:00
);
await renameFile(fileId, newFileId, file.data);
2024-05-05 12:55:34 -07:00
} catch (e) {
2024-05-13 23:22:06 -07:00
io.emit("rateLimit", "Rate limited: file renaming. Please slow down.");
return;
2024-05-05 12:55:34 -07:00
}
2024-05-13 23:22:06 -07:00
});
2024-04-28 20:06:47 -04:00
2024-04-30 01:56:43 -04:00
socket.on("deleteFile", async (fileId: string, callback) => {
2024-05-05 12:55:34 -07:00
try {
2024-05-13 23:22:06 -07:00
await deleteFileRL.consume(data.userId, 1);
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
if (!file) return;
2024-04-30 01:56:43 -04:00
2024-05-05 12:55:34 -07:00
fs.unlink(path.join(dirName, fileId), function (err) {
2024-05-13 23:22:06 -07:00
if (err) throw err;
});
2024-05-05 12:55:34 -07:00
sandboxFiles.fileData = sandboxFiles.fileData.filter(
(f) => f.id !== fileId
2024-05-13 23:22:06 -07:00
);
2024-04-30 01:56:43 -04:00
2024-05-13 23:22:06 -07:00
await deleteFile(fileId);
2024-04-30 01:56:43 -04:00
2024-05-13 23:22:06 -07:00
const newFiles = await getSandboxFiles(data.sandboxId);
callback(newFiles.files);
2024-05-05 12:55:34 -07:00
} catch (e) {
2024-05-13 23:22:06 -07:00
io.emit("rateLimit", "Rate limited: file deletion. Please slow down.");
2024-05-05 12:55:34 -07:00
}
2024-05-13 23:22:06 -07:00
});
2024-04-30 01:56:43 -04:00
2024-05-17 22:23:44 -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) => {
2024-05-13 23:22:06 -07:00
const files = await getFolder(folderId);
2024-05-11 17:23:45 -07:00
2024-05-13 23:22:06 -07:00
await Promise.all(
files.map(async (file) => {
fs.unlink(path.join(dirName, file), function (err) {
if (err) throw err;
});
2024-05-11 17:23:45 -07:00
2024-05-13 23:22:06 -07:00
sandboxFiles.fileData = sandboxFiles.fileData.filter(
(f) => f.id !== file
);
2024-05-11 17:23:45 -07:00
2024-05-13 23:22:06 -07:00
await deleteFile(file);
})
);
2024-05-11 17:23:45 -07:00
2024-05-13 23:22:06 -07:00
const newFiles = await getSandboxFiles(data.sandboxId);
2024-05-11 17:23:45 -07:00
2024-05-13 23:22:06 -07:00
callback(newFiles.files);
});
2024-05-11 17:23:45 -07:00
2024-05-06 23:34:45 -07:00
socket.on("createTerminal", (id: string, callback) => {
2024-05-13 23:22:06 -07:00
console.log("creating terminal", id);
if (terminals[id] || Object.keys(terminals).length >= 4) {
2024-05-13 23:22:06 -07:00
return;
2024-05-05 12:55:34 -07:00
}
2024-04-29 02:19:27 -04:00
const pty = spawn(os.platform() === "win32" ? "cmd.exe" : "bash", [], {
name: "xterm",
cols: 100,
cwd: path.join(dirName, "projects", data.sandboxId),
2024-05-13 23:22:06 -07:00
});
2024-04-29 02:19:27 -04:00
2024-04-29 21:36:33 -04:00
const onData = pty.onData((data) => {
2024-05-07 23:52:14 -07:00
io.emit("terminalResponse", {
2024-05-06 23:34:45 -07:00
id,
2024-04-29 02:19:27 -04:00
data,
2024-05-13 23:22:06 -07:00
});
});
2024-04-29 02:19:27 -04:00
2024-05-13 23:22:06 -07:00
const onExit = pty.onExit((code) => console.log("exit :(", code));
2024-04-29 02:19:27 -04:00
2024-05-24 01:28:50 -07:00
pty.write("export PS1='\\u > '\r");
2024-05-13 23:22:06 -07:00
pty.write("clear\r");
2024-04-30 22:48:36 -04:00
2024-04-29 21:36:33 -04:00
terminals[id] = {
terminal: pty,
onData,
onExit,
2024-05-13 23:22:06 -07:00
};
2024-05-06 23:34:45 -07:00
2024-05-13 23:22:06 -07:00
callback();
});
2024-04-28 20:06:47 -04:00
2024-05-09 22:16:56 -07:00
socket.on("resizeTerminal", (dimensions: { cols: number; rows: number }) => {
2024-05-13 23:22:06 -07:00
console.log("resizeTerminal", dimensions);
2024-05-09 22:16:56 -07:00
Object.values(terminals).forEach((t) => {
2024-05-13 23:22:06 -07:00
t.terminal.resize(dimensions.cols, dimensions.rows);
});
});
2024-05-09 22:16:56 -07:00
2024-04-29 02:19:27 -04:00
socket.on("terminalData", (id: string, data: string) => {
2024-04-28 20:06:47 -04:00
if (!terminals[id]) {
2024-05-13 23:22:06 -07:00
console.log("terminal not found", id);
return;
2024-04-28 20:06:47 -04:00
}
2024-04-29 02:19:27 -04:00
try {
2024-05-13 23:22:06 -07:00
terminals[id].terminal.write(data);
2024-04-29 02:19:27 -04:00
} catch (e) {
2024-05-13 23:22:06 -07:00
console.log("Error writing to terminal", e);
2024-04-29 02:19:27 -04:00
}
2024-05-13 23:22:06 -07:00
});
2024-04-28 20:06:47 -04:00
2024-05-06 23:34:45 -07:00
socket.on("closeTerminal", (id: string, callback) => {
if (!terminals[id]) {
2024-05-13 23:22:06 -07:00
return;
2024-05-06 23:34:45 -07:00
}
2024-05-13 23:22:06 -07:00
terminals[id].onData.dispose();
terminals[id].onExit.dispose();
delete terminals[id];
2024-05-06 23:34:45 -07:00
2024-05-13 23:22:06 -07:00
callback();
});
2024-05-06 23:34:45 -07:00
2024-05-03 00:52:01 -07:00
socket.on(
"generateCode",
async (
fileName: string,
code: string,
line: number,
instructions: string,
callback
) => {
2024-05-11 17:23:45 -07:00
// Log code generation credit in DB
2024-05-13 23:22:06 -07:00
const fetchPromise = fetch(
2024-05-26 18:37:36 -07:00
`${process.env.DATABASE_WORKER_URL}/api/sandbox/generate`,
2024-05-13 23:22:06 -07:00
{
method: "POST",
headers: {
"Content-Type": "application/json",
2024-05-26 18:37:36 -07:00
Authorization: `${process.env.WORKERS_KEY}`,
2024-05-13 23:22:06 -07:00
},
body: JSON.stringify({
userId: data.userId,
}),
}
);
2024-05-11 17:23:45 -07:00
// Generate code from cloudflare workers AI
2024-05-13 23:22:06 -07:00
const generateCodePromise = fetch(
2024-05-26 18:37:36 -07:00
`${process.env.AI_WORKER_URL}/api?fileName=${fileName}&code=${code}&line=${line}&instructions=${instructions}`,
2024-05-13 23:22:06 -07:00
{
headers: {
"Content-Type": "application/json",
Authorization: `${process.env.CF_AI_KEY}`,
},
}
);
const [fetchResponse, generateCodeResponse] = await Promise.all([
fetchPromise,
generateCodePromise,
2024-05-13 23:22:06 -07:00
]);
2024-05-03 00:52:01 -07:00
2024-05-13 23:22:06 -07:00
const json = await generateCodeResponse.json();
2024-05-14 00:18:27 -07:00
console.log("Code generation response", json);
callback({ response: json.response, success: true });
2024-05-03 00:52:01 -07:00
}
2024-05-13 23:22:06 -07:00
);
2024-05-03 00:52:01 -07:00
socket.on("disconnect", async () => {
2024-05-13 23:22:06 -07:00
console.log("disconnected", data.userId, data.sandboxId);
if (data.isOwner) {
Object.entries(terminals).forEach((t) => {
2024-05-13 23:22:06 -07:00
const { terminal, onData, onExit } = t[1];
onData.dispose();
onExit.dispose();
delete terminals[t[0]];
});
2024-05-13 23:22:06 -07:00
socket.broadcast.emit(
"disableAccess",
"The sandbox owner has disconnected."
);
}
2024-05-26 18:04:43 -07:00
// 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);
// }
2024-05-13 23:22:06 -07:00
});
});
2024-04-18 16:40:08 -04:00
httpServer.listen(port, () => {
2024-05-25 20:13:31 -07:00
console.log(`Server 123, running on port ${port}`);
2024-05-13 23:22:06 -07:00
});