-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
250 lines (207 loc) · 7 KB
/
server.js
File metadata and controls
250 lines (207 loc) · 7 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
'use strict';
const fs = require('node:fs');
const http = require('node:http');
const path = require('node:path');
const dgram = require('node:dgram');
const PORT = 8000;
const STUN_PORT = 3478;
const MIME_TYPES = {
default: 'application/octet-stream',
html: 'text/html; charset=UTF-8',
js: 'application/javascript; charset=UTF-8',
json: 'application/json',
css: 'text/css',
png: 'image/png',
jpg: 'image/jpg',
jpeg: 'image/jpeg',
gif: 'image/gif',
ico: 'image/x-icon',
svg: 'image/svg+xml',
};
const HEADERS = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
};
const HEADERS_HTML = {
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'X-XSS-Protection': '1; mode=block',
};
const STATIC_PATH = path.join(process.cwd(), 'Application', 'static');
const toBool = [() => true, () => false];
const rooms = new Map();
const getRoom = (roomId) => {
if (!rooms.has(roomId)) {
rooms.set(roomId, new Map());
}
return rooms.get(roomId);
};
const parseBody = async (req) => {
const chunks = [];
for await (const chunk of req) chunks.push(chunk);
const buffer = Buffer.concat(chunks);
if (buffer.length === 0) return {};
return JSON.parse(buffer.toString());
};
const sendJSON = (res, status, obj) => {
const headers = { ...HEADERS, 'Content-Type': 'application/json' };
res.writeHead(status, headers);
res.end(JSON.stringify(obj));
};
const joinRoom = async (req, res) => {
const body = await parseBody(req);
const roomId = body.roomId || 'default';
const clientId = body.clientId || '';
if (!clientId) {
sendJSON(res, 400, { error: 'clientId required' });
return;
}
const room = getRoom(roomId);
if (!room.has(clientId)) {
room.set(clientId, []);
}
sendJSON(res, 200, { ok: true });
};
const sendSignal = async (req, res) => {
const body = await parseBody(req);
const { roomId, from, to, data } = body;
if (!from || !to || !data) {
sendJSON(res, 400, { error: 'from, to, data required' });
return;
}
const room = getRoom(roomId);
if (!room.has(to)) {
room.set(to, []);
}
const inbox = room.get(to);
inbox.push({ from, data, ts: Date.now() });
sendJSON(res, 200, { ok: true });
};
const getSignal = (req, res, url) => {
const roomId = url.searchParams.get('roomId') || 'default';
const clientId = url.searchParams.get('clientId') || '';
if (!clientId) {
sendJSON(res, 400, { error: 'clientId required' });
return;
}
const room = getRoom(roomId);
const inbox = room.get(clientId) || [];
const messages = inbox.splice(0, inbox.length);
sendJSON(res, 200, { messages });
};
const getPeers = (req, res, url) => {
const roomId = url.searchParams.get('roomId') || 'default';
const clientId = url.searchParams.get('clientId') || '';
if (!clientId) {
sendJSON(res, 400, { error: 'clientId required' });
return;
}
const room = getRoom(roomId);
const peers = Array.from(room.keys()).filter((id) => id !== clientId);
sendJSON(res, 200, { peers });
};
const routes = new Map([
['/join', { post: joinRoom }],
['/signal', { post: sendSignal, get: getSignal }],
['/peers', { get: getPeers }],
]);
const STUN_COOKIE = 0x2112a442;
const STUN_REQ = 0x0001;
const STUN_RESP = 0x0101;
const STUN_ATTR_XOR_ADDR = 0x0020;
const STUN_HDR_SIZE = 20;
const STUN_ATTR_XOR_SIZE = 8;
const STUN_FAMILY_IPV4 = 0x01;
const STUN_COOKIE_BYTE1 = (STUN_COOKIE >>> 24) & 0xff;
const STUN_COOKIE_WORD1 = (STUN_COOKIE >>> 16) & 0xffff;
const createStunServer = () => {
const socket = dgram.createSocket('udp4');
socket.on('message', (msg, rinfo) => {
if (msg.length < STUN_HDR_SIZE) return;
const messageType = msg.readUInt16BE(0);
const messageLength = msg.readUInt16BE(2);
const magicCookie = msg.readUInt32BE(4);
const transactionId = msg.slice(8, STUN_HDR_SIZE);
if (magicCookie !== STUN_COOKIE) return;
if (messageType !== STUN_REQ) return;
if (msg.length < STUN_HDR_SIZE + messageLength) return;
const responseSize = STUN_HDR_SIZE + 4 + STUN_ATTR_XOR_SIZE;
const response = Buffer.alloc(responseSize);
response.writeUInt16BE(STUN_RESP, 0);
response.writeUInt16BE(STUN_ATTR_XOR_SIZE, 2);
response.writeUInt32BE(STUN_COOKIE, 4);
transactionId.copy(response, 8);
response.writeUInt16BE(STUN_ATTR_XOR_ADDR, STUN_HDR_SIZE);
response.writeUInt16BE(STUN_ATTR_XOR_SIZE, STUN_HDR_SIZE + 2);
response.writeUInt8(0x00, STUN_HDR_SIZE + 4);
const family = STUN_FAMILY_IPV4 ^ STUN_COOKIE_BYTE1;
response.writeUInt8(family, STUN_HDR_SIZE + 5);
const port = rinfo.port;
const xorPort = port ^ STUN_COOKIE_WORD1;
response.writeUInt16BE(xorPort, STUN_HDR_SIZE + 6);
const ipParts = rinfo.address.split('.').map(Number);
const shifts = [24, 16, 8, 0];
const ip = ipParts.reduce((acc, part, i) => acc | (part << shifts[i]), 0);
const xorIp = ip ^ STUN_COOKIE;
response.writeUInt32BE(xorIp, STUN_HDR_SIZE + 8);
socket.send(response, rinfo.port, rinfo.address, (error) => {
if (error) {
console.error('STUN send error:', error);
}
});
});
socket.on('error', (error) => {
console.error('STUN server error:', error);
});
return socket;
};
const prepareFile = async (url) => {
const paths = [STATIC_PATH, url];
if (url.endsWith('/')) paths.push('index.html');
const filePath = path.join(...paths);
const pathTraversal = !filePath.startsWith(STATIC_PATH);
const exists = await fs.promises.access(filePath).then(...toBool);
const found = !pathTraversal && exists;
const streamPath = found ? filePath : path.join(STATIC_PATH, '404.html');
const ext = path.extname(streamPath).substring(1).toLowerCase();
const stream = fs.createReadStream(streamPath);
return { found, ext, stream };
};
const handleRequest = async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`);
const route = routes.get(url.pathname);
const method = req.method.toLowerCase();
const handler = route?.[method];
if (handler) {
await handler(req, res, url);
return;
}
const file = await prepareFile(url.pathname);
const statusCode = file.found ? 200 : 404;
const mimeType = MIME_TYPES[file.ext] || MIME_TYPES.default;
const headers = { ...HEADERS, 'Content-Type': mimeType };
if (file.ext === 'html') Object.assign(headers, HEADERS_HTML);
res.writeHead(statusCode, headers);
file.stream.pipe(res);
};
const startServer = async () => {
const server = http.createServer();
const stunSocket = createStunServer();
process.on('SIGINT', () => {
console.log('\nShutting down server...');
stunSocket.close();
server.close(() => {
console.log('Server closed');
process.exit(0);
});
});
server.on('request', handleRequest);
server.listen(PORT, () => {
console.log(`Static Server running at http://127.0.0.1:${PORT}/`);
});
stunSocket.bind(STUN_PORT, () => {
console.log(`STUN Server running on UDP port ${STUN_PORT}`);
});
};
startServer();