-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
275 lines (245 loc) · 8.86 KB
/
Copy pathserver.js
File metadata and controls
275 lines (245 loc) · 8.86 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
const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');
const DIST_DIR = path.join(__dirname, 'dist');
const CLIENT_DIR = path.join(__dirname, 'client');
// Check if IS_PRODUCTION is set to true
const isProduction = process.env.IS_PRODUCTION === 'true';
// In production mode, dist directory must exist
if (isProduction && !fs.existsSync(DIST_DIR)) {
throw new Error(`Production mode enabled but dist directory does not exist: ${DIST_DIR}`);
}
// Force port 3000 in production, otherwise use PORT environment variable or default to 3000
const PORT = isProduction ? 3000 : (process.env.PORT || 3000);
// MIME types for different file extensions
const mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.ttf': 'font/ttf',
'.eot': 'application/vnd.ms-fontobject'
};
// Get MIME type based on file extension
function getMimeType(filePath) {
const ext = path.extname(filePath).toLowerCase();
return mimeTypes[ext] || 'text/plain';
}
function getStatsFilePath() {
return isProduction
? path.join(DIST_DIR, 'stats.txt')
: path.join(CLIENT_DIR, 'stats.txt');
}
// Play counter for audio tasks that cap how many times the clip may be played.
// It lives server-side (not in the browser) so reloading the page cannot hand
// the candidate a fresh listen budget.
function getPlaysFilePath() {
return isProduction
? path.join(DIST_DIR, 'plays.json')
: path.join(CLIENT_DIR, 'plays.json');
}
// The server is the authority on the limit too: config.json is on disk here, so
// the browser cannot raise its own cap by editing the copy it was served.
function getConfigFilePath() {
return isProduction
? path.join(DIST_DIR, 'config.json')
: path.join(CLIENT_DIR, 'config.json');
}
// Returns the configured limit, 0 when the task configures no limit, or null
// when the configuration cannot be read. Null means "unknown", and callers must
// fail closed: treating an unreadable config as unlimited would silently drop
// the limit for a task that has one. (Only tasks that configure a limit ever
// call /play, so failing closed cannot over-block an unlimited task.)
function getMaxPlays() {
let raw;
try {
raw = fs.readFileSync(getConfigFilePath(), 'utf8');
} catch (error) {
return null;
}
try {
const config = JSON.parse(raw);
const max = config && config.audio && config.audio.maxPlays;
return Number.isInteger(max) && max > 0 ? max : 0;
} catch (error) {
return null;
}
}
// Returns the number of plays consumed, or null when the counter exists but
// cannot be trusted. A missing file means "none used yet"; corrupt data must NOT
// silently become 0, or a damaged file would hand back the whole listen budget.
function readPlaysUsed() {
let raw;
try {
raw = fs.readFileSync(getPlaysFilePath(), 'utf8');
} catch (error) {
return error.code === 'ENOENT' ? 0 : null;
}
try {
const parsed = JSON.parse(raw);
if (!Number.isInteger(parsed.playsUsed) || parsed.playsUsed < 0) return null;
return parsed.playsUsed;
} catch (error) {
return null;
}
}
// Write to a sibling temp file and rename, so an interrupted write can never
// leave a truncated plays.json behind (rename is atomic on the same filesystem).
function writePlaysUsed(playsUsed) {
const playsPath = getPlaysFilePath();
const dir = path.dirname(playsPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
const tempPath = path.join(dir, `.plays.${process.pid}.tmp`);
fs.writeFileSync(tempPath, JSON.stringify({ playsUsed }), 'utf8');
fs.renameSync(tempPath, playsPath);
}
// Serve static files
function serveFile(filePath, res) {
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('File not found');
return;
}
const mimeType = getMimeType(filePath);
res.writeHead(200, { 'Content-Type': mimeType });
res.end(data);
});
}
// Handle POST requests
function handlePostRequest(req, res, parsedUrl) {
if (parsedUrl.pathname === '/play') {
// Reserve one play. This is the authority: it decides against the limit in
// config.json on disk, so a stale client, a second tab, or a dropped request
// cannot push playback past the cap.
try {
const maxPlays = getMaxPlays();
const used = readPlaysUsed();
if (used === null || maxPlays === null) {
// Counter or limit unreadable: fail closed rather than granting a free
// play. An unknown limit must never be treated as "unlimited".
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ allowed: false, unavailable: true, maxPlays }));
return;
}
if (maxPlays && used >= maxPlays) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ allowed: false, playsUsed: used, maxPlays }));
return;
}
const playsUsed = used + 1;
writePlaysUsed(playsUsed);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ allowed: true, playsUsed, maxPlays }));
} catch (error) {
console.error('Error recording play:', error);
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Failed to record play' }));
}
return;
}
if (parsedUrl.pathname === '/save-stats') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
const statsPath = getStatsFilePath();
const statsDir = path.dirname(statsPath);
if (!fs.existsSync(statsDir)) {
fs.mkdirSync(statsDir, { recursive: true });
}
fs.writeFileSync(statsPath, body, 'utf8');
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ success: true, message: 'Statistics saved' }));
} catch (error) {
console.error('Error saving statistics:', error);
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Failed to save statistics' }));
}
});
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not found');
}
}
// Create HTTP server
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
let pathName = parsedUrl.pathname === '/' ? '/index.html' : parsedUrl.pathname;
// Handle POST requests
if (req.method === 'POST') {
handlePostRequest(req, res, parsedUrl);
return;
}
// Report how many plays have been consumed so the client can restore the
// remaining listen budget after a reload.
if (parsedUrl.pathname === '/plays') {
const used = readPlaysUsed();
const max = getMaxPlays();
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(used === null || max === null
? { unavailable: true, maxPlays: max }
: { playsUsed: used, maxPlays: max }));
return;
}
// In production mode, serve static files from dist directory
if (isProduction) {
// Strip leading slashes so path.join/resolve can't ignore DIST_DIR
let filePath = path.join(DIST_DIR, pathName.replace(/^\/+/, ''));
// Security check - prevent directory traversal
const resolvedDistDir = path.resolve(DIST_DIR);
const resolvedFilePath = path.resolve(filePath);
const relativePath = path.relative(resolvedDistDir, resolvedFilePath);
// Reject if path tries to traverse outside the base directory
if (relativePath.startsWith('..')) {
res.writeHead(403, { 'Content-Type': 'text/plain' });
res.end('Forbidden');
return;
}
serveFile(filePath, res);
} else {
// Development mode - static files are served by Vite
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not found (development mode - use Vite dev server `npm run start:dev`)');
}
});
// Start server
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
if (isProduction) {
console.log(`Serving static files from: ${DIST_DIR}`);
} else {
console.log(`Development mode - static files served by Vite`);
}
console.log('Press Ctrl+C to stop the server');
});
// Handle server errors
server.on('error', (err) => {
if (err.code === 'EADDRINUSE') {
console.error(`Port ${PORT} is already in use. Please try a different port.`);
} else {
console.error('Server error:', err);
}
process.exit(1);
});
// Graceful shutdown
process.on('SIGINT', () => {
console.log('\nShutting down server...');
server.close(() => {
console.log('Server closed');
process.exit(0);
});
});