LandveX Gateway v0.1.0 + Operations API + Communications Module — ALL RUNNING

This commit is contained in:
Bernt
2026-07-02 18:33:25 +00:00
parent 4f7152316c
commit 8dcca96185
20 changed files with 1754 additions and 81 deletions
+122 -81
View File
@@ -1,95 +1,136 @@
/**
* LandveX Master Gateway
*
*
* Unifies all backend services:
* - Intelligence Lab (port 3002)
* - Apollo CRM (/api/apollo)
* - Stripe billing
* - aamos-ledger (port 3250)
* - aamos-incidents (port 3303)
* - Auth & API keys
* - Operations API (port 3005)
* - Communications (port 3010)
* - Apollo CRM (port 3001)
* - AAMOS Ledger (port 3250)
* - AAMOS Incidents (port 3303)
*/
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import rateLimit from 'express-rate-limit';
import { createProxyMiddleware } from 'http-proxy-middleware';
import dotenv from 'dotenv';
import http from 'http';
import { GATEWAY_CONFIG, SERVICES } from './config';
import { requireAuth, requireRole, verifyApiKey } from './auth';
import { proxyRequest, checkServiceHealth } from './proxy';
dotenv.config();
// Service health status
const serviceHealth: Record<string, { healthy: boolean; latency: number; lastCheck: number; error?: string }> = {};
const app = express();
const PORT = process.env.PORT || 3004;
// Rate limiting (simple in-memory)
const rateLimits: Record<string, { count: number; resetAt: number }> = {};
// Middleware
app.use(helmet());
app.use(cors());
app.use(express.json());
function checkRateLimit(identifier: string, maxRequests: number): boolean {
const now = Date.now();
const windowStart = Math.floor(now / GATEWAY_CONFIG.rateLimitWindow) * GATEWAY_CONFIG.rateLimitWindow;
if (!rateLimits[identifier] || rateLimits[identifier].resetAt < windowStart) {
rateLimits[identifier] = { count: 0, resetAt: windowStart + GATEWAY_CONFIG.rateLimitWindow };
}
rateLimits[identifier].count++;
return rateLimits[identifier].count <= maxRequests;
}
// Rate limiting
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
});
app.use(limiter);
// CORS headers
function setCorsHeaders(res: http.ServerResponse): void {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-API-Key');
}
// Health check
app.get('/health', (_req, res) => {
res.json({
status: 'ok',
version: '0.1.0-master',
services: {
intelligence: 'http://localhost:3002',
apollo: '/api/apollo',
ledger: 'http://localhost:3250',
incidents: 'http://localhost:3303',
// Main server
const server = http.createServer(async (req, res) => {
setCorsHeaders(res);
if (req.method === 'OPTIONS') {
res.statusCode = 204;
res.end();
return;
}
const url = req.url || '/';
// Health check
if (url === '/health') {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({
status: 'ok',
version: '0.1.0-gateway',
environment: GATEWAY_CONFIG.env,
services: Object.entries(serviceHealth).map(([name, health]) => ({
name,
healthy: health.healthy,
latency: health.latency,
lastCheck: health.lastCheck,
error: health.error,
})),
}));
return;
}
// API Key auth for external API access
const apiKey = req.headers['x-api-key'] as string;
if (apiKey) {
const keyInfo = verifyApiKey(apiKey);
if (!keyInfo.valid) {
res.statusCode = 401;
res.end(JSON.stringify({ error: 'Invalid API key' }));
return;
}
if (!checkRateLimit(apiKey, keyInfo.rateLimit || 100)) {
res.statusCode = 429;
res.end(JSON.stringify({ error: 'Rate limit exceeded' }));
return;
}
}
// Route to services
if (url.startsWith('/api/v1/government') || url.startsWith('/api/v1/customers')) {
proxyRequest(req, res, SERVICES.operations);
return;
} else if (url.startsWith('/api/v1/communications')) {
proxyRequest(req, res, SERVICES.communications);
return;
} else if (url.startsWith('/api/v1/missions') || url.startsWith('/api/v1/artifacts')) {
proxyRequest(req, res, SERVICES.intelligence);
return;
} else if (url.startsWith('/api/apollo')) {
proxyRequest(req, res, SERVICES.apollo);
} else if (url.startsWith('/api/ledger')) {
proxyRequest(req, res, SERVICES.ledger);
} else if (url.startsWith('/api/incidents')) {
proxyRequest(req, res, SERVICES.incidents);
} else if (url === '/webhooks/stripe') {
// Stripe webhook — handle directly or proxy to billing
res.statusCode = 200;
res.end(JSON.stringify({ received: true }));
} else {
res.statusCode = 404;
res.end(JSON.stringify({ error: 'Not Found', path: url }));
}
});
// Health check loop
async function updateHealth() {
for (const [name, service] of Object.entries(SERVICES)) {
const health = await checkServiceHealth(service);
serviceHealth[name] = {
...health,
lastCheck: Date.now(),
};
}
}
// Initial health check
updateHealth();
setInterval(updateHealth, 30000); // Every 30 seconds
server.listen(GATEWAY_CONFIG.port, () => {
console.log(`🚀 LandveX Gateway running on port ${GATEWAY_CONFIG.port}`);
console.log(`📡 Services:`);
Object.entries(SERVICES).forEach(([key, service]) => {
console.log(` - ${service.name}: http://${service.host}:${service.port}`);
});
});
// Proxy to Intelligence Lab
app.use('/api/v1', createProxyMiddleware({
target: 'http://localhost:3002',
changeOrigin: true,
pathRewrite: { '^/api/v1': '/api/v1' },
}));
// Proxy to Apollo CRM
app.use('/api/apollo', createProxyMiddleware({
target: 'http://localhost:3001',
changeOrigin: true,
pathRewrite: { '^/api/apollo': '/api/apollo' },
}));
// Proxy to Ledger
app.use('/api/ledger', createProxyMiddleware({
target: 'http://localhost:3250',
changeOrigin: true,
pathRewrite: { '^/api/ledger': '' },
}));
// Proxy to Incidents
app.use('/api/incidents', createProxyMiddleware({
target: 'http://localhost:3303',
changeOrigin: true,
pathRewrite: { '^/api/incidents': '' },
}));
// Stripe webhook
app.post('/webhooks/stripe', express.raw({ type: 'application/json' }), (req, res) => {
// TODO: Implement Stripe webhook handling
res.json({ received: true });
});
// Start server
app.listen(PORT, () => {
console.log(`🚀 LandveX Master Gateway running on port ${PORT}`);
console.log(`📡 Proxying to:`);
console.log(` - Intelligence Lab: http://localhost:3002`);
console.log(` - Apollo CRM: http://localhost:3001`);
console.log(` - Ledger: http://localhost:3250`);
console.log(` - Incidents: http://localhost:3303`);
});
export default app;