-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
342 lines (307 loc) · 13 KB
/
server.js
File metadata and controls
342 lines (307 loc) · 13 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
/**
* Portainer Run — CORS proxy + Anthropic relay + session cache
*
* Responsibilities:
* 1. Serve HTTPS (443 by default) with self-signed or real certs
* 2. Redirect HTTP (80) → HTTPS
* 3. Proxy /portainer-api/* → Portainer (CORS bypass, user token passed through)
* 4. Proxy /ai/triage → Anthropic API (key stored server-side, never in browser)
* 5. File-backed session cache keyed by hashed PAT (/cache GET/POST/DELETE)
* Default path: /app/data/cache.json — mount /app/data as a volume to persist
* across container restarts, or set CACHE_DIR to an external path.
*
* .env config:
* PORTAINER_URL=https://portainer.example.com:9443 (required)
* ANTHROPIC_API_KEY=sk-ant-... (optional, enables AI triage)
* PORT=443 (optional, default 443)
* HTTP_PORT=80 (optional, default 80)
* SSL_CERT=/path/to/fullchain.pem (optional, uses self-signed if not set)
* SSL_KEY=/path/to/privkey.pem (optional, uses self-signed if not set)
* SSL_CERT_DIR=/certs (optional, dir for self-signed cert storage)
* CACHE_DIR=/app/data (optional, dir for cache.json)
*/
const http = require('http');
const https = require('https');
const fs = require('fs');
const path = require('path');
const url = require('url');
const cp = require('child_process');
const crypto = require('crypto');
// ── CONFIG ────────────────────────────────────────────────────────────────────
const envFile = path.join(__dirname, '.env');
if (fs.existsSync(envFile)) {
fs.readFileSync(envFile, 'utf8')
.split('\n')
.filter(l => l.trim() && !l.startsWith('#'))
.forEach(l => {
const [k, ...v] = l.split('=');
if (k && !process.env[k.trim()]) {
process.env[k.trim()] = v.join('=').trim().replace(/^["']|["']$/g, '');
}
});
}
const PORTAINER_URL = (process.env.PORTAINER_URL || '').replace(/\/$/, '');
const ANTHROPIC_KEY = process.env.ANTHROPIC_API_KEY || '';
const PORT = parseInt(process.env.PORT || '443');
const HTTP_PORT = parseInt(process.env.HTTP_PORT || '80');
const SSL_CERT_PATH = process.env.SSL_CERT || '';
const SSL_KEY_PATH = process.env.SSL_KEY || '';
const CERT_DIR = process.env.SSL_CERT_DIR || __dirname;
const CACHE_DIR = process.env.CACHE_DIR || path.join(__dirname, 'data');
const CACHE_FILE = path.join(CACHE_DIR, 'cache.json');
if (!PORTAINER_URL) {
console.error('\n❌ PORTAINER_URL must be set\n');
process.exit(1);
}
if (!ANTHROPIC_KEY) {
console.warn('\n⚠️ ANTHROPIC_API_KEY not set — AI triage will be unavailable\n');
}
try { new URL(PORTAINER_URL); } catch(_) {
console.error(`\n❌ Invalid PORTAINER_URL: "${PORTAINER_URL}"\n`);
process.exit(1);
}
const pOrigin = new URL(PORTAINER_URL);
const pIsHttps = pOrigin.protocol === 'https:';
const pHost = pOrigin.hostname;
const pPort = pOrigin.port ? parseInt(pOrigin.port) : (pIsHttps ? 443 : 80);
const CORS = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,POST,PUT,PATCH,DELETE,OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type,X-API-Key,Authorization',
};
// ── FILE-BACKED SESSION CACHE ─────────────────────────────────────────────────
// Keyed by SHA-256 hash of the user's PAT.
// Cleared on disconnect (DELETE /cache). Persists across container restarts
// if CACHE_DIR is mounted as an external volume.
if (!fs.existsSync(CACHE_DIR)) {
fs.mkdirSync(CACHE_DIR, { recursive: true });
}
function cacheKey(token) {
return crypto.createHash('sha256').update(token).digest('hex');
}
function readCacheFile() {
try {
if (fs.existsSync(CACHE_FILE)) {
return JSON.parse(fs.readFileSync(CACHE_FILE, 'utf8'));
}
} catch(_) {}
return {};
}
function writeCacheFile(data) {
try {
fs.writeFileSync(CACHE_FILE, JSON.stringify(data), 'utf8');
} catch(e) {
console.warn('[cache] write failed:', e.message);
}
}
function handleCache(req, res) {
const token = req.headers['x-api-key'] || '';
if (!token) {
res.writeHead(401, { 'Content-Type': 'application/json', ...CORS });
res.end(JSON.stringify({ error: 'X-API-Key header required' }));
return;
}
const key = cacheKey(token);
if (req.method === 'GET') {
const all = readCacheFile();
const entry = all[key] || null;
res.writeHead(200, { 'Content-Type': 'application/json', ...CORS });
res.end(JSON.stringify(entry));
return;
}
if (req.method === 'POST') {
readBody(req).then(body => {
try {
const data = JSON.parse(body.toString());
const all = readCacheFile();
all[key] = { ...data, savedAt: Date.now() };
writeCacheFile(all);
res.writeHead(200, { 'Content-Type': 'application/json', ...CORS });
res.end(JSON.stringify({ ok: true }));
} catch(_) {
res.writeHead(400, { 'Content-Type': 'application/json', ...CORS });
res.end(JSON.stringify({ error: 'Invalid JSON' }));
}
});
return;
}
if (req.method === 'DELETE') {
const all = readCacheFile();
delete all[key];
writeCacheFile(all);
res.writeHead(200, { 'Content-Type': 'application/json', ...CORS });
res.end(JSON.stringify({ ok: true }));
return;
}
res.writeHead(405, CORS);
res.end();
}
// ── TLS CERT SETUP ────────────────────────────────────────────────────────────
function ensureSelfSignedCert(certFile, keyFile) {
if (fs.existsSync(certFile) && fs.existsSync(keyFile)) return;
console.log('🔐 Generating self-signed certificate (3 year validity)...');
try {
cp.execSync(
`openssl req -x509 -newkey rsa:2048 -nodes` +
` -keyout "${keyFile}"` +
` -out "${certFile}"` +
` -days 1095` +
` -subj "/CN=portainer-run"` +
` -addext "subjectAltName=IP:127.0.0.1,DNS:localhost"`,
{ stdio: 'pipe' }
);
console.log('✅ Self-signed certificate generated');
} catch(e) {
console.error('❌ Failed to generate self-signed cert:', e.message);
process.exit(1);
}
}
function loadTlsOptions() {
if (SSL_CERT_PATH && SSL_KEY_PATH) {
if (!fs.existsSync(SSL_CERT_PATH)) { console.error(`\n❌ SSL_CERT not found: ${SSL_CERT_PATH}\n`); process.exit(1); }
if (!fs.existsSync(SSL_KEY_PATH)) { console.error(`\n❌ SSL_KEY not found: ${SSL_KEY_PATH}\n`); process.exit(1); }
console.log('🔐 Using provided TLS certificates');
return { cert: fs.readFileSync(SSL_CERT_PATH), key: fs.readFileSync(SSL_KEY_PATH) };
}
const certFile = path.join(CERT_DIR, 'portainer-run.crt');
const keyFile = path.join(CERT_DIR, 'portainer-run.key');
ensureSelfSignedCert(certFile, keyFile);
return { cert: fs.readFileSync(certFile), key: fs.readFileSync(keyFile) };
}
// ── HELPERS ───────────────────────────────────────────────────────────────────
function readBody(req) {
return new Promise((resolve, reject) => {
const chunks = [];
req.on('data', c => chunks.push(c));
req.on('end', () => resolve(chunks.length ? Buffer.concat(chunks) : null));
req.on('error', reject);
});
}
function proxyToPortainer(req, res, upstreamPath, body) {
const userToken = req.headers['x-api-key'] || '';
const headers = {
'Content-Type': req.headers['content-type'] || 'application/json',
'Accept': 'application/json',
};
if (userToken) headers['X-API-Key'] = userToken;
if (body && body.length) headers['Content-Length'] = body.length;
const opts = {
hostname: pHost, port: pPort, path: upstreamPath,
method: req.method, headers, rejectUnauthorized: false,
};
const transport = pIsHttps ? https : http;
const upstream = transport.request(opts, upRes => {
const resHeaders = { ...CORS, 'Content-Type': upRes.headers['content-type'] || 'application/json' };
if (upRes.headers['content-encoding']) resHeaders['Content-Encoding'] = upRes.headers['content-encoding'];
res.writeHead(upRes.statusCode, resHeaders);
upRes.pipe(res);
});
upstream.on('error', e => {
console.error('[portainer proxy error]', e.message);
res.writeHead(502, { 'Content-Type': 'application/json', ...CORS });
res.end(JSON.stringify({ error: 'Proxy error', message: e.message }));
});
if (body && body.length) upstream.write(body);
upstream.end();
}
function proxyToAnthropic(req, res, body) {
if (!ANTHROPIC_KEY) {
res.writeHead(503, { 'Content-Type': 'application/json', ...CORS });
res.end(JSON.stringify({ error: 'ANTHROPIC_API_KEY not configured on server' }));
return;
}
let payload;
try { payload = JSON.parse(body.toString()); } catch(_) {
res.writeHead(400, { 'Content-Type': 'application/json', ...CORS });
res.end(JSON.stringify({ error: 'Invalid JSON body' }));
return;
}
const outBody = Buffer.from(JSON.stringify(payload));
const headers = {
'Content-Type': 'application/json', 'x-api-key': ANTHROPIC_KEY,
'anthropic-version': '2023-06-01', 'Content-Length': outBody.length,
};
const upstream = https.request(
{ hostname: 'api.anthropic.com', port: 443, path: '/v1/messages', method: 'POST', headers },
upRes => {
res.writeHead(upRes.statusCode, {
...CORS,
'Content-Type': upRes.headers['content-type'] || 'text/event-stream',
'Cache-Control': 'no-cache',
});
upRes.pipe(res);
}
);
upstream.on('error', e => {
console.error('[anthropic proxy error]', e.message);
if (!res.headersSent) {
res.writeHead(502, { 'Content-Type': 'application/json', ...CORS });
res.end(JSON.stringify({ error: e.message }));
}
});
upstream.write(outBody);
upstream.end();
}
// ── REQUEST HANDLER ───────────────────────────────────────────────────────────
async function handleRequest(req, res) {
const parsed = url.parse(req.url);
const pathname = parsed.pathname;
if (req.method === 'OPTIONS') { res.writeHead(204, CORS); res.end(); return; }
if (pathname === '/config') {
res.writeHead(200, { 'Content-Type': 'application/json', ...CORS });
res.end(JSON.stringify({ portainerUrl: PORTAINER_URL, aiAvailable: !!ANTHROPIC_KEY }));
return;
}
// Session cache endpoints
if (pathname === '/cache') {
handleCache(req, res);
return;
}
if (pathname.startsWith('/portainer-api/')) {
const body = await readBody(req);
const upstreamPath = '/api/' + pathname.slice('/portainer-api/'.length) + (parsed.search || '');
proxyToPortainer(req, res, upstreamPath, body);
return;
}
if (pathname === '/ai/triage') {
const body = await readBody(req);
proxyToAnthropic(req, res, body);
return;
}
if (pathname === '/' || pathname === '/index.html') {
const htmlPath = path.join(__dirname, 'portainer-run.html');
if (!fs.existsSync(htmlPath)) { res.writeHead(404); res.end('portainer-run.html not found'); return; }
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
fs.createReadStream(htmlPath).pipe(res);
return;
}
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not found');
}
// ── START SERVERS ─────────────────────────────────────────────────────────────
const tlsOptions = loadTlsOptions();
const httpsServer = https.createServer(tlsOptions, handleRequest);
httpsServer.listen(PORT, () => {
console.log('\n✅ Portainer Run started');
console.log(` UI: https://localhost${PORT !== 443 ? ':' + PORT : ''}`);
console.log(` Portainer: ${PORTAINER_URL}`);
console.log(` AI triage: ${ANTHROPIC_KEY ? '✓ configured' : '✗ not set'}`);
console.log(` TLS: ${SSL_CERT_PATH ? 'provided certs' : 'self-signed (portainer-run.crt)'}`);
console.log(` Cache: ${CACHE_FILE}`);
console.log(` HTTP ${HTTP_PORT} → redirecting to HTTPS\n`);
});
httpsServer.on('error', e => {
if (e.code === 'EADDRINUSE') console.error(`\n❌ Port ${PORT} already in use\n`);
else console.error('\n❌ ', e.message, '\n');
process.exit(1);
});
const httpServer = http.createServer((req, res) => {
const host = (req.headers.host || 'localhost').replace(/:\d+$/, '');
const target = `https://${host}${PORT !== 443 ? ':' + PORT : ''}${req.url}`;
res.writeHead(301, { Location: target });
res.end();
});
httpServer.listen(HTTP_PORT);
httpServer.on('error', e => {
console.warn(`⚠️ HTTP redirect on port ${HTTP_PORT} unavailable: ${e.message}`);
});