Files

167 lines
6.4 KiB
JavaScript

/** Production static server + fixed-upstream task proxy. No provider credentials in the browser. */
import http from 'node:http';
import { createPreviewHandler } from './pcb-preview.mjs';
import https from 'node:https';
import { readFile, stat } from 'node:fs/promises';
import { createReadStream } from 'node:fs';
import { resolve, extname, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
import { pipeline } from 'node:stream';
const root = resolve(fileURLToPath(new URL('../designer/dist/', import.meta.url)));
const deployment = JSON.parse(await readFile(resolve(root, 'pcb-service-config.json'), 'utf8'));
const siteBase = deployment.base;
if (typeof siteBase !== 'string' || !siteBase.startsWith('/') || !siteBase.endsWith('/'))
throw Error('Build base must be an absolute URL path ending in /');
const apiPrefix = `${siteBase}pcb-api/`;
const previewPrefix = `${siteBase}pcb-preview/`;
const preview = createPreviewHandler();
const target = new URL(process.env.PCB_API_TARGET || 'http://39.105.93.138:8003');
if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password)
throw Error('PCB_API_TARGET must be an HTTP(S) address without embedded credentials');
const platformTarget = new URL(process.env.API_TARGET || 'https://dev-vibemake-api.robotquan.com');
if (
!['http:', 'https:'].includes(platformTarget.protocol) ||
platformTarget.username ||
platformTarget.password
)
throw Error('API_TARGET must be an HTTP(S) address without embedded credentials');
const host = process.env.HOST || '127.0.0.1',
port = Number(process.env.PORT || 5180);
const mime = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.wasm': 'application/wasm',
'.webmanifest': 'application/manifest+json',
};
const handler = async (req, res) => {
try {
const url = new URL(req.url, 'http://localhost');
if (url.pathname.startsWith(previewPrefix)) {
const ownOrigin = process.env.PUBLIC_ORIGIN || `${process.env.TLS_CERT && process.env.TLS_KEY ? 'https' : 'http'}://${req.headers.host}`;
if (req.headers.origin && req.headers.origin !== ownOrigin) { res.writeHead(403); res.end(); return; }
await preview(req, res, url.pathname.slice(previewPrefix.length), url.searchParams);
return;
}
const pcbApi = url.pathname.startsWith(apiPrefix);
if (pcbApi || url.pathname === '/api' || url.pathname.startsWith('/api/')) {
const ownOrigin =
process.env.PUBLIC_ORIGIN ||
`${process.env.TLS_CERT && process.env.TLS_KEY ? 'https' : 'http'}://${req.headers.host}`;
if (
(req.headers.origin && req.headers.origin !== ownOrigin) ||
(!['GET', 'HEAD', 'OPTIONS'].includes(req.method) && req.headers.origin !== ownOrigin)
) {
res.writeHead(403, { 'content-type': 'application/json' });
res.end(JSON.stringify({ message: '请求来源不匹配' }));
return;
}
const upstreamTarget = pcbApi ? target : platformTarget;
const headers = {
...req.headers,
host: upstreamTarget.host,
};
if (pcbApi) headers.origin = process.env.PCB_API_ORIGIN || 'http://127.0.0.1:5173';
else {
delete headers.origin;
delete headers.referer;
}
const upstreamPath = pcbApi ? '/api/' + url.pathname.slice(apiPrefix.length) : url.pathname;
const upstream = (upstreamTarget.protocol === 'https:' ? https : http).request(
new URL(upstreamPath + url.search, upstreamTarget),
{ method: req.method, headers },
(reply) => {
res.writeHead(reply.statusCode || 502, {
...reply.headers,
'cache-control': 'no-store',
'x-accel-buffering': 'no',
});
pipeline(reply, res, () => {});
},
);
upstream.on('error', () => {
if (!res.headersSent) res.writeHead(502, { 'content-type': 'application/json' });
res.end(
JSON.stringify({
message: pcbApi
? '无法连接 PCB 后台,请检查 PCB_API_TARGET 和后台运行状态。'
: '无法连接平台后台,请检查 API_TARGET 和后台运行状态。',
}),
);
});
req.on('aborted', () => upstream.destroy());
res.on('close', () => upstream.destroy());
pipeline(req, upstream, () => {});
return;
}
if (!['GET', 'HEAD'].includes(req.method)) {
res.writeHead(405);
res.end();
return;
}
if (siteBase !== '/' && (url.pathname === '/' || url.pathname === siteBase.slice(0, -1))) {
res.writeHead(302, { location: siteBase + url.search });
res.end();
return;
}
if (!url.pathname.startsWith(siteBase)) {
res.writeHead(404);
res.end();
return;
}
let path = resolve(root, './' + decodeURIComponent(url.pathname.slice(siteBase.length)));
if (path !== root && !path.startsWith(root + sep)) {
res.writeHead(403);
res.end();
return;
}
try {
if ((await stat(path)).isDirectory()) path = resolve(path, 'index.html');
await stat(path);
} catch {
if (extname(url.pathname)) {
res.writeHead(404);
res.end();
return;
}
path = resolve(root, 'index.html');
}
res.writeHead(200, {
'content-type': mime[extname(path)] || 'application/octet-stream',
'cache-control': url.pathname.startsWith(`${siteBase}assets/`)
? 'public, max-age=31536000, immutable'
: 'no-cache',
'x-content-type-options': 'nosniff',
});
if (req.method === 'HEAD') {
res.end();
return;
}
pipeline(createReadStream(path), res, () => {});
} catch {
if (!res.headersSent) res.writeHead(500);
res.end('Request failed');
}
};
const server =
process.env.TLS_CERT && process.env.TLS_KEY
? https.createServer(
{ cert: await readFile(process.env.TLS_CERT), key: await readFile(process.env.TLS_KEY) },
handler,
)
: http.createServer(handler);
server.listen(port, host, () => {
console.log(
`VibeMake PCB: ${process.env.TLS_CERT ? 'https' : 'http'}://${host}:${port}${siteBase}`,
);
console.log(`PCB API: ${target.origin}`);
console.log(`Platform API: ${platformTarget.origin}`);
console.log(
'For a remote server, use SSH port forwarding and visit http://localhost:' + port + siteBase,
);
});