path:
/dev-server.mjs
6.18 KB | plain
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
#!/usr/bin/env node
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { extname, join, normalize } from 'node:path';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
const execFileAsync = promisify(execFile);
const root = process.cwd();
const port = Number(process.env.PORT || 8088);
const host = process.env.HOST || '127.0.0.1';
const remoteHost = process.env.DEV_REMOTE_HOST || 'maa-1';
const deviceOrigin = process.env.DEV_DEVICE_ORIGIN;
const contentTypes = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon'
};
function send(res, status, body, headers = {}) {
res.writeHead(status, headers);
res.end(body);
}
function safeStaticPath(pathname) {
const requested = pathname === '/' ? '/index.html' : pathname;
const clean = normalize(decodeURIComponent(requested)).replace(/^\.\.(\/|\\|$)/, '');
return join(root, clean);
}
function shellQuote(value) {
return `'${String(value).replace(/'/g, `'\\''`)}'`;
}
async function proxyDevice(res, pathname) {
const headers = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' };
if (!deviceOrigin) {
send(res, 503, JSON.stringify({ error: 'Set DEV_DEVICE_ORIGIN to a local device API fixture or authorized proxy' }), headers);
return;
}
try {
const response = await fetch(new URL(pathname, deviceOrigin), {
redirect: 'manual', signal: AbortSignal.timeout(5000)
});
send(res, response.status, Buffer.from(await response.arrayBuffer()), headers);
} catch (error) {
console.warn('[dev-server] device lookup failed:', error.message);
send(res, 502, JSON.stringify({ error: 'Device lookup failed' }), headers);
}
}
const fastcgiProxyScript = String.raw`
import glob, socket, struct, sys
query = sys.argv[1]
sockets = sorted(glob.glob('/run/lighttpd/http.socket-*'))
if not sockets:
raise SystemExit('No kidang FastCGI socket found')
def rec(record_type, request_id, content=b''):
padding = (-len(content)) % 8
return struct.pack('!BBHHBB', 1, record_type, request_id, len(content), padding, 0) + content + (b'\0' * padding)
def enc_len(length):
return bytes([length]) if length < 128 else struct.pack('!I', length | 0x80000000)
def param(name, value):
name = name.encode()
value = value.encode()
return enc_len(len(name)) + enc_len(len(value)) + name + value
request_id = 1
params = {
'GATEWAY_INTERFACE': 'CGI/1.1',
'REQUEST_METHOD': 'GET',
'SCRIPT_NAME': '/kidang.fcgi',
'SCRIPT_FILENAME': '/home/bharat/kidang/kidang.fcgi',
'QUERY_STRING': query,
'SERVER_SOFTWARE': 'logs-dev-server',
'SERVER_PROTOCOL': 'HTTP/1.1',
'CONTENT_LENGTH': '0',
'DOCUMENT_ROOT': '/srv/www/logs.saikrupagas.com',
'REMOTE_ADDR': '127.0.0.1',
'SERVER_NAME': 'logs.saikrupagas.com',
'SERVER_PORT': '443',
'HTTPS': 'on',
}
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(sockets[-1])
sock.sendall(rec(1, request_id, struct.pack('!HB5s', 1, 0, b'')))
sock.sendall(rec(4, request_id, b''.join(param(k, v) for k, v in params.items())))
sock.sendall(rec(4, request_id, b''))
sock.sendall(rec(5, request_id, b''))
stdout = b''
stderr = b''
while True:
header = sock.recv(8)
if not header:
break
_version, record_type, _rid, content_length, padding_length, _reserved = struct.unpack('!BBHHBB', header)
content = b''
while len(content) < content_length:
content += sock.recv(content_length - len(content))
if padding_length:
sock.recv(padding_length)
if record_type == 6:
stdout += content
elif record_type == 7:
stderr += content
elif record_type == 3:
break
if stderr:
print(stderr.decode('utf-8', 'replace'), file=sys.stderr)
separator = b'\r\n\r\n' if b'\r\n\r\n' in stdout else b'\n\n'
body = stdout.split(separator, 1)[1] if separator in stdout else stdout
sys.stdout.buffer.write(body)
`;
async function proxyRemoteKidang(res, query) {
try {
const remoteCommand = ['python3', '-c', shellQuote(fastcgiProxyScript), shellQuote(query)].join(' ');
const { stdout, stderr } = await execFileAsync('ssh', [remoteHost, remoteCommand], { maxBuffer: 20 * 1024 * 1024 });
if (stderr) console.warn(`[dev-server] remote kidang stderr: ${stderr.trim()}`);
send(res, 200, stdout, {
'Content-Type': 'text/plain; charset=utf-8',
'Cache-Control': 'no-store'
});
} catch (error) {
console.error('[dev-server] remote kidang failed:', error.message);
send(res, 502, JSON.stringify({ error: 'Remote kidang failed', detail: error.message }), {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store'
});
}
}
createServer(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
if (url.pathname === '/api/devices' || url.pathname.startsWith('/api/devices/')) {
if (req.method !== 'GET' || url.search || !/^\/api\/devices\/[A-Za-z0-9_-][A-Za-z0-9_.-]*$/.test(url.pathname)) {
send(res, 403, 'Forbidden\n');
return;
}
await proxyDevice(res, url.pathname);
return;
}
if (url.pathname === '/logs.php' || url.pathname.startsWith('/deploy/') || url.pathname.startsWith('/.')) {
send(res, 403, 'Forbidden\n');
return;
}
if (url.pathname === '/kidang.fcgi') {
await proxyRemoteKidang(res, url.searchParams.toString());
return;
}
try {
const filePath = safeStaticPath(url.pathname);
const body = await readFile(filePath);
send(res, 200, body, {
'Content-Type': contentTypes[extname(filePath).toLowerCase()] || 'application/octet-stream',
'Cache-Control': 'no-store'
});
} catch (error) {
send(res, 404, 'Not found\n', { 'Content-Type': 'text/plain; charset=utf-8' });
}
}).listen(port, host, () => {
console.log(`Local dev server: http://${host}:${port}`);
console.log(`Device API: ${deviceOrigin || 'disabled (set DEV_DEVICE_ORIGIN)'}; kidang via ${remoteHost}`);
});