Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
346 lines (308 loc) · 12.3 KB
/
Copy pathserver.js
File metadata and controls
346 lines (308 loc) · 12.3 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
// Local WebSynapse server and Windows HID bridge host. Uses Node.js built-ins.
const http = require('http');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { spawn } = require('child_process');
const root = path.resolve(__dirname);
const port = Number(process.env.WEBSYNAPSE_PORT || 8000);
const bridgeScript = path.join(root, 'native-bridge.ps1');
// Per-process auth token required on every /api/hid/* request. It is injected
// into index.html on load (see handleStatic), so the real page has it but a
// page on a different origin cannot read it.
const authToken = crypto.randomBytes(24).toString('hex');
const AUTH_HEADER = 'x-websynapse-token';
// DNS-rebinding defence: only answer requests addressed to our own loopback
// host:port. A rebinding attack arrives with the attacker's hostname in Host.
// The server binds to 127.0.0.1 only; add `[::1]:${port}` if that ever changes.
const allowedHosts = new Set([`localhost:${port}`, `127.0.0.1:${port}`]);
const allowedOrigins = new Set([`http://localhost:${port}`, `http://127.0.0.1:${port}`]);
function isTrustedRequest(request) {
const host = String(request.headers.host || '').toLowerCase();
if (!allowedHosts.has(host)) return false;
const origin = request.headers.origin;
return origin === undefined || allowedOrigins.has(String(origin).toLowerCase());
}
// A bridge request that gets no answer usually means the bridge is stuck.
const BRIDGE_TIMEOUT_MS = 10000;
const contentTypes = {
'.css': 'text/css; charset=utf-8',
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.svg': 'image/svg+xml'
};
let bridge = null;
let bridgeBuffer = '';
let bridgeFailure = null;
let nextBridgeRequestId = 1;
const pendingBridgeRequests = new Map();
function rejectPendingBridgeRequests(error) {
for (const { reject } of pendingBridgeRequests.values()) reject(error);
pendingBridgeRequests.clear();
}
function stopBridge() {
const child = bridge;
bridge = null;
if (child && !child.killed) child.kill();
rejectPendingBridgeRequests(new Error('The local Windows HID bridge stopped. Restart WebSynapse and try again.'));
}
function processBridgeOutput(chunk) {
bridgeBuffer += chunk;
let newline;
while ((newline = bridgeBuffer.indexOf('\n')) !== -1) {
const line = bridgeBuffer.slice(0, newline).trim();
bridgeBuffer = bridgeBuffer.slice(newline + 1);
if (!line) continue;
let message;
try {
message = JSON.parse(line);
} catch {
bridgeFailure = `The Windows HID bridge returned an invalid response: ${line}`;
continue;
}
const pending = pendingBridgeRequests.get(message.id);
if (pending) {
pendingBridgeRequests.delete(message.id);
pending.resolve(message);
}
}
}
function startBridge() {
if (bridge) return bridge;
bridgeFailure = null;
bridgeBuffer = '';
// -ExecutionPolicy Bypass applies to this one pwsh process only (it does not
// change the system policy). Without it, a native-bridge.ps1 that Windows
// marks as downloaded from the internet is refused as "not digitally signed".
const child = spawn('pwsh.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', bridgeScript], {
cwd: root,
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true
});
bridge = child;
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
child.stdout.on('data', processBridgeOutput);
child.stderr.on('data', data => {
bridgeFailure = String(data).trim() || bridgeFailure;
});
child.on('error', error => {
bridgeFailure = `Could not start the Windows HID bridge: ${error.message}`;
if (bridge === child) bridge = null;
rejectPendingBridgeRequests(new Error(bridgeFailure));
});
child.on('close', code => {
if (bridge === child) bridge = null;
const message = bridgeFailure || `The Windows HID bridge exited (${code ?? 'unknown'}).`;
rejectPendingBridgeRequests(new Error(message));
});
return child;
}
function sendBridgeCommand(command, extra = {}) {
const child = startBridge();
if (!child.stdin || child.stdin.destroyed) {
return Promise.reject(new Error(bridgeFailure || 'The Windows HID bridge is unavailable.'));
}
const id = nextBridgeRequestId++;
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
if (!pendingBridgeRequests.delete(id)) return;
reject(new Error('The Windows HID bridge did not respond in time.'));
stopBridge(); // a silent bridge is stuck; restart it on the next call
}, BRIDGE_TIMEOUT_MS);
pendingBridgeRequests.set(id, {
resolve: value => { clearTimeout(timer); resolve(value); },
reject: error => { clearTimeout(timer); reject(error); }
});
child.stdin.write(`${JSON.stringify({ id, command, ...extra })}\n`, error => {
if (!error) return;
clearTimeout(timer);
pendingBridgeRequests.delete(id);
reject(new Error(`Could not send a command to the Windows HID bridge: ${error.message}`));
});
});
}
function sendJson(response, status, body) {
response.writeHead(status, {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store'
});
response.end(JSON.stringify(body));
}
// Requires application/json for anything with a body, which stops a plain
// HTML <form> POST (sent by browsers without preflight) from reaching the parser.
function readJson(request) {
return new Promise((resolve, reject) => {
const contentType = request.headers['content-type'] || '';
if (request.method === 'POST' && contentType && !contentType.includes('application/json')) {
const error = new Error('Content-Type must be application/json.');
error.statusCode = 415;
reject(error);
return;
}
let body = '';
request.setEncoding('utf8');
request.on('data', chunk => {
body += chunk;
if (body.length > 16 * 1024) {
const error = new Error('Request body is too large.');
error.statusCode = 413;
reject(error);
request.destroy();
}
});
request.on('end', () => {
try {
resolve(body ? JSON.parse(body) : {});
} catch {
const error = new Error('Request body must be valid JSON.');
error.statusCode = 400;
reject(error);
}
});
request.on('error', reject);
});
}
// Rejects anything that isn't even a well-formed Razer report (wrong length or
// bad checksum) before it reaches the device.
function validateRazerReportBase64(value) {
if (typeof value !== 'string') return 'A base64 feature report is required.';
let bytes;
try {
bytes = Buffer.from(value, 'base64');
} catch {
return 'The report was not valid base64.';
}
if (bytes.length !== 90) {
return `The report must be exactly 90 bytes (got ${bytes.length}).`;
}
let crc = 0;
for (let i = 2; i < 88; i++) crc ^= bytes[i];
if (crc !== bytes[88]) {
return 'The report\u2019s checksum does not match its contents.';
}
return null;
}
function isAuthorized(request) {
const presented = request.headers[AUTH_HEADER];
return typeof presented === 'string' && presented === authToken;
}
async function handleApi(request, response, pathname) {
if (!isAuthorized(request)) {
sendJson(response, 403, { ok: false, error: 'Missing or invalid session token.' });
return;
}
let command;
let extra = {};
if (request.method === 'GET' && pathname === '/api/hid/status') command = 'status';
if (request.method === 'POST' && pathname === '/api/hid/connect') command = 'connect';
if (request.method === 'POST' && pathname === '/api/hid/disconnect') command = 'disconnect';
if (request.method === 'POST' && pathname === '/api/hid/set') {
command = 'setFeature';
const body = await readJson(request);
const validationError = validateRazerReportBase64(body.report);
if (validationError) {
sendJson(response, 400, { ok: false, error: validationError });
return;
}
extra = { report: body.report };
}
if (request.method === 'POST' && pathname === '/api/hid/get') command = 'getFeature';
if (!command) {
sendJson(response, 404, { ok: false, error: 'Unknown HID bridge endpoint.' });
return;
}
try {
const result = await sendBridgeCommand(command, extra);
sendJson(response, result.ok ? 200 : 409, result);
} catch (error) {
sendJson(response, 503, { ok: false, error: error.message });
}
}
function handleStatic(request, response, pathname) {
if (pathname === '/favicon.ico') {
response.writeHead(204, { 'Cache-Control': 'no-store' });
response.end();
return;
}
if (!['GET', 'HEAD'].includes(request.method)) {
response.writeHead(405);
response.end('Method not allowed');
return;
}
const relativePath = pathname === '/' ? 'index.html' : pathname.slice(1);
const filePath = path.resolve(root, relativePath);
if (filePath !== root && !filePath.startsWith(root + path.sep)) {
response.writeHead(403);
response.end('Forbidden');
return;
}
// index.html gets the session token injected on every load; every other
// static asset streams straight from disk, unchanged.
if (relativePath === 'index.html') {
fs.readFile(filePath, 'utf8', (readError, html) => {
if (readError) {
response.writeHead(404);
response.end('Not found');
return;
}
const tokenScript = `<script>window.__WEBSYNAPSE_TOKEN__=${JSON.stringify(authToken)};</script>\n</head>`;
const injected = html.includes('</head>') ? html.replace('</head>', tokenScript) : html;
response.writeHead(200, {
'Content-Type': contentTypes['.html'],
'Cache-Control': 'no-store'
});
response.end(request.method === 'HEAD' ? undefined : injected);
});
return;
}
fs.stat(filePath, (statError, stats) => {
if (statError || !stats.isFile()) {
response.writeHead(404);
response.end('Not found');
return;
}
response.writeHead(200, {
'Content-Type': contentTypes[path.extname(filePath).toLowerCase()] || 'application/octet-stream',
'Cache-Control': 'no-store'
});
if (request.method === 'HEAD') response.end();
else fs.createReadStream(filePath).pipe(response);
});
}
const server = http.createServer(async (request, response) => {
// Applies to ALL requests (static files included): the session token is
// served through index.html, so that is where a rebinding attack would leak it.
if (!isTrustedRequest(request)) {
response.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
response.end('Forbidden: unexpected Host or Origin.');
return;
}
let pathname;
try {
pathname = decodeURIComponent(new URL(request.url, 'http://localhost').pathname);
} catch {
response.writeHead(400);
response.end('Bad request');
return;
}
try {
if (pathname.startsWith('/api/hid/')) await handleApi(request, response, pathname);
else handleStatic(request, response, pathname);
} catch (error) {
sendJson(response, error.statusCode || 500, { ok: false, error: error.message || 'Server error.' });
}
});
function shutdown() {
stopBridge();
server.close(() => process.exit(0));
setTimeout(() => process.exit(0), 1000).unref();
}
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
server.listen(port, '127.0.0.1', () => {
console.log(`WebSynapse is running at http://localhost:${port}`);
console.log('The Windows HID bridge starts automatically when you connect. Press Ctrl+C to stop the server.');
});