-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
2188 lines (1912 loc) · 76 KB
/
server.js
File metadata and controls
2188 lines (1912 loc) · 76 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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const db = require('./database');
const crypto = require('crypto');
const DataTransformer = require('./transformer');
const AlertMonitor = require('./alert-monitor');
const app = express();
const PORT = 3000;
const transformer = new DataTransformer();
const alertMonitor = new AlertMonitor();
app.use(cors());
app.use(bodyParser.json());
app.use(express.static('public'));
// --- Cache Storage ---
const cache = new Map();
const CACHE_TTL = 3600000; // 1 hour in milliseconds
// --- Middleware ---
// 1. Authentication & Rate Limiting Middleware
const authenticateAndRateLimit = (req, res, next) => {
const apiKey = req.headers['x-gateway-api-key'];
// Skip auth for OpenData (public)
if (req.path.startsWith('/opendata/')) {
return next();
}
// Skip auth for Admin (simplified for prototype, usually needs login)
// For this prototype, we'll check a hardcoded admin key or just allow local access if needed.
// Let's enforce key for simplicity based on requirements.
if (!apiKey) {
return res.status(401).json({ error: 'Unauthorized: Missing API Key' });
}
const apiKeyHash = hashApiKey(apiKey);
db.get("SELECT * FROM systems WHERE api_key_hash = ?", [apiKeyHash], (err, system) => {
if (err) {
return res.status(500).json({ error: 'Internal Server Error' });
}
if (!system) {
return res.status(401).json({ error: 'Unauthorized: Invalid API Key' });
}
// Check IP whitelist if configured
if (system.ip_whitelist) {
const clientIp = req.ip || req.connection.remoteAddress;
if (!checkIpWhitelist(clientIp, system.ip_whitelist)) {
return res.status(403).json({ error: 'Forbidden: IP not in whitelist' });
}
}
// Skip rate limiting for admin endpoints
if (req.path.startsWith('/api/admin/')) {
req.system = system;
return next();
}
// Rate Limiting Check (for non-admin endpoints)
checkRateLimit(system, (rateLimitErr, allowed, remaining) => {
if (rateLimitErr) {
return res.status(500).json({ error: 'Internal Server Error' });
}
if (!allowed) {
res.set('X-RateLimit-Limit', system.rate_limit);
res.set('X-RateLimit-Remaining', 0);
res.set('Retry-After', 3600); // 1 hour in seconds
return res.status(429).json({
error: 'Too Many Requests',
message: `Rate limit exceeded. Limit: ${system.rate_limit} requests per hour.`
});
}
// Add rate limit headers
res.set('X-RateLimit-Limit', system.rate_limit);
res.set('X-RateLimit-Remaining', remaining);
// Permission Check (only for non-admin endpoints)
if (!req.path.startsWith('/api/admin/')) {
checkPermission(system.system_id, req.path, (permErr, hasPermission) => {
if (permErr) {
return res.status(500).json({ error: 'Internal Server Error' });
}
if (!hasPermission) {
return res.status(403).json({
error: 'Forbidden',
message: `System '${system.system_name}' does not have permission to access this endpoint.`
});
}
req.system = system;
next();
});
} else {
req.system = system;
next();
}
});
});
};
// 2. Logging Middleware
app.use((req, res, next) => {
// Skip logging for:
// - Admin endpoints
// - Static files (HTML, CSS, JS, images, etc.)
// - Root path
if (
req.path.startsWith('/api/admin/') ||
req.path === '/' ||
req.path.endsWith('.html') ||
req.path.endsWith('.css') ||
req.path.endsWith('.js') ||
req.path.endsWith('.png') ||
req.path.endsWith('.jpg') ||
req.path.endsWith('.ico')
) {
return next();
}
const start = Date.now();
const originalSend = res.send;
res.send = function (body) {
const duration = Date.now() - start;
const logId = crypto.randomUUID();
const systemId = req.system ? req.system.system_id : null;
// Resolve endpoint_id based on path
db.get("SELECT endpoint_id FROM api_endpoints WHERE gateway_path = ?", [req.path], (err, endpoint) => {
const endpointId = endpoint ? endpoint.endpoint_id : null;
// Only log if we found a matching endpoint (real business API request)
if (endpointId) {
db.run(`INSERT INTO request_logs (log_id, request_id, system_id, endpoint_id, http_status, response_time_ms)
VALUES (?, ?, ?, ?, ?, ?)`,
[logId, crypto.randomUUID(), systemId, endpointId, res.statusCode, duration],
(err) => {
if (err) console.error("Logging error:", err);
});
}
});
originalSend.call(this, body);
};
next();
});
// 3. Cache Middleware
const cacheMiddleware = (req, res, next) => {
// Only cache GET requests
if (req.method !== 'GET') {
return next();
}
// Skip cache for admin endpoints
if (req.path.startsWith('/api/admin/')) {
return next();
}
const cacheKey = req.path + JSON.stringify(req.query);
const cached = cache.get(cacheKey);
if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
res.set('X-Cache-Status', 'HIT');
res.set('X-Cache-Age', Math.floor((Date.now() - cached.timestamp) / 1000) + 's');
return res.send(cached.data);
}
// Store original send function
const originalSend = res.send;
// Override send to cache the response
res.send = function (body) {
cache.set(cacheKey, {
data: body,
timestamp: Date.now()
});
res.set('X-Cache-Status', 'MISS');
originalSend.call(this, body);
};
next();
};
app.use(cacheMiddleware);
app.use(authenticateAndRateLimit);
// --- Routes ---
// 1. OpenData Endpoint
app.get('/opendata/health-centers', async (req, res) => {
// Mock Data as per requirements
const data = [
{
"Name": "斗六市衛生所",
"Code": "YL001",
"Telephone": "05-5322154",
"Address": "雲林縣斗六市府前街23號",
"City": "雲林縣",
"District": "斗六市",
"Latitude": 23.7117,
"Longitude": 120.5437
},
{
"Name": "斗南鎮衛生所",
"Code": "YL002",
"Telephone": "05-5962004",
"Address": "雲林縣斗南鎮中山路180號",
"City": "雲林縣",
"District": "斗南鎮",
"Latitude": 23.6797,
"Longitude": 120.4783
}
];
const format = req.query.format || 'json';
const sourcePayload = {
metadata: {
datasetIdentifier: "yunlin-health-centers",
title: "雲林縣衛生所資訊",
organization: "雲林縣衛生局",
lastModified: "2024-11-20",
schema: "https://schema.gov.tw/Details?nodeId=25507",
totalRecords: data.length
},
data: data
};
// Apply transformation rule if configured for this endpoint
const transformed = await maybeTransformResponse(req.path, sourcePayload, 'json');
if (transformed) {
res.header('Content-Type', transformed.contentType);
return res.send(transformed.body);
}
if (format === 'csv') {
let csv = 'Name,Code,Telephone,Address,City,District,Latitude,Longitude\n';
data.forEach(row => {
csv += `${row.Name},${row.Code},${row.Telephone},${row.Address},${row.City},${row.District},${row.Latitude},${row.Longitude}\n`;
});
res.header('Content-Type', 'text/csv');
return res.send(csv);
}
res.json(sourcePayload);
});
// 2. AI Passthrough Endpoint - OpenAI
app.post('/external/openai/chat', async (req, res) => {
const targetKey = req.headers['x-target-api-key'];
if (!targetKey) {
return res.status(400).json({ error: 'Missing X-Target-API-Key' });
}
// Mock response for testing
if (targetKey === 'mock-openai-key') {
return res.json({
id: "chatcmpl-mock",
object: "chat.completion",
created: Date.now(),
model: req.body.model || "gpt-4o-mini",
choices: [{
index: 0,
message: {
role: "assistant",
content: "This is a mocked response from the API Gateway."
},
finish_reason: "stop"
}]
});
}
// Forwarding to real OpenAI
try {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${targetKey}`
},
body: JSON.stringify(req.body)
});
const data = await response.json();
res.status(response.status).json(data);
} catch (error) {
res.status(502).json({ error: 'Bad Gateway: Failed to connect to OpenAI' });
}
});
// 2b. AI Passthrough Endpoint - xAI (Grok)
app.post('/external/xai/chat', async (req, res) => {
// Support both X-Target-API-Key and Authorization header
let targetKey = req.headers['x-target-api-key'];
if (!targetKey && req.headers['authorization']) {
const authHeader = req.headers['authorization'];
if (authHeader.startsWith('Bearer ')) {
targetKey = authHeader.substring(7);
}
}
if (!targetKey) {
return res.status(400).json({ error: 'Missing X-Target-API-Key or Authorization header' });
}
// === Apply Request Transformation (Push) ===
let requestBody = req.body;
const transformedRequest = await maybeTransformRequest(req.path, req.body, 'json');
if (transformedRequest) {
requestBody = transformedRequest.body;
console.log(`✓ Request transformed for ${req.path}:`, JSON.stringify(requestBody));
}
// Forwarding to xAI (Grok)
try {
const response = await fetch('https://api.x.ai/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${targetKey}`
},
body: JSON.stringify(requestBody)
});
const data = await response.json();
// === Apply Response Transformation (Pull) ===
const transformedResponse = await maybeTransformResponse(req.path, data, 'json');
if (transformedResponse) {
console.log(`✓ Response transformed for ${req.path}`);
return res.status(response.status).json(transformedResponse.body);
}
res.status(response.status).json(data);
} catch (error) {
res.status(502).json({ error: 'Bad Gateway: Failed to connect to xAI' });
}
});
// 3. Admin API Endpoints
app.get('/api/admin/stats', (req, res) => {
const period = req.query.period || 'today';
// Configure time filter and grouping based on period
let timeFilter, groupBy, timeLabel, dataPoints;
switch (period) {
case 'week':
timeFilter = "datetime('now', '-7 days')";
groupBy = "strftime('%Y-%m-%d', created_at)";
timeLabel = 'date';
dataPoints = 7;
break;
case 'month':
timeFilter = "datetime('now', '-30 days')";
groupBy = "strftime('%Y-%m-%d', created_at)";
timeLabel = 'date';
dataPoints = 30;
break;
case 'today':
default:
timeFilter = "datetime('now', '-24 hours')";
groupBy = "strftime('%H', created_at)";
timeLabel = 'hour';
dataPoints = 24;
break;
}
// Return stats including traffic data for chart
db.get("SELECT COUNT(*) as count FROM request_logs", (err, row) => {
if (err) return res.status(500).json({ error: err.message });
db.get("SELECT COUNT(*) as count FROM api_endpoints WHERE is_active = 1", (err, epRow) => {
if (err) return res.status(500).json({ error: err.message });
db.get("SELECT COUNT(*) as count FROM systems", (err, sysRow) => {
if (err) return res.status(500).json({ error: err.message });
// Get traffic data based on period
const trafficQuery = `
SELECT
${groupBy} as time_unit,
COUNT(*) as count
FROM request_logs
WHERE created_at >= ${timeFilter}
GROUP BY time_unit
ORDER BY time_unit
`;
db.all(trafficQuery, (err, trafficData) => {
if (err) {
// If error, return basic stats without traffic data
return res.json({
total_requests: row.count,
active_endpoints: epRow.count,
systems_connected: sysRow.count,
traffic_data: [],
api_usage: []
});
}
// Process traffic data based on period
let processedTraffic = [];
const now = new Date();
if (period === 'today') {
// Fill in missing hours with zero counts
const hourlyMap = {};
trafficData.forEach(item => {
hourlyMap[parseInt(item.time_unit)] = item.count;
});
// Generate last 24 hours of data
for (let i = 23; i >= 0; i--) {
const targetHour = (now.getHours() - i + 24) % 24;
processedTraffic.push({
label: `${String(targetHour).padStart(2, '0')}:00`,
count: hourlyMap[targetHour] || 0
});
}
} else {
// For week/month, fill in missing dates
const dateMap = {};
trafficData.forEach(item => {
dateMap[item.time_unit] = item.count;
});
const daysBack = period === 'week' ? 7 : 30;
for (let i = daysBack - 1; i >= 0; i--) {
const targetDate = new Date(now);
targetDate.setDate(targetDate.getDate() - i);
const dateStr = targetDate.toISOString().split('T')[0];
processedTraffic.push({
label: dateStr,
count: dateMap[dateStr] || 0
});
}
}
// Get API endpoint usage statistics
const apiUsageQuery = `
SELECT
e.name,
e.api_type,
COUNT(*) as count
FROM request_logs rl
INNER JOIN api_endpoints e ON rl.endpoint_id = e.endpoint_id
WHERE rl.created_at >= ${timeFilter}
AND rl.endpoint_id IS NOT NULL
GROUP BY e.endpoint_id, e.name, e.api_type
ORDER BY count DESC
LIMIT 10
`;
db.all(apiUsageQuery, (err, apiUsageData) => {
if (err) {
// If error getting API usage, return without it
return res.json({
total_requests: row.count,
active_endpoints: epRow.count,
systems_connected: sysRow.count,
traffic_data: processedTraffic,
api_usage: [],
period: period
});
}
res.json({
total_requests: row.count,
active_endpoints: epRow.count,
systems_connected: sysRow.count,
traffic_data: processedTraffic,
api_usage: apiUsageData || [],
period: period
});
});
});
});
});
});
});
app.get('/api/admin/logs', (req, res) => {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 20;
const offset = (page - 1) * limit;
// Get total count
db.get("SELECT COUNT(*) as total FROM request_logs", (err, countRow) => {
if (err) return res.status(500).json({ error: err.message });
const total = countRow.total;
const totalPages = Math.ceil(total / limit);
const query = `
SELECT
rl.log_id,
rl.request_id,
rl.http_status,
rl.response_time_ms,
rl.created_at,
s.system_name,
e.name as endpoint_name,
e.gateway_path
FROM request_logs rl
LEFT JOIN systems s ON rl.system_id = s.system_id
LEFT JOIN api_endpoints e ON rl.endpoint_id = e.endpoint_id
ORDER BY rl.created_at DESC
LIMIT ? OFFSET ?
`;
db.all(query, [limit, offset], (err, rows) => {
if (err) return res.status(500).json({ error: err.message });
res.json({
data: rows,
pagination: {
page,
limit,
total,
totalPages
}
});
});
});
});
// Get all endpoints
app.get('/api/admin/endpoints', (req, res) => {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
const offset = (page - 1) * limit;
// Get total count
db.get("SELECT COUNT(*) as total FROM api_endpoints", (err, countRow) => {
if (err) return res.status(500).json({ error: err.message });
const total = countRow.total;
const totalPages = Math.ceil(total / limit);
db.all("SELECT * FROM api_endpoints LIMIT ? OFFSET ?", [limit, offset], (err, rows) => {
if (err) return res.status(500).json({ error: err.message });
res.json({
data: rows,
pagination: {
page,
limit,
total,
totalPages
}
});
});
});
});
// Create endpoint
app.post('/api/admin/endpoints', (req, res) => {
const { name, gateway_path, target_url, api_type, timeout } = req.body;
const endpoint_id = crypto.randomUUID();
db.run(`INSERT INTO api_endpoints (endpoint_id, name, gateway_path, target_url, api_type, timeout)
VALUES (?, ?, ?, ?, ?, ?)`,
[endpoint_id, name, gateway_path, target_url, api_type, timeout || 30],
function (err) {
if (err) return res.status(500).json({ error: err.message });
res.json({ id: endpoint_id, message: "Endpoint created" });
});
});
// Update endpoint
app.put('/api/admin/endpoints/:id', (req, res) => {
const { name, gateway_path, target_url, api_type, timeout, is_active } = req.body;
const { id } = req.params;
db.run(`UPDATE api_endpoints SET name = ?, gateway_path = ?, target_url = ?, api_type = ?, timeout = ?, is_active = ?
WHERE endpoint_id = ?`,
[name, gateway_path, target_url, api_type, timeout, is_active, id],
function (err) {
if (err) return res.status(500).json({ error: err.message });
res.json({ message: "Endpoint updated" });
});
});
// Delete endpoint
app.delete('/api/admin/endpoints/:id', (req, res) => {
const { id } = req.params;
db.run("DELETE FROM api_endpoints WHERE endpoint_id = ?", [id], function (err) {
if (err) return res.status(500).json({ error: err.message });
res.json({ message: "Endpoint deleted" });
});
});
// 4. System Management API Endpoints
// Get all systems
app.get('/api/admin/systems', (req, res) => {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
const offset = (page - 1) * limit;
// Get total count
db.get("SELECT COUNT(*) as total FROM systems", (err, countRow) => {
if (err) return res.status(500).json({ error: err.message });
const total = countRow.total;
const totalPages = Math.ceil(total / limit);
db.all("SELECT * FROM systems LIMIT ? OFFSET ?", [limit, offset], (err, rows) => {
if (err) return res.status(500).json({ error: err.message });
// Mask API keys for security - but we can't show the original key anymore
const maskedRows = rows.map(row => ({
...row,
api_key_display: '(已加密存儲)',
api_key_hash: undefined // Don't expose hash
}));
res.json({
data: maskedRows,
pagination: {
page,
limit,
total,
totalPages
}
});
});
});
});
// Create system
app.post('/api/admin/systems', (req, res) => {
const { system_name, rate_limit, ip_whitelist } = req.body;
const system_id = crypto.randomUUID();
const api_key = generateApiKey();
const api_key_hash = hashApiKey(api_key);
db.run(`INSERT INTO systems (system_id, system_name, api_key_hash, rate_limit, ip_whitelist)
VALUES (?, ?, ?, ?, ?)`,
[system_id, system_name, api_key_hash, rate_limit || 1000, ip_whitelist || null],
function (err) {
if (err) return res.status(500).json({ error: err.message });
res.json({
id: system_id,
api_key: api_key, // Return plain key only once
message: "System created"
});
});
});
// Update system
app.put('/api/admin/systems/:id', (req, res) => {
const { system_name, rate_limit, ip_whitelist } = req.body;
const { id } = req.params;
db.run(`UPDATE systems SET system_name = ?, rate_limit = ?, ip_whitelist = ?
WHERE system_id = ?`,
[system_name, rate_limit, ip_whitelist, id],
function (err) {
if (err) return res.status(500).json({ error: err.message });
res.json({ message: "System updated" });
});
});
// Delete system
app.delete('/api/admin/systems/:id', (req, res) => {
const { id } = req.params;
db.run("DELETE FROM systems WHERE system_id = ?", [id], function (err) {
if (err) return res.status(500).json({ error: err.message });
res.json({ message: "System deleted" });
});
});
// Reset API Key
app.post('/api/admin/systems/:id/reset-key', (req, res) => {
const { id } = req.params;
const new_api_key = generateApiKey();
const new_api_key_hash = hashApiKey(new_api_key);
db.run("UPDATE systems SET api_key_hash = ? WHERE system_id = ?", [new_api_key_hash, id], function (err) {
if (err) return res.status(500).json({ error: err.message });
res.json({ api_key: new_api_key, message: "API Key reset successfully" });
});
});
// 5. Permission Management Endpoints
// Get permissions for a system
app.get('/api/admin/systems/:id/permissions', (req, res) => {
const { id } = req.params;
db.all(`
SELECT p.permission_id, p.system_id, p.endpoint_id, p.created_at,
e.name as endpoint_name, e.gateway_path, e.api_type
FROM system_permissions p
JOIN api_endpoints e ON p.endpoint_id = e.endpoint_id
WHERE p.system_id = ?
`, [id], (err, rows) => {
if (err) return res.status(500).json({ error: err.message });
res.json(rows);
});
});
// Get all permissions (for overview)
app.get('/api/admin/permissions', (req, res) => {
db.all(`
SELECT p.permission_id, p.system_id, p.endpoint_id, p.created_at,
s.system_name, e.name as endpoint_name, e.gateway_path
FROM system_permissions p
JOIN systems s ON p.system_id = s.system_id
JOIN api_endpoints e ON p.endpoint_id = e.endpoint_id
ORDER BY s.system_name, e.name
`, (err, rows) => {
if (err) return res.status(500).json({ error: err.message });
res.json(rows);
});
});
// Grant permission to a system
app.post('/api/admin/permissions', (req, res) => {
const { system_id, endpoint_id } = req.body;
if (!system_id || !endpoint_id) {
return res.status(400).json({ error: 'system_id and endpoint_id are required' });
}
const permission_id = crypto.randomUUID();
db.run(`
INSERT INTO system_permissions (permission_id, system_id, endpoint_id)
VALUES (?, ?, ?)
`, [permission_id, system_id, endpoint_id], function (err) {
if (err) {
if (err.message.includes('UNIQUE')) {
return res.status(409).json({ error: 'Permission already exists' });
}
return res.status(500).json({ error: err.message });
}
res.json({
id: permission_id,
message: "Permission granted successfully"
});
});
});
// Revoke permission from a system
app.delete('/api/admin/permissions/:id', (req, res) => {
const { id } = req.params;
db.run("DELETE FROM system_permissions WHERE permission_id = ?", [id], function (err) {
if (err) return res.status(500).json({ error: err.message });
if (this.changes === 0) {
return res.status(404).json({ error: 'Permission not found' });
}
res.json({ message: "Permission revoked successfully" });
});
});
// Batch grant permissions to a system
app.post('/api/admin/systems/:id/permissions/batch', (req, res) => {
const { id } = req.params;
const { endpoint_ids } = req.body;
if (!Array.isArray(endpoint_ids)) {
return res.status(400).json({ error: 'endpoint_ids must be an array' });
}
// First, delete all existing permissions for this system
db.run("DELETE FROM system_permissions WHERE system_id = ?", [id], (err) => {
if (err) return res.status(500).json({ error: err.message });
// Then insert new permissions
if (endpoint_ids.length === 0) {
return res.json({ message: "All permissions revoked", granted: 0 });
}
const stmt = db.prepare(`
INSERT INTO system_permissions (permission_id, system_id, endpoint_id)
VALUES (?, ?, ?)
`);
let completed = 0;
let errors = [];
endpoint_ids.forEach(endpoint_id => {
const permission_id = crypto.randomUUID();
stmt.run([permission_id, id, endpoint_id], (err) => {
if (err) errors.push(err.message);
completed++;
if (completed === endpoint_ids.length) {
stmt.finalize();
if (errors.length > 0) {
return res.status(500).json({
message: "Some permissions failed to grant",
errors: errors,
granted: endpoint_ids.length - errors.length
});
}
res.json({
message: "Permissions updated successfully",
granted: endpoint_ids.length
});
}
});
});
});
});
// 6. Transformation Rules Management
app.get('/api/admin/transformations', (req, res) => {
db.all(`SELECT * FROM transformation_rules ORDER BY updated_at DESC`, (err, rows) => {
if (err) return res.status(500).json({ error: err.message });
res.json(rows.map(hydrateRuleRow));
});
});
app.post('/api/admin/transformations', (req, res) => {
const payload = normalizeRulePayload(req.body);
if (!payload.rule_name) {
return res.status(400).json({ error: 'rule_name is required' });
}
const ruleId = crypto.randomUUID();
const params = [
ruleId,
payload.endpoint_id || null,
payload.rule_name,
payload.description || null,
payload.source_format,
payload.target_format,
payload.transformation_type,
payload.direction || 'response',
payload.template_config || null,
payload.mapping_config || null,
payload.filter_config || '[]',
payload.pipeline_config || '[]',
payload.validation_config || null,
payload.validation_field_mappings || null,
payload.validation_schema_uri || null,
payload.validation_on_fail || 'reject',
payload.validation_strict_mode !== false ? 1 : 0,
payload.test_source_url || null,
payload.sample_input || null,
payload.expected_output || null,
payload.is_active ? 1 : 0
];
db.run(`
INSERT INTO transformation_rules (
rule_id, endpoint_id, rule_name, description,
source_format, target_format, transformation_type, direction,
template_config, mapping_config, filter_config, pipeline_config,
validation_config, validation_field_mappings, validation_schema_uri,
validation_on_fail, validation_strict_mode,
test_source_url, sample_input, expected_output, is_active
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`, params, function (err) {
if (err) return res.status(500).json({ error: err.message });
res.status(201).json(hydrateRuleRow({
rule_id: ruleId,
...payload
}));
});
});
app.put('/api/admin/transformations/:id', (req, res) => {
const { id } = req.params;
const payload = normalizeRulePayload(req.body);
db.run(`
UPDATE transformation_rules SET
endpoint_id = ?,
rule_name = ?,
description = ?,
source_format = ?,
target_format = ?,
transformation_type = ?,
direction = ?,
template_config = ?,
mapping_config = ?,
filter_config = ?,
pipeline_config = ?,
validation_config = ?,
validation_field_mappings = ?,
validation_schema_uri = ?,
validation_on_fail = ?,
validation_strict_mode = ?,
test_source_url = ?,
sample_input = ?,
expected_output = ?,
is_active = ?,
updated_at = CURRENT_TIMESTAMP
WHERE rule_id = ?
`, [
payload.endpoint_id || null,
payload.rule_name,
payload.description || null,
payload.source_format,
payload.target_format,
payload.transformation_type,
payload.direction || 'response',
payload.template_config || null,
payload.mapping_config || null,
payload.filter_config || '[]',
payload.pipeline_config || '[]',
payload.validation_config || null,
payload.validation_field_mappings || null,
payload.validation_schema_uri || null,
payload.validation_on_fail || 'reject',
payload.validation_strict_mode !== false ? 1 : 0,
payload.test_source_url || null,
payload.sample_input || null,
payload.expected_output || null,
payload.is_active ? 1 : 0,
id
], function (err) {
if (err) return res.status(500).json({ error: err.message });
if (this.changes === 0) return res.status(404).json({ error: 'Rule not found' });
getRuleById(id).then(rule => res.json(rule)).catch(e => res.status(500).json({ error: e.message }));
});
});
app.delete('/api/admin/transformations/:id', (req, res) => {
const { id } = req.params;
db.run(`DELETE FROM transformation_rules WHERE rule_id = ?`, [id], function (err) {
if (err) return res.status(500).json({ error: err.message });
if (this.changes === 0) return res.status(404).json({ error: 'Rule not found' });
res.json({ message: 'Rule deleted' });
});
});
app.post('/api/admin/transformations/preview', async (req, res) => {
try {
const { rule, rule_id, sample_input, test_source_url } = req.body;
let ruleToUse = rule ? normalizeRulePayload(rule, true) : null;
if (!ruleToUse && rule_id) {
ruleToUse = await getRuleById(rule_id);
}
if (!ruleToUse) {
return res.status(400).json({ error: 'No rule definition provided' });
}
const execution = await executeTransformation(ruleToUse, sample_input, test_source_url);
res.json(execution);
} catch (err) {
console.error('Preview failed:', err);
res.status(400).json({ error: err.message });
}
});
app.post('/api/admin/transformations/test', async (req, res) => {
try {
const { rule_id, sample_input } = req.body;
if (!rule_id) {
return res.status(400).json({ error: 'rule_id is required' });
}
const rule = await getRuleById(rule_id);
if (!rule) {
return res.status(404).json({ error: 'Rule not found' });
}
const execution = await executeTransformation(rule, sample_input);
res.json(execution);
} catch (err) {
console.error('Test run failed:', err);
res.status(400).json({ error: err.message });
}
});
app.get('/api/admin/transformations/fetch', async (req, res) => {
const { url } = req.query;
if (!url) {
return res.status(400).json({ error: 'url query parameter is required' });
}
try {
const response = await fetch(url);
const text = await response.text();
res.json({
status: response.status,
headers: {
'content-type': response.headers.get('content-type')
},
body: text
});