-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcustom-server.ts
More file actions
246 lines (223 loc) · 8.54 KB
/
custom-server.ts
File metadata and controls
246 lines (223 loc) · 8.54 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
/**
* DBackup Custom Server - HTTPS by default, HTTP optional.
*
* This file replaces the Next.js standalone server.js as the Docker entry point.
* It creates an HTTPS server (with auto-generated self-signed cert if needed)
* and delegates request handling to the Next.js application.
*
* Environment variables:
* DISABLE_HTTPS - "true" to use plain HTTP (default: false - HTTPS)
* PORT - Listen port (default: 3000)
* HOSTNAME - Bind address (default: "0.0.0.0")
* CERTS_DIR - Directory for tls.crt/tls.key (default: "/data/certs")
*/
import { createServer as createHttpsServer } from "node:https";
import { createServer as createHttpServer, type Server } from "node:http";
import { execSync } from "node:child_process";
import path from "node:path";
import fs from "node:fs";
import type { IncomingMessage, ServerResponse } from "node:http";
import next from "next";
// ── Configuration ──────────────────────────────────────────────
(process.env as Record<string, string | undefined>).NODE_ENV = "production";
process.chdir(__dirname);
const port = parseInt(process.env.PORT || "3000", 10);
const hostname = process.env.HOSTNAME || "0.0.0.0";
const disableHttps = process.env.DISABLE_HTTPS === "true";
const certsDir = process.env.CERTS_DIR || "/data/certs";
const certPath = path.join(certsDir, "tls.crt");
const keyPath = path.join(certsDir, "tls.key");
// ── Next.js Setup ────────────────────────────────────────────
// Set standalone config env BEFORE importing next (matches generated server.js)
const nextConfig = JSON.parse(
fs.readFileSync(path.join(__dirname, ".next/required-server-files.json"), "utf8")
).config;
process.env.__NEXT_PRIVATE_STANDALONE_CONFIG = JSON.stringify(nextConfig);
const app = next({ dev: false, hostname, port, dir: __dirname, conf: nextConfig });
const handler = app.getRequestHandler();
// ── TLS Certificate Management ────────────────────────────────
function isSelfSigned(): boolean {
try {
const info = execSync(`openssl x509 -in "${certPath}" -noout -issuer -subject`, {
encoding: "utf8",
stdio: ["pipe", "pipe", "pipe"],
timeout: 5000,
});
const issuer = info.match(/issuer\s*=\s*(.*)/i)?.[1]?.trim() || "";
const subject = info.match(/subject\s*=\s*(.*)/i)?.[1]?.trim() || "";
return issuer === subject;
} catch {
return false;
}
}
function isExpired(): boolean {
try {
execSync(`openssl x509 -in "${certPath}" -noout -checkend 0`, {
stdio: "pipe",
timeout: 5000,
});
return false; // checkend 0 exits 0 if NOT expired
} catch {
return true; // exits 1 if expired
}
}
/**
* Extracts additional SAN entries from BETTER_AUTH_URL.
* Returns a comma-prefixed string like ",DNS:myhost.example.com" or ",IP:192.168.1.1",
* or an empty string if no extra SAN is needed.
*/
function getExtraSansFromAuthUrl(): string {
const authUrl = process.env.BETTER_AUTH_URL || "";
if (!authUrl) return "";
try {
const hostname = new URL(authUrl).hostname;
if (!hostname || hostname === "localhost" || hostname === "127.0.0.1") return "";
const isIp = /^\d{1,3}(\.\d{1,3}){3}$/.test(hostname);
return isIp ? `,IP:${hostname}` : `,DNS:${hostname}`;
} catch {
return "";
}
}
function generateSelfSignedCert(): void {
const extraSans = getExtraSansFromAuthUrl();
execSync(
`openssl req -x509 -newkey rsa:2048 -keyout "${keyPath}" -out "${certPath}" ` +
`-days 365 -nodes -subj "/CN=DBackup/O=DBackup Self-Signed" ` +
`-addext "subjectAltName=DNS:localhost,IP:127.0.0.1${extraSans}"`,
{ stdio: "pipe", timeout: 30000 }
);
execSync(`chmod 600 "${keyPath}"`, { stdio: "pipe" });
execSync(`chmod 644 "${certPath}"`, { stdio: "pipe" });
}
/**
* Checks whether the existing self-signed cert covers the hostname from BETTER_AUTH_URL.
* Returns true if the cert needs to be regenerated.
*/
function selfSignedCertMissesHostname(): boolean {
const authUrl = process.env.BETTER_AUTH_URL || "";
if (!authUrl) return false;
let hostname: string;
try {
hostname = new URL(authUrl).hostname;
} catch {
return false;
}
if (!hostname || hostname === "localhost" || hostname === "127.0.0.1") return false;
try {
const sans = execSync(
`openssl x509 -in "${certPath}" -noout -ext subjectAltName`,
{ encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], timeout: 5000 }
);
return !sans.includes(hostname);
} catch {
return false;
}
}
function ensureCertificate(): boolean {
if (!fs.existsSync(certsDir)) {
fs.mkdirSync(certsDir, { recursive: true, mode: 0o700 });
}
if (fs.existsSync(certPath) && fs.existsSync(keyPath)) {
// Check if existing cert is expired
if (isExpired()) {
if (isSelfSigned()) {
console.log("[TLS] Self-signed certificate expired - regenerating...");
try {
generateSelfSignedCert();
console.log("[TLS] Self-signed certificate renewed successfully");
return true;
} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err);
console.error("[TLS] Failed to renew certificate:", message);
return false;
}
} else {
console.warn(
"[TLS] WARNING: Custom certificate has expired! " +
"Upload a new certificate via Settings - Certificate or replace files in the configured CERTS_DIR"
);
}
} else if (isSelfSigned() && selfSignedCertMissesHostname()) {
console.log(
"[TLS] Self-signed certificate does not cover the configured hostname - regenerating..."
);
try {
generateSelfSignedCert();
console.log("[TLS] Self-signed certificate regenerated with updated hostname");
return true;
} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err);
console.error("[TLS] Failed to regenerate certificate:", message);
return false;
}
} else {
console.log("[TLS] Using existing certificate from configured CERTS_DIR");
}
return true;
}
console.log("[TLS] No certificate found. Generating self-signed certificate...");
try {
generateSelfSignedCert();
console.log("[TLS] Self-signed certificate generated successfully");
return true;
} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err);
console.error("[TLS] Failed to generate certificate:", message);
console.error(
"[TLS] Falling back to HTTP. Install openssl or provide custom certificates."
);
return false;
}
}
// ── Server Start ──────────────────────────────────────────────
app.prepare().then(() => {
let server: Server;
let protocol: string;
const requestHandler = async (req: IncomingMessage, res: ServerResponse) => {
try {
await handler(req, res);
} catch (err) {
console.error("[Server] Request error:", err);
res.statusCode = 500;
res.end("Internal Server Error");
}
};
if (disableHttps) {
protocol = "http";
server = createHttpServer(requestHandler);
console.log("[Server] HTTPS disabled via DISABLE_HTTPS=true - using HTTP");
} else {
const certReady = ensureCertificate();
if (certReady && fs.existsSync(certPath) && fs.existsSync(keyPath)) {
protocol = "https";
const tlsOptions = {
cert: fs.readFileSync(certPath),
key: fs.readFileSync(keyPath),
};
server = createHttpsServer(tlsOptions, requestHandler);
console.log("[Server] HTTPS enabled with certificate from configured CERTS_DIR");
} else {
protocol = "http";
server = createHttpServer(requestHandler);
console.warn(
"[Server] WARNING: Falling back to HTTP - certificate generation failed"
);
}
}
server.listen(port, hostname, () => {
console.log(
`[Server] DBackup ready on ${protocol}://${hostname}:${port}`
);
});
// Graceful shutdown
const shutdown = (signal: string) => {
console.log(`[Server] ${signal} received - shutting down...`);
server.close(() => {
console.log("[Server] Closed");
process.exit(0);
});
setTimeout(() => process.exit(1), 10000);
};
process.on("SIGTERM", () => shutdown("SIGTERM"));
process.on("SIGINT", () => shutdown("SIGINT"));
});