-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathserver.js
104 lines (84 loc) · 2.79 KB
/
server.js
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
'use strict';
const express = require('express');
const cors = require('cors');
const fs = require('fs');
const path = require('path');
const app = express();
const port = process.env.PORT || 8080;
// Replace with your actual logging mechanism
const log = {
warn: console.warn,
error: console.error,
debug: console.log,
};
// Directory where recordings will be stored
const recordingDirectory = path.join(__dirname, 'rec');
// Flag to enable/disable server recording
const isServerRecordingEnabled = true;
// CORS options
const corsOptions = {
origin: '*',
methods: ['POST'],
};
// Middleware
app.use(express.json());
app.use(cors(corsOptions));
// Ensure the recording directory exists
function ensureRecordingDirectoryExists() {
if (!fs.existsSync(recordingDirectory)) {
fs.mkdirSync(recordingDirectory, { recursive: true });
}
}
// Endpoint to handle recording uploads
app.post('/recSync', (req, res) => {
try {
if (!isServerRecordingEnabled) {
return res.status(403).send('Server recording is disabled');
}
const { fileName } = req.query;
if (!fileName) {
return res.status(400).send('Filename not provided');
}
if (!isValidRecFileNameFormat(fileName)) {
log.warn('[RecSync] - Invalid file name', fileName);
return res.status(400).send('Invalid file name');
}
ensureRecordingDirectoryExists();
const filePath = path.join(recordingDirectory, fileName);
const writeStream = fs.createWriteStream(filePath, { flags: 'a' });
req.pipe(writeStream);
writeStream.on('error', (err) => {
log.error('[RecSync] - Error writing to file:', err.message);
res.status(500).send('Internal Server Error');
});
writeStream.on('finish', () => {
log.debug('[RecSync] - File saved successfully:', fileName);
res.status(200).send('File uploaded successfully');
});
req.on('error', (err) => {
log.error('[RecSync] - Error processing request:', err.message);
res.status(500).send('Internal Server Error');
});
} catch (err) {
log.error('[RecSync] - Error processing upload', err.message);
res.status(500).send('Internal Server Error');
}
});
// Start the server
app.listen(port, () => {
log.debug(`Server is running on http://localhost:${port}`);
});
// Utils
function isValidRecFileNameFormat(input) {
if (typeof input !== 'string') {
return false;
}
if (!input.startsWith('Rec_') || !input.endsWith('.webm')) {
return false;
}
return !hasPathTraversal(input);
}
function hasPathTraversal(input) {
const pathTraversalPattern = /(\.\.(\/|\\))+/;
return pathTraversalPattern.test(input);
}