-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
523 lines (450 loc) · 17.1 KB
/
server.js
File metadata and controls
523 lines (450 loc) · 17.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
import express from 'express';
import http from 'http';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import { Server } from 'socket.io';
import { WebSocketServer } from 'ws';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const { setupWSConnection, setPersistence } = require('y-websocket/bin/utils');
const { LeveldbPersistence } = require('y-leveldb');
import * as Y from 'yjs';
import ACTIONS from './src/actions/Actions.js';
import helmet from 'helmet';
import compression from 'compression';
import { exec } from 'child_process';
import { promisify } from 'util';
import fs from 'fs';
import { writeFile, unlink } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
const execAsync = promisify(exec);
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const app = express();
const server = http.createServer(app);
// Accept comma-separated allowed origins via env; default to localhost:5173 for dev
const allowedOrigins = (process.env.CLIENT_ORIGIN || 'http://localhost:5173')
.split(',')
.map((o) => o.trim());
const io = new Server(server, {
cors: {
// Allow dynamic origin during development if CLIENT_ORIGIN is not provided
origin: (origin, callback) => {
// No origin (e.g., mobile apps, curl) -> allow
if (!origin) return callback(null, true);
// If explicit list provided, enforce it
if (process.env.CLIENT_ORIGIN) {
if (allowedOrigins.includes(origin)) return callback(null, true);
return callback(new Error('Not allowed by CORS'));
}
// No env set -> allow the requesting origin (useful for Vite dev and same-origin prod)
return callback(null, true);
},
methods: ['GET', 'POST'],
},
});
// Yjs WebSocket Server Setup
const wss = new WebSocketServer({ noServer: true });
// Configure LevelDB Persistence
const ldb = new LeveldbPersistence('./storage');
setPersistence({
bindState: async (docName, doc) => {
const persistedYdoc = await ldb.getYDoc(docName);
const persistedStateVector = Y.encodeStateVector(doc);
const diff = Y.encodeStateAsUpdate(persistedYdoc, persistedStateVector);
// Apply the persisted state to the current doc
if (diff.byteLength > 0) {
Y.applyUpdate(doc, diff);
}
// Store updates
doc.on('update', update => {
ldb.storeUpdate(docName, update);
});
},
writeState: async (docName, doc) => {
// efficient storage is already handled by ldb.storeUpdate in the listener
}
});
wss.on('connection', (ws, req) => {
setupWSConnection(ws, req);
});
// Handle upgrade requests
server.on('upgrade', (request, socket, head) => {
if (request.url.startsWith('/yjs')) {
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request);
});
}
});
// Security and performance middleware
app.use(helmet({
contentSecurityPolicy: false,
}));
app.use(compression());
// Healthcheck for uptime monitors and container orchestrators
app.get('/healthz', (req, res) => {
res.status(200).json({ status: 'ok' });
});
// Debug endpoint to check available runtimes
app.get('/api/runtimes', async (req, res) => {
try {
let fetchFn = globalThis.fetch;
if (!fetchFn) {
const mod = await import('node-fetch');
fetchFn = mod.default || mod;
}
const runtimes = await getAvailableRuntimes(fetchFn);
res.json(runtimes);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Lightweight CORS for API routes (matches socket origins)
app.use('/api', (req, res, next) => {
const reqOrigin = req.headers.origin;
let allow = false;
if (!process.env.CLIENT_ORIGIN) {
allow = true; // dev: allow any
} else if (reqOrigin && allowedOrigins.includes(reqOrigin)) {
allow = true;
}
if (allow) {
res.header('Access-Control-Allow-Origin', reqOrigin || '*');
res.header('Vary', 'Origin');
}
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Methods', 'POST, OPTIONS');
if (req.method === 'OPTIONS') {
return res.sendStatus(204);
}
next();
});
// Cache for available runtimes
let runtimesCache = null;
let runtimesCacheTime = 0;
const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes
// Function to get available runtimes from Piston
async function getAvailableRuntimes(fetchFn) {
const now = Date.now();
if (runtimesCache && (now - runtimesCacheTime) < CACHE_DURATION) {
return runtimesCache;
}
try {
const response = await fetchFn('https://emkc.org/api/v2/piston/runtimes');
if (!response.ok) {
throw new Error(`Failed to fetch runtimes: ${response.status}`);
}
const runtimes = await response.json();
runtimesCache = runtimes;
runtimesCacheTime = now;
return runtimes;
} catch (error) {
console.error('Failed to fetch runtimes:', error.message);
// Return default versions if fetch fails
return [
{ language: 'c', version: '10.2.0' },
{ language: 'cpp', version: '10.2.0' }
];
}
}
// Execute code (C/C++) via multiple execution services
app.use(express.json({ limit: '200kb' }));
app.post('/api/run', async (req, res) => {
try {
const { language, code } = req.body || {};
if (!language || !code) {
return res.status(400).json({ error: 'language and code are required' });
}
// Map our frontend mode names to language identifiers
let langId;
let fileName;
if (language === 'text/x-c++src') {
langId = 'cpp';
fileName = 'main.cpp';
} else if (language === 'c' || language === 'text/x-csrc') {
langId = 'c';
fileName = 'main.c';
} else if (language === 'text/x-java') {
langId = 'java';
fileName = 'Main.java';
} else {
return res.status(400).json({ error: 'Unsupported language' });
}
console.log(`Executing ${langId} code via execution service...`);
// Try multiple execution services in order of preference
const executionServices = [];
// Enable "Local" (Docker) execution on all platforms now
if (true) {
executionServices.push({
name: 'Local',
url: 'local',
transformRequest: async (lang, code, fetchFn) => ({ lang, code }),
transformResponse: async (data, fetchFn) => {
// Local execution using Docker Sandbox
const { lang, code } = data;
const tempDir = tmpdir();
const uniqueId = `exec_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
const hostFilePath = join(tempDir, `${uniqueId}_${fileName}`);
try {
// Write code to temporary file on host
await writeFile(hostFilePath, code);
let compileRunCmd;
if (lang === 'java') {
compileRunCmd = `javac /code/${fileName} && java -cp /code Main`;
} else {
const compiler = lang === 'cpp' ? 'g++' : 'gcc';
compileRunCmd = `${compiler} -o /code/output /code/${fileName} && /code/output`;
}
const containerName = `sandbox_${uniqueId}`;
const dockerCmd = `docker run --rm --name ${containerName} --network none --cpus 0.5 --memory 128m -v "${hostFilePath}:/code/${fileName}" code-sandbox sh -c "${compileRunCmd}"`;
// Execute
const { stdout, stderr } = await execAsync(dockerCmd);
// Cleanup
await unlink(hostFilePath).catch(() => { });
if (stderr && !stdout) {
return { stdout: '', stderr: stderr, exitCode: 1 };
}
return { stdout: stdout, stderr: stderr, exitCode: 0 };
} catch (e) {
// Cleanup host file
await unlink(hostFilePath).catch(() => { });
// Check for Docker daemon errors specifically
const errorMsg = (e.message || '') + (e.stderr || '');
const isDockerError = errorMsg.includes('docker') ||
errorMsg.includes('error during connect') ||
errorMsg.includes('cannot find the file specified') ||
errorMsg.includes('pipe') ||
errorMsg.includes('daemon');
if (isDockerError) {
// Re-throw so the main loop catches it and tries the next service
throw new Error(`Docker service unavailable: ${errorMsg}`);
}
return { stdout: '', stderr: errorMsg || 'Execution failed', exitCode: 1 };
}
},
});
}
// Add remote services
executionServices.push(
{
name: 'Piston',
url: 'https://emkc.org/api/v2/piston/execute',
transformRequest: async (lang, code, fetchFn) => {
const runtimes = await getAvailableRuntimes(fetchFn);
console.log('Available runtimes:', JSON.stringify(runtimes, null, 2));
// Find the runtime for the specific language
const langRuntime = runtimes.find(r => r.language === lang);
const version = langRuntime ? langRuntime.version : '10.2.0';
console.log(`Using version ${version} for language ${lang}`);
return {
language: lang,
version: version,
files: [{ name: fileName, content: code }],
stdin: '',
args: [],
compile_timeout: 10000,
run_timeout: 3000,
compile_memory_limit: -1,
run_memory_limit: -1
};
},
transformResponse: (data) => ({
stdout: data?.run?.stdout || '',
stderr: data?.run?.stderr || '',
exitCode: data?.run?.code || 0,
}),
},
{
name: 'Judge0',
url: 'https://judge0-ce.p.rapidapi.com/submissions',
transformRequest: async (lang, code, fetchFn) => ({
language_id: langId === 'cpp' ? 54 : 50, // C++: 54, C: 50
source_code: code,
}),
transformResponse: async (data, fetchFn) => {
// Judge0 requires a second request to get results
const token = data.token;
if (!token) throw new Error('No token received from Judge0');
// Wait a bit and then fetch results
await new Promise(resolve => setTimeout(resolve, 2000));
const resultResponse = await fetchFn(`https://judge0-ce.p.rapidapi.com/submissions/${token}`, {
headers: {
'X-RapidAPI-Key': process.env.RAPIDAPI_KEY || 'demo-key',
'X-RapidAPI-Host': 'judge0-ce.p.rapidapi.com'
}
});
if (!resultResponse.ok) {
throw new Error(`Judge0 result fetch failed: ${resultResponse.status}`);
}
const resultData = await resultResponse.json();
return {
stdout: resultData.stdout || '',
stderr: resultData.stderr || '',
exitCode: resultData.status?.id || 0,
};
},
}
);
// Use global fetch if present; else fallback to node-fetch dynamically
let fetchFn = globalThis.fetch;
if (!fetchFn) {
const mod = await import('node-fetch');
fetchFn = mod.default || mod;
}
let lastError = null;
for (const service of executionServices) {
try {
console.log(`Trying ${service.name} execution service...`);
const requestBody = await service.transformRequest(langId, code, fetchFn);
// Handle local execution
if (service.name === 'Local') {
try {
const result = await service.transformResponse(requestBody, fetchFn);
console.log(`${service.name} execution successful`);
return res.json(result);
} catch (localError) {
console.warn(`Local execution unavailable, falling back: ${localError.message}`);
lastError = localError;
continue; // Proceed to next service (Piston)
}
}
// Handle remote services
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(requestBody),
};
// Add special headers for Judge0
if (service.name === 'Judge0') {
requestOptions.headers['X-RapidAPI-Key'] = process.env.RAPIDAPI_KEY || 'demo-key';
requestOptions.headers['X-RapidAPI-Host'] = 'judge0-ce.p.rapidapi.com';
}
const response = await fetchFn(service.url, requestOptions);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`${service.name} service failed: ${response.status} - ${errorText}`);
}
const data = await response.json();
const result = await service.transformResponse(data, fetchFn);
console.log(`${service.name} execution successful`);
return res.json(result);
} catch (error) {
console.error(`${service.name} execution failed:`, error.message);
lastError = error;
continue; // Try next service
}
}
// If all services failed, return a helpful error message
console.error('All execution services failed');
return res.status(502).json({
error: 'All execution services are currently unavailable',
detail: lastError?.message || 'Unknown error',
suggestion: 'Please try again later or check your internet connection'
});
} catch (e) {
console.error('Run API error:', e);
res.status(500).json({
error: 'Server error',
detail: String(e?.message || e),
suggestion: 'Please check the server logs for more details'
});
}
});
// Serve Vite build output from dist
const DIST_DIR = path.join(__dirname, 'dist');
app.use(express.static(DIST_DIR));
app.use((req, res, next) => {
res.sendFile(path.join(DIST_DIR, 'index.html'));
});
const userSocketMap = {};
function getAllConnectedClients(roomId) {
// For every socket in a room, get its username
return Array.from(io.sockets.adapter.rooms.get(roomId) || []).map((socketId) => {
return {
socketId,
username: userSocketMap[socketId] || "Anonymous", // fallback to avoid undefined
};
});
}
io.on('connection', (socket) => {
console.log('socket connected', socket.id);
socket.on(ACTIONS.JOIN, ({ roomId, username }) => {
// Prevent empty username; fallback/debug
if (!username || username.trim() === "") {
console.log(`[WARN] Empty username received for socketId ${socket.id}`);
userSocketMap[socket.id] = "Anonymous";
} else {
userSocketMap[socket.id] = username;
}
socket.join(roomId);
const clients = getAllConnectedClients(roomId);
console.log('[JOINED EMIT]:', clients);
// Send joined event to everyone in the room (including joiner)
io.to(roomId).emit(ACTIONS.JOINED, {
clients,
username: userSocketMap[socket.id],
socketId: socket.id,
});
});
socket.on(ACTIONS.CODE_CHANGE, ({ roomId, code }) => {
if (!roomId || typeof code !== 'string') {
console.warn(`[WARN] Invalid CODE_CHANGE from ${socket.id}: roomId=${roomId}, code type=${typeof code}`);
return;
}
// Verify socket is in the room before broadcasting
if (socket.rooms.has(roomId)) {
socket.in(roomId).emit(ACTIONS.CODE_CHANGE, { code });
} else {
console.warn(`[WARN] Socket ${socket.id} tried to send CODE_CHANGE to room ${roomId} but is not in that room`);
}
});
socket.on(ACTIONS.SYNC_CODE, ({ socketId, code }) => {
if (!socketId || typeof code !== 'string') {
console.warn(`[WARN] Invalid SYNC_CODE from ${socket.id}: socketId=${socketId}, code type=${typeof code}`);
return;
}
// Security: Only allow syncing to sockets in the same rooms as the sender
const senderRooms = Array.from(socket.rooms);
const targetSocket = io.sockets.sockets.get(socketId);
if (!targetSocket) {
console.warn(`[WARN] SYNC_CODE target socket ${socketId} not found`);
return;
}
// Check if target socket is in at least one room with the sender
const targetRooms = Array.from(targetSocket.rooms);
const commonRooms = senderRooms.filter(room => targetRooms.includes(room) && room !== socket.id);
if (commonRooms.length > 0) {
io.to(socketId).emit(ACTIONS.CODE_CHANGE, { code });
} else {
console.warn(`[WARN] Socket ${socket.id} tried to SYNC_CODE to ${socketId} but they share no rooms`);
}
});
socket.on('disconnecting', () => {
const rooms = [...socket.rooms];
rooms.forEach((roomId) => {
socket.in(roomId).emit(ACTIONS.DISCONNECTED, {
socketId: socket.id,
username: userSocketMap[socket.id],
});
});
delete userSocketMap[socket.id];
});
});
app.get('/', (req, res) => {
const htmlContent = '<h1>Welcome to the code editor server</h1>';
res.setHeader('Content-Type', 'text/html');
res.send(htmlContent);
});
const PORT = process.env.SERVER_PORT || 5000;
server.listen(PORT, async () => {
console.log(`🚀 Professional Code Editor Backend running on port ${PORT}`);
// Diagnostic startup check for Docker
try {
await execAsync('docker info');
console.log('✅ Secure Code Sandbox: Docker is active and available.');
} catch (e) {
console.warn('⚠️ Secure Code Sandbox: Docker is not active. Falling back to remote execution services.');
}
});