File size: 4,234 Bytes
72eebaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import http from 'node:http';
import {Client} from 'itdog-web-api';

const port = Number.parseInt(process.env.PORT || '7860', 10);

const client = new Client();

const sendJson = (res, statusCode, payload) => {
    const body = JSON.stringify(payload, null, 2);
    res.writeHead(statusCode, {
        'content-type': 'application/json; charset=utf-8',
        'access-control-allow-origin': '*',
        'access-control-allow-methods': 'GET,POST,OPTIONS',
        'access-control-allow-headers': 'content-type',
    });
    res.end(body);
};

const readJsonBody = (req) => new Promise((resolve, reject) => {
    let data = '';
    req.on('data', (chunk) => {
        data += chunk;
        if (data.length > 2 * 1024 * 1024) {
            reject(new Error('Request body too large'));
            req.destroy();
        }
    });
    req.on('end', () => {                                                          if (!data) {
            resolve({});
            return;
        }
        try {
            resolve(JSON.parse(data));
        } catch {
            reject(new Error('Invalid JSON body'));
        }
    });
    req.on('error', (err) => reject(err));
});                                                                                                                                                   const pickAPIResult = (result) => ({
    task_id: result.task_id,
    wss_url: result.wss_url,
    taskToken: result.taskToken,
});

const runWS = async (runner) => {
    const messages = [];
    const final = await runner((data) => {
        messages.push(data);
    });
    return {
        result: pickAPIResult(final.result),
        messages,
    };
};
                                                                           const routes = {
    'POST /ping': (body) => runWS((onMessage) => client.ping(body, onMessage)),
    'POST /pingv6': (body) => runWS((onMessage) => client.pingV6(body, onMessage)),
    'POST /tcping': (body) => runWS((onMessage) => client.tcping(body, onMessage)),
    'POST /tcpingv6': (body) => runWS((onMessage) => client.tcpingV6(body, onMessage)),
    'POST /http': (body) => runWS((onMessage) => client.http(body, onMessage)),
    'POST /httpv6': (body) => runWS((onMessage) => client.httpV6(body, onMessage)),
    'POST /httping': (body) => runWS((onMessage) => client.httping(body, onMessage)),
    'POST /httpingv6': (body) => runWS((onMessage) => client.httpingV6(body, onMessage)),
    'POST /traceroute': (body) => runWS((onMessage) => client.traceRoute(body, onMessage)),
    'POST /traceroutev6': (body) => runWS((onMessage) => client.traceRouteV6(body, onMessage)),
    'POST /dns': (body) => runWS((onMessage) => client.dns(body, onMessage)),
    'POST /batch-tcping': (body) => runWS((onMessage) => client.batchTCPing(body, onMessage)),
    'POST /generic': async (body) => {
        if (!body?.endpoint) {
            throw new Error('Missing "endpoint" in body');
        }
        const method = body.method || 'POST';
        const params = body.params || {};
        return runWS((onMessage) => client.generic(body.endpoint, method, params, onMessage));
    },
};

const server = http.createServer(async (req, res) => {
    if (!req.url || !req.method) {
        sendJson(res, 400, {error: 'Invalid request'});
        return;
    }

    if (req.method === 'OPTIONS') {
        sendJson(res, 204, {});
        return;
    }

    if (req.method === 'GET' && req.url === '/') {
        sendJson(res, 200, {
            ok: true,
            service: 'itdog-web-api',
            endpoints: Object.keys(routes).map((key) => key.replace('POST ', '')),
        });
        return;
    }

    const routeKey = `${req.method} ${req.url}`;
    const handler = routes[routeKey];
    if (!handler) {
        sendJson(res, 404, {error: 'Not found'});
        return;
    }

    try {
        const body = await readJsonBody(req);
        const data = await handler(body);
        sendJson(res, 200, data);
    } catch (error) {
        sendJson(res, 400, {error: error instanceof Error ? error.message : 'Unknown error'});
    }
});

server.listen(port, () => {                                                    console.log(`Server listening on http://0.0.0.0:${port}`);
});