-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
355 lines (314 loc) · 9.69 KB
/
server.js
File metadata and controls
355 lines (314 loc) · 9.69 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
347
348
349
350
351
352
353
354
355
// Import necessary modules
import http from 'http';
import fs from 'fs';
import crypto from 'crypto';
import { fileURLToPath } from 'url';
import path from 'path';
import { minify as terserMinify } from 'terser';
import pino from 'pino';
import connect from 'connect';
import route from 'connect-route';
import serveStatic from 'st';
import rateLimit from 'connect-ratelimit';
import fetch from 'node-fetch';
import dotenv from 'dotenv';
import DocumentHandler from './lib/document_handler.js';
dotenv.config();
const resolvedConfigPath = path.resolve('./config.js');
const resolvedConfigExamplePath = path.resolve('./config.js.example');
let createdConfigFromExample = false;
if (
!fs.existsSync(resolvedConfigPath) &&
fs.existsSync(resolvedConfigExamplePath)
) {
fs.copyFileSync(resolvedConfigExamplePath, resolvedConfigPath);
createdConfigFromExample = true;
}
const { default: config } = await import('./config.js');
config.port = process.env.PORT || config.port || 7777;
config.host = process.env.HOST || config.host || 'localhost';
config.storage = process.env.STORAGE || config.storage || { type: 'file' };
config.storage.type = process.env.STORAGE_TYPE || config.storage.type || 'file';
const enableDiscordLogging =
process.env.ENABLE_DISCORD_LOGGING === 'true' ||
config.enableDiscordLogging === true;
const discordWebhookUrl =
process.env.DISCORD_WEBHOOK_URL || config.discordWebhookUrl || null;
// Configure Pino logger
const logger = pino({
transport: {
target: 'pino-pretty',
options: {
colorize: true,
translateTime: 'SYS:standard',
ignore: 'pid,hostname',
},
},
});
if (createdConfigFromExample) {
logger.warn(
'config.js was missing and has been created from config.js.example',
);
}
logger.info({ configSource: 'config.js' }, 'Configuration loaded');
if (enableDiscordLogging && !discordWebhookUrl) {
logger.warn('Discord logging is enabled but no webhook URL is configured');
}
// Function to send logs to Discord
function sendLogToDiscord(message) {
if (enableDiscordLogging && discordWebhookUrl) {
fetch(discordWebhookUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content: message }),
}).catch((err) => {
logger.error('Failed to send log to Discord', { error: err });
});
}
}
// Initialize key generator
const { type: keyGenType = 'random', ...keyGenOptions } =
config.keyGenerator || {};
const KeyGenerator = (await import(`./lib/key_generators/${keyGenType}.js`))
.default;
const keyGenerator = new KeyGenerator(keyGenOptions);
// Initialize the preferred store
let Store;
let preferredStore;
if (process.env.REDISTOGO_URL && config.storage.type === 'redis') {
const redisClient = (await import('redis-url')).connect(
process.env.REDISTOGO_URL,
);
Store = (await import('./lib/document_stores/redis.js')).default;
preferredStore = new Store(config.storage, redisClient);
} else {
Store = (await import(`./lib/document_stores/${config.storage.type}.js`))
.default;
preferredStore = new Store(config.storage);
}
const documentHandler = new DocumentHandler({
store: preferredStore,
maxLength: config.maxLength,
keyLength: config.keyLength,
keyGenerator,
config, // Pass the full config including discordWebhookUrl
});
// Resolve __dirname for ES modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Compress static JavaScript assets
if (config.recompressStaticAssets) {
const staticDir = path.join(__dirname, 'static');
const files = fs.readdirSync(staticDir);
for (const file of files.filter(
(file) => file.endsWith('.js') && !file.endsWith('.min.js'),
)) {
const filePath = path.join(staticDir, file);
const minFilePath = filePath.replace(/\.js$/, '.min.js');
try {
const code = fs.readFileSync(filePath, 'utf8');
const minified = await terserMinify(code);
if (!minified.code) {
logger.error(`Error minifying file: ${file}`, {
error: 'Unknown minification error',
filePath,
});
} else {
fs.writeFileSync(minFilePath, minified.code, 'utf8');
logger.info(`Compressed ${file} to ${path.basename(minFilePath)}`);
}
} catch (err) {
logger.error(`Failed to process file: ${file}`, { error: err.message });
}
}
}
// Preload static documents
for (const [name, documentPath] of Object.entries(config.documents || {})) {
try {
const data = fs.readFileSync(documentPath, 'utf8');
preferredStore.set(
name,
data,
() => {
logger.debug(`Loaded static document: ${name}`);
},
true,
);
} catch (err) {
logger.warn(`Failed to load static document: ${name} - ${err.message}`);
}
}
const app = connect();
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('Referrer-Policy', 'no-referrer');
res.setHeader(
'Permissions-Policy',
'geolocation=(), microphone=(), camera=()',
);
next();
});
app.use((req, res, next) => {
const requestId = crypto.randomUUID();
const startedAt = Date.now();
req.requestId = requestId;
res.setHeader('X-Request-Id', requestId);
logger.info(
{ requestId, method: req.method, path: req.url },
'Request started',
);
res.on('finish', () => {
logger.info(
{
requestId,
method: req.method,
path: req.url,
statusCode: res.statusCode,
durationMs: Date.now() - startedAt,
},
'Request completed',
);
});
next();
});
app.use((req, res, next) => {
const routePath = (req.url || '').split('?')[0];
const originalWriteHead = res.writeHead;
res.writeHead = function patchedWriteHead(...args) {
if (
routePath === '/health' ||
routePath.startsWith('/documents') ||
routePath.startsWith('/raw/')
) {
res.setHeader('Cache-Control', 'no-store');
} else if (
routePath === '/' ||
routePath.endsWith('.html') ||
!path.extname(routePath)
) {
res.setHeader('Cache-Control', 'no-cache');
} else if (
routePath.endsWith('.min.js') ||
routePath.endsWith('.min.css')
) {
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
} else {
res.setHeader(
'Cache-Control',
`public, max-age=${config.staticMaxAge || 86400}`,
);
}
return originalWriteHead.apply(this, args);
};
next();
});
app.use((req, res, next) => {
if (req.method === 'POST' && req.url === '/documents') {
const contentLength = Number(req.headers['content-length'] || 0);
const postTimeoutMs = Number(
process.env.POST_TIMEOUT_MS || config.postTimeoutMs || 15000,
);
if (config.maxLength && contentLength && contentLength > config.maxLength) {
res.writeHead(413, { 'content-type': 'application/json' });
res.end(
JSON.stringify({
message: 'Payload too large.',
requestId: req.requestId || null,
}),
);
return;
}
req.setTimeout(postTimeoutMs, () => {
if (!res.headersSent) {
res.writeHead(408, { 'content-type': 'application/json' });
res.end(
JSON.stringify({
message: 'Request timeout.',
requestId: req.requestId || null,
}),
);
}
req.destroy();
});
}
next();
});
// Apply rate limiting if configured
if (config.rateLimits) {
app.use(rateLimit({ ...config.rateLimits, end: true }));
}
// Define API routes
app.use(
route((router) => {
router.get('/health', (req, res) => {
res.writeHead(200, { 'content-type': 'application/json' });
res.end(
JSON.stringify({ status: 'ok', requestId: req.requestId || null }),
);
});
router.get('/raw/:id', (req, res) =>
documentHandler.handleRawGet(req, res, config),
);
router.head('/raw/:id', (req, res) =>
documentHandler.handleRawGet(req, res, config),
);
router.get('/documents/:id', (req, res) =>
documentHandler.handleGet(req, res, config),
);
router.post('/documents', (req, res) =>
documentHandler.handlePost(req, res),
);
router.head('/documents/:id', (req, res) =>
documentHandler.handleGet(req, res, config),
);
}),
);
// Serve static files
const staticOptions = {
path: path.join(__dirname, 'static'),
content: { maxAge: config.staticMaxAge },
passthrough: true,
index: false,
};
app.use(serveStatic(staticOptions));
// Fallback to index.html for unmatched routes
app.use(
route((router) => {
router.get('/:id', (req, res, next) => {
// Strip any file extension from the ID
req.params.id = req.params.id.split('.')[0];
req.sturl = '/';
next();
});
}),
);
app.use(serveStatic({ ...staticOptions, index: 'index.html' }));
// Start the server
const server = http.createServer(app);
server.requestTimeout = Number(
process.env.REQUEST_TIMEOUT_MS || config.requestTimeoutMs || 30000,
);
server.headersTimeout = Number(
process.env.HEADERS_TIMEOUT_MS || config.headersTimeoutMs || 60000,
);
server.listen(config.port, config.host, () => {
const message = `Server listening on ${config.host}:${config.port}`;
logger.info(message);
sendLogToDiscord(message);
});
server.on('error', (error) => {
logger.error(`Server error: ${error.message}`, { error });
sendLogToDiscord(
`:x: Server error on ${config.host}:${config.port} - ${error.message}`,
);
});
const shutdown = (signal) => {
logger.info(`Received ${signal}, shutting down server...`);
server.close(() => {
logger.info('Server shutdown complete.');
process.exit(0);
});
};
process.on('SIGINT', () => shutdown('SIGINT'));
process.on('SIGTERM', () => shutdown('SIGTERM'));