-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
225 lines (197 loc) · 8.59 KB
/
Copy pathserver.js
File metadata and controls
225 lines (197 loc) · 8.59 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
'use strict';
/**
* CodeQuorum server: static client + REST API + real-time collaboration.
*
* Security posture (see SECURITY.md):
* - helmet sets security headers incl. a tailored Content-Security-Policy
* - express-rate-limit throttles the API
* - all input is validated (zod) and all SQL is parameterized
* - authorization is enforced SERVER-SIDE on the socket layer: private rooms
* reject non-members, and "viewer" role edits are dropped, never trusted
*
* Realtime wire protocol:
* client → join { roomId, user, clientId }
* server → joined { role } 'owner' | 'editor' | 'viewer'
* server → access-denied { reason }
* server → init <binary Yjs state>
* server → presence [{ id, name, color, file }]
* client → y-update <binary> (ignored from viewers)
* server → y-update <binary>
* client → awareness <binary> ; server → awareness <binary>
* client → set-activity <fileName|null> ; client → rename <name>
* server → peer-left { clientId }
*/
const http = require('http');
const os = require('os');
const crypto = require('crypto');
const path = require('path');
const express = require('express');
const helmet = require('helmet');
const cookieParser = require('cookie-parser');
const rateLimit = require('express-rate-limit');
const { Server } = require('socket.io');
const rooms = require('./rooms');
const repo = require('./repo');
const apiRouter = require('./api');
const { attachUser, userIdFromCookieHeader } = require('./auth');
const PORT = process.env.PORT || 3000;
const PUBLIC_DIR = path.join(__dirname, '..', 'public');
const app = express();
const server = http.createServer(app);
const io = new Server(server, { maxHttpBufferSize: 1e7 });
app.disable('x-powered-by');
app.use(helmet({
contentSecurityPolicy: {
useDefaults: true,
directives: {
'default-src': ["'self'"],
// 'wasm-unsafe-eval' lets the self-hosted Pyodide (Python) runtime compile
// its WebAssembly. It permits WASM only — NOT arbitrary JS eval.
'script-src': ["'self'", "'wasm-unsafe-eval'"],
'style-src': ["'self'", "'unsafe-inline'"], // CodeMirror injects styles
'img-src': ["'self'", 'data:'],
'connect-src': ["'self'", 'ws:', 'wss:'],
'worker-src': ["'self'", 'blob:'], // JS sandbox (blob) + Python worker (self)
'frame-src': ["'self'", 'blob:'], // sandboxed HTML preview
'object-src': ["'none'"],
'base-uri': ["'self'"],
'form-action': ["'self'"],
},
},
// The HTML preview is intentionally framed; allow same-origin framing only.
crossOriginEmbedderPolicy: false,
}));
app.use(express.json({ limit: '1mb' }));
app.use(cookieParser());
app.use(attachUser);
app.use('/api', rateLimit({ windowMs: 60 * 1000, max: 300, standardHeaders: true, legacyHeaders: false }), apiRouter);
// Sandboxed live preview. Client posts assembled HTML; we serve it from a
// short-lived URL with its OWN locked-down CSP (inline scripts allowed so the
// user's page runs, but `default-src 'none'` blocks all network access). Served
// from a real URL so it does NOT inherit the app's strict CSP.
const previews = new Map(); // token -> { html, ts }
const PREVIEW_TTL = 60 * 1000;
function sweepPreviews() {
const now = Date.now();
for (const [t, v] of previews) if (now - v.ts > PREVIEW_TTL) previews.delete(t);
}
app.post('/api/preview', (req, res) => {
sweepPreviews();
if (previews.size > 500) return res.status(429).json({ error: 'Too many previews in flight.' });
const html = String((req.body && req.body.html) || '');
const token = crypto.randomBytes(12).toString('hex');
previews.set(token, { html, ts: Date.now() });
res.json({ token });
});
app.get('/preview/:token', (req, res) => {
const entry = previews.get(req.params.token);
if (!entry) return res.status(404).type('html').send('<p style="font:14px sans-serif">Preview expired — run it again.</p>');
res.setHeader('Content-Security-Policy',
"default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval' blob:; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; media-src data: blob:; frame-ancestors 'self'");
res.type('html').send(entry.html);
});
// Self-hosted Pyodide runtime (Python in notebooks) — served from our origin.
app.use('/pyodide', express.static(path.join(__dirname, '..', 'node_modules', 'pyodide'), {
immutable: true,
maxAge: '7d',
}));
app.use(express.static(PUBLIC_DIR));
app.get('/', (_req, res) => res.sendFile(path.join(PUBLIC_DIR, 'index.html')));
app.get('/room/:id', (_req, res) => res.sendFile(path.join(PUBLIC_DIR, 'room.html')));
app.get('/healthz', (_req, res) => res.json({ ok: true, rooms: rooms._rooms.size }));
async function emitPresence(roomId) {
const sockets = await io.in(roomId).fetchSockets();
io.in(roomId).emit('presence', sockets.map((s) => s.data.user).filter(Boolean));
}
io.use((socket, next) => {
socket.data.userId = userIdFromCookieHeader(socket.handshake.headers.cookie) || null;
next();
});
io.on('connection', (socket) => {
socket.on('join', async ({ roomId, user, clientId } = {}) => {
const id = rooms.sanitizeId(roomId);
if (!id) return socket.emit('access-denied', { reason: 'Invalid room id.' });
// Ensure a room record exists; a first visitor (anonymous or signed-in)
// creates a public room, becoming owner if signed in.
let room = repo.rooms.byId(id);
if (!room) {
room = repo.rooms.create({ roomId: id, name: id, ownerId: socket.data.userId, visibility: 'public' });
if (socket.data.userId) repo.members.add(id, socket.data.userId, 'editor');
}
const role = repo.effectiveRole(room, socket.data.userId);
if (!role) return socket.emit('access-denied', { reason: 'This room is private.' });
socket.data.roomId = id;
socket.data.role = role;
socket.data.canEdit = role !== 'viewer';
socket.data.clientId = clientId;
socket.data.user = {
id: socket.id,
clientId, // Yjs clientID, used for "follow" / "spotlight"
name: (user && String(user.name).slice(0, 40)) || 'Anonymous',
color: (user && user.color) || '#888888',
file: null,
};
socket.join(id);
rooms.join(id);
socket.emit('joined', { role });
socket.emit('init', Buffer.from(rooms.getStateAsUpdate(id)));
await emitPresence(id);
});
socket.on('y-update', (update) => {
const id = socket.data.roomId;
if (!id || !update || !socket.data.canEdit) return; // viewers cannot write
const bytes = new Uint8Array(update);
rooms.applyUpdate(id, bytes);
repo.rooms.touch(id);
socket.to(id).emit('y-update', Buffer.from(bytes));
});
socket.on('awareness', (update) => {
const id = socket.data.roomId;
if (!id || !update) return;
socket.to(id).emit('awareness', Buffer.from(new Uint8Array(update)));
});
socket.on('rename', async (name) => {
const id = socket.data.roomId;
if (!id || !socket.data.user) return;
socket.data.user.name = String(name).slice(0, 40) || 'Anonymous';
await emitPresence(id);
});
// Figma-style "spotlight": ask everyone in the room to follow this user.
socket.on('spotlight', () => {
const id = socket.data.roomId;
if (!id || socket.data.clientId == null) return;
socket.to(id).emit('spotlight', { clientId: socket.data.clientId, name: socket.data.user && socket.data.user.name });
});
socket.on('set-activity', async (fileName) => {
const id = socket.data.roomId;
if (!id || !socket.data.user) return;
socket.data.user.file = fileName ? String(fileName).slice(0, 120) : null;
await emitPresence(id);
});
socket.on('disconnect', async () => {
const id = socket.data.roomId;
if (!id) return;
rooms.leave(id);
if (socket.data.clientId != null) socket.to(id).emit('peer-left', { clientId: socket.data.clientId });
await emitPresence(id);
});
});
function lanAddresses() {
const out = [];
for (const ifaces of Object.values(os.networkInterfaces())) {
for (const i of ifaces || []) {
if (i.family === 'IPv4' && !i.internal) out.push(i.address);
}
}
return out;
}
if (require.main === module) {
server.listen(PORT, () => {
console.log(`\n CodeQuorum is running:\n`);
console.log(` • Local: http://localhost:${PORT}`);
for (const ip of lanAddresses()) console.log(` • Network: http://${ip}:${PORT} (share THIS with people on your Wi-Fi/LAN)`);
console.log(`\n Note: a "localhost" link only works on THIS machine. To collaborate`);
console.log(` with others, share the Network URL above, or deploy (see README).\n`);
});
}
module.exports = { app, server, io };