2026-06-03 11:37:55 +08:00

132 lines
3.1 KiB
JavaScript

import http from 'node:http';
const moduleId = 'intranet-penetration-core';
const port = Number.parseInt(process.env.PORT || '8787', 10);
const provider = (process.env.TUNNEL_PROVIDER || '').trim();
const capabilities = ['intranetPenetration'];
const allowedActions = new Set([
'intranetPenetration:status',
'intranetPenetration:start',
'intranetPenetration:stop',
'intranetPenetration:read',
]);
function sendJson(res, statusCode, payload) {
const body = JSON.stringify(payload);
res.writeHead(statusCode, {
'Content-Type': 'application/json; charset=utf-8',
'Content-Length': Buffer.byteLength(body),
});
res.end(body);
}
function readJsonBody(req) {
return new Promise((resolve, reject) => {
let body = '';
req.on('data', (chunk) => {
body += chunk;
if (body.length > 1024 * 1024) {
req.destroy();
reject(new Error('request_body_too_large'));
}
});
req.on('end', () => {
if (!body.trim()) {
resolve({});
return;
}
try {
resolve(JSON.parse(body));
} catch {
reject(new Error('invalid_json'));
}
});
req.on('error', reject);
});
}
function providerNotConfigured(res, action) {
sendJson(res, 501, {
moduleId,
status: 'provider_not_configured',
action,
error: '内网穿透模块已加载,但尚未配置真实穿透提供商',
});
}
function sendAuthorization(res, action) {
const allowed = typeof action === 'string' && allowedActions.has(action);
sendJson(res, allowed ? 200 : 403, {
moduleId,
allowed,
action,
capabilities,
});
}
const server = http.createServer((req, res) => {
const url = new URL(req.url || '/', `http://${req.headers.host || '127.0.0.1'}`);
if (req.method === 'GET' && url.pathname === '/health') {
sendJson(res, 200, { moduleId, status: 'healthy' });
return;
}
if (req.method === 'GET' && url.pathname === '/status') {
if (!provider) {
providerNotConfigured(res, 'status');
return;
}
providerNotConfigured(res, 'status');
return;
}
if (req.method === 'GET' && url.pathname === '/capabilities') {
sendJson(res, 200, {
moduleId,
capabilities,
actions: Array.from(allowedActions),
});
return;
}
if (req.method === 'POST' && url.pathname === '/start') {
if (!provider) {
providerNotConfigured(res, 'start');
return;
}
providerNotConfigured(res, 'start');
return;
}
if (req.method === 'POST' && url.pathname === '/stop') {
if (!provider) {
providerNotConfigured(res, 'stop');
return;
}
providerNotConfigured(res, 'stop');
return;
}
if (req.method === 'POST' && url.pathname === '/authorize') {
readJsonBody(req)
.then((body) => {
sendAuthorization(res, body.action);
})
.catch((error) => {
sendJson(res, 400, { moduleId, allowed: false, error: error.message });
});
return;
}
sendJson(res, 404, { moduleId, error: '接口不存在' });
});
server.listen(port, '0.0.0.0', () => {
console.log(`${moduleId} listening on ${port}`);
});