Repository navigation
Expand file tree
/
Copy pathsimple_api.js
More file actions
453 lines (383 loc) · 14.6 KB
/
Copy pathsimple_api.js
File metadata and controls
453 lines (383 loc) · 14.6 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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const morgan = require('morgan');
const fs = require('fs').promises;
const path = require('path');
const WebSocket = require('ws');
const http = require('http');
const url = require('url');
const { v4: uuidv4 } = require('uuid');
const cookieParser = require('cookie-parser');
// Get the directory where the script is located using __dirname
const APP_DIR = __dirname;
const app = express();
const server = http.createServer(app);
// Constants
const MAX_RECORDS = 50;
// WebSocket server with proxy path support
const wss = new WebSocket.Server({
noServer: true
});
// Security middleware
app.use(helmet({
contentSecurityPolicy: {
directives: {
...helmet.contentSecurityPolicy.getDefaultDirectives(),
"script-src": ["'self'", "'unsafe-inline'"],
"connect-src": ["'self'", "ws://localhost:3006", "ws://localhost:3007", "ws://localhost:3008", "wss://codeserver.api-coolify.onlinecenter.com.br"]
}
}
}));
app.use(cors());
app.use(morgan('combined'));
app.use(express.json());
app.use(cookieParser());
// Authentication middleware
const AUTH_TOKEN = 'Bearer uzJtmYh8DrCuAK5td3APLxvYds704hOslXZJd7a';
const authenticateToken = (req, res, next) => {
const token = req.headers.authorization;
if (!token || token !== AUTH_TOKEN) {
return res.status(401).json({ error: 'Unauthorized' });
}
next();
};
// Constants for UUID cookie
const UUID_COOKIE_NAME = 'user_uuid';
const UUID_COOKIE_MAX_AGE = 1000 * 24 * 60 * 60 * 1000; // 1000 days in milliseconds
// Data file paths - using absolute path
const DATA_DIR = path.join(APP_DIR, 'data');
// Helper function to ensure data directory exists
async function ensureDataDir() {
try {
await fs.access(DATA_DIR);
} catch (error) {
if (error.code === 'ENOENT') {
await fs.mkdir(DATA_DIR, { recursive: true });
} else {
throw error;
}
}
}
// Helper function to get user file path
function getUserFilePath(uuid) {
return path.join(DATA_DIR, `${uuid}.json`);
}
// Helper function to read user data
async function readUserData(uuid) {
try {
await ensureDataDir();
const userFilePath = getUserFilePath(uuid);
const data = await fs.readFile(userFilePath, 'utf8');
return JSON.parse(data);
} catch (error) {
if (error.code === 'ENOENT') {
// Create empty data file for user
const emptyData = [];
await fs.writeFile(getUserFilePath(uuid), JSON.stringify(emptyData, null, 2));
return emptyData;
}
throw error;
}
}
// Helper function to write user data
async function writeUserData(uuid, data, changeInfo) {
// Sort by ID to ensure we keep the newest records
data.sort((a, b) => b.id - a.id);
// Keep only the newest MAX_RECORDS records
if (data.length > MAX_RECORDS) {
data = data.slice(0, MAX_RECORDS);
}
await ensureDataDir();
// Ensure proper JSON formatting with indentation
const jsonData = JSON.stringify(data, null, 2);
await fs.writeFile(getUserFilePath(uuid), jsonData);
broadcastUserData(uuid, changeInfo);
}
// Helper function to get or create UUID
function getOrCreateUuid(req, res) {
// Check if UUID exists in cookie
let uuid = req.cookies[UUID_COOKIE_NAME];
// If no UUID in cookie, create a new one
if (!uuid) {
uuid = uuidv4();
// Set cookie with long expiration
res.cookie(UUID_COOKIE_NAME, uuid, {
maxAge: UUID_COOKIE_MAX_AGE,
httpOnly: true,
path: '/'
});
}
return uuid;
}
// Map to store WebSocket connections by UUID
const wsConnectionsByUuid = new Map();
// Broadcast data to clients with specific UUID
function broadcastUserData(uuid, changeInfo = null) {
readUserData(uuid).then(data => {
const message = {
type: 'update',
data,
changeInfo
};
// Get WebSocket connections for this UUID
const connections = wsConnectionsByUuid.get(uuid) || [];
connections.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(message));
}
});
});
}
// Handle WebSocket upgrade
server.on('upgrade', (request, socket, head) => {
const parsedUrl = url.parse(request.url, true);
const { pathname } = parsedUrl;
// Extract UUID from path
const pathParts = pathname.split('/');
const uuidIndex = pathParts.findIndex(part =>
part.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i)
);
if (uuidIndex !== -1) {
const uuid = pathParts[uuidIndex];
wss.handleUpgrade(request, socket, head, (ws) => {
// Store UUID with the WebSocket connection
ws.uuid = uuid;
wss.emit('connection', ws, request);
});
} else if (pathname === '/simple-api' || pathname === '/proxy/3006' || pathname === '/proxy/3007' || pathname === '/') {
// Legacy path handling (should redirect in HTTP layer)
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request);
});
} else {
socket.destroy();
}
});
// WebSocket connection handler
wss.on('connection', (ws, request) => {
console.log('New WebSocket connection');
const uuid = ws.uuid;
if (uuid) {
// Add this connection to the map for the UUID
if (!wsConnectionsByUuid.has(uuid)) {
wsConnectionsByUuid.set(uuid, []);
}
wsConnectionsByUuid.get(uuid).push(ws);
// Send initial data
readUserData(uuid).then(data => {
ws.send(JSON.stringify({ type: 'update', data }));
});
// Clean up when connection closes
ws.on('close', () => {
const connections = wsConnectionsByUuid.get(uuid) || [];
const index = connections.indexOf(ws);
if (index !== -1) {
connections.splice(index, 1);
}
if (connections.length === 0) {
wsConnectionsByUuid.delete(uuid);
}
});
} else {
// Legacy connection without UUID
readUserData('default').then(data => {
ws.send(JSON.stringify({ type: 'update', data }));
});
}
ws.on('error', console.error);
});
// Helper function to extract UUID from URL
function extractUuidFromUrl(req) {
const pathParts = req.path.split('/');
const uuidIndex = pathParts.findIndex(part =>
part.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i)
);
return uuidIndex !== -1 ? pathParts[uuidIndex] : null;
}
// Create CRUD handlers
const createCrudHandlers = () => ({
create: async (req, res) => {
try {
const { name, occupation } = req.body;
if (!name || !occupation) {
return res.status(400).json({ error: 'Name e occupation são obrigatórios' });
}
// Get UUID from URL or cookie
const urlUuid = extractUuidFromUrl(req);
const uuid = urlUuid || getOrCreateUuid(req, res);
const data = await readUserData(uuid);
const newId = data.length > 0 ? Math.max(...data.map(r => r.id)) + 1 : 1;
const now = new Date().toISOString();
const newRecord = {
id: newId,
name,
occupation,
dataCriacao: now,
dataEdicao: now
};
data.push(newRecord);
await writeUserData(uuid, data, {
type: 'create',
id: newId,
timestamp: now
});
res.status(201).json(newRecord);
} catch (error) {
console.error('Error in create handler:', error);
res.status(500).json({ error: 'Erro interno do servidor' });
}
},
read: async (req, res) => {
try {
// Get UUID from URL or cookie
const urlUuid = extractUuidFromUrl(req);
const uuid = urlUuid || getOrCreateUuid(req, res);
const { id, name, occupation } = req.query;
let data = await readUserData(uuid);
// Aplicar filtros se fornecidos
if (id) {
data = data.filter(record => record.id === parseInt(id));
}
if (name) {
const nameLowerCase = name.toLowerCase();
data = data.filter(record =>
record.name.toLowerCase().includes(nameLowerCase)
);
}
if (occupation) {
const occupationLowerCase = occupation.toLowerCase();
data = data.filter(record =>
record.occupation.toLowerCase().includes(occupationLowerCase)
);
}
res.json(data);
} catch (error) {
console.error('Error in read handler:', error);
res.status(500).json({ error: 'Erro interno do servidor' });
}
},
update: async (req, res) => {
try {
const { id } = req.params;
const { name, occupation } = req.body;
if (!name || !occupation) {
return res.status(400).json({ error: 'Name e occupation são obrigatórios' });
}
// Get UUID from URL or cookie
const urlUuid = extractUuidFromUrl(req);
const uuid = urlUuid || getOrCreateUuid(req, res);
const data = await readUserData(uuid);
const index = data.findIndex(r => r.id === parseInt(id));
if (index === -1) {
return res.status(404).json({ error: 'Registro não encontrado' });
}
const now = new Date().toISOString();
data[index] = {
...data[index],
name,
occupation,
dataEdicao: now
};
await writeUserData(uuid, data, {
type: 'update',
id: parseInt(id),
timestamp: now
});
res.status(200).json(data[index]);
} catch (error) {
console.error('Error in update handler:', error);
res.status(500).json({ error: 'Erro interno do servidor' });
}
},
delete: async (req, res) => {
try {
const { id } = req.params;
// Get UUID from URL or cookie
const urlUuid = extractUuidFromUrl(req);
const uuid = urlUuid || getOrCreateUuid(req, res);
const data = await readUserData(uuid);
const index = data.findIndex(r => r.id === parseInt(id));
if (index === -1) {
return res.status(404).json({ error: 'Registro não encontrado' });
}
const now = new Date().toISOString();
data.splice(index, 1);
await writeUserData(uuid, data, {
type: 'delete',
id: parseInt(id),
timestamp: now
});
res.status(204).send();
} catch (error) {
console.error('Error in delete handler:', error);
res.status(500).json({ error: 'Erro interno do servidor' });
}
}
});
const handlers = createCrudHandlers();
// UUID redirect middleware
const uuidRedirectMiddleware = (req, res, next) => {
// Skip for static files, view routes, and API calls with Authorization header
if (req.path.includes('.') || req.path.includes('/view') || req.headers.authorization) {
return next();
}
// Check if URL already contains a UUID
const urlUuid = extractUuidFromUrl(req);
if (urlUuid) {
return next();
}
// Get or create UUID from cookie
const uuid = getOrCreateUuid(req, res);
// Construct redirect URL with UUID
let redirectUrl = req.originalUrl;
if (redirectUrl.endsWith('/')) {
redirectUrl = redirectUrl.slice(0, -1);
}
redirectUrl = `${redirectUrl}/${uuid}`;
// Redirect to URL with UUID
res.redirect(redirectUrl);
};
// Mount routes for both paths
const mountRoutes = (router, prefix = '') => {
// Add UUID redirect middleware only for root path
router.use(prefix, uuidRedirectMiddleware);
// Serve static files
router.use(prefix, express.static(path.join(APP_DIR, 'public')));
// View routes
router.get(`${prefix}/:uuid/view`, (req, res) => {
res.sendFile(path.join(APP_DIR, 'public', 'index.html'));
});
// REST API routes with authentication
router.post(`${prefix}/:uuid`, authenticateToken, handlers.create);
router.get(`${prefix}/:uuid`, (req, res, next) => {
// If it has authorization header, treat as API call
if (req.headers.authorization) {
return authenticateToken(req, res, () => handlers.read(req, res));
}
// Otherwise, check if it's a valid UUID and serve the interface
const uuid = req.params.uuid;
if (uuid && uuid.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i)) {
res.sendFile(path.join(APP_DIR, 'public', 'index.html'));
} else {
res.status(404).send('Not found');
}
});
router.put(`${prefix}/:uuid/:id`, authenticateToken, handlers.update);
router.delete(`${prefix}/:uuid/:id`, authenticateToken, handlers.delete);
// Root redirect
router.get(prefix, (req, res) => {
const uuid = getOrCreateUuid(req, res);
res.redirect(`${prefix}/${uuid}/view`);
});
};
// Mount routes for all paths
mountRoutes(app, '/simple-api');
mountRoutes(app, '/proxy/3006');
mountRoutes(app, '/proxy/3007');
mountRoutes(app);
const PORT = process.env.PORT || 3006;
server.listen(PORT, '0.0.0.0', () => {
console.log(`Server running on port ${PORT}`);
console.log(`Application directory: ${APP_DIR}`);
});