1
0

reverse-proxy.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Pure builders for reverse-proxy configs (Nginx / Caddy) and cert commands.
  2. export type ProxyServer = 'nginx' | 'caddy';
  3. export type CertTool = 'certbot' | 'acme.sh';
  4. export interface ReverseProxyOptions {
  5. server: ProxyServer;
  6. domain: string;
  7. panelPort: string;
  8. /** Web base path the panel is served under, e.g. `/panel`. */
  9. panelPath: string;
  10. certTool: CertTool;
  11. }
  12. function normalizePath(path: string): string {
  13. const p = path.trim();
  14. if (!p) return '/';
  15. return p.startsWith('/') ? p : `/${p}`;
  16. }
  17. export function buildProxyConfig(o: ReverseProxyOptions): string {
  18. return o.server === 'nginx' ? buildNginx(o) : buildCaddy(o);
  19. }
  20. function buildNginx(o: ReverseProxyOptions): string {
  21. const path = normalizePath(o.panelPath);
  22. const loc = path === '/' ? '/' : `${path.replace(/\/$/, '')}/`;
  23. return `server {
  24. listen 443 ssl http2;
  25. server_name ${o.domain};
  26. ssl_certificate /etc/letsencrypt/live/${o.domain}/fullchain.pem;
  27. ssl_certificate_key /etc/letsencrypt/live/${o.domain}/privkey.pem;
  28. location ${loc} {
  29. proxy_pass http://127.0.0.1:${o.panelPort};
  30. proxy_http_version 1.1;
  31. proxy_set_header Upgrade $http_upgrade;
  32. proxy_set_header Connection "upgrade";
  33. proxy_set_header Host $host;
  34. proxy_set_header X-Real-IP $remote_addr;
  35. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  36. proxy_set_header X-Forwarded-Proto $scheme;
  37. proxy_read_timeout 3600s;
  38. proxy_send_timeout 3600s;
  39. }
  40. }`;
  41. }
  42. function buildCaddy(o: ReverseProxyOptions): string {
  43. const path = normalizePath(o.panelPath);
  44. if (path === '/') {
  45. return `${o.domain} {
  46. reverse_proxy 127.0.0.1:${o.panelPort}
  47. }`;
  48. }
  49. const matcher = `${path.replace(/\/$/, '')}/*`;
  50. return `${o.domain} {
  51. reverse_proxy ${matcher} 127.0.0.1:${o.panelPort}
  52. }`;
  53. }
  54. export function buildCertCommand(o: ReverseProxyOptions): string {
  55. if (o.certTool === 'certbot') {
  56. return `certbot certonly --nginx -d ${o.domain}`;
  57. }
  58. return `acme.sh --issue -d ${o.domain} --nginx`;
  59. }