chore: 完善生产发布与部署校验

This commit is contained in:
que01 committed 2026-10-13 09:19:57 +08:00
1 parent 048c42207c
commit 5c6ad02f46
18 files changed
+1013 -47

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
const path = require("node:path");
const root = process.env.DEPLOY_ROOT;
if (!root || !path.isAbsolute(root)) throw new Error("DEPLOY_ROOT must be absolute");
module.exports = {
apps: [
{
name: "personal-brand-api",
cwd: path.join(root, "current/apps/api"),
script: "dist/main.js",
interpreter: process.execPath,
node_args: ["--env-file=" + path.join(root, "shared/.env.production")],
env: { NODE_ENV: "production" },
autorestart: true,
restart_delay: 2000,
max_restarts: 10,
time: true,
},
{
name: "personal-brand-admin-static",
cwd: path.join(root, "current"),
script: "deploy/static-server.mjs",
interpreter: process.execPath,
env: { NODE_ENV: "production", ADMIN_STATIC_PORT: "3010" },
autorestart: true,
restart_delay: 2000,
max_restarts: 10,
time: true,
},
],
};
+298
View File
@@ -0,0 +1,298 @@
import { createWriteStream } from "node:fs";
import {
copyFile,
cp,
mkdir,
open,
readFile,
readlink,
readdir,
rename,
rm,
symlink,
unlink,
writeFile,
} from "node:fs/promises";
import path from "node:path";
import { spawn, spawnSync } from "node:child_process";
import { checkPackage } from "../scripts/deploy/check-package.mjs";
const root = process.env.DEPLOY_ROOT;
if (!root || !path.isAbsolute(root)) throw new Error("DEPLOY_ROOT must be absolute");
const source = path.resolve(process.argv[2] ?? ".");
const environmentFile = path.join(root, "shared/.env.production");
process.loadEnvFile(environmentFile);
const current = path.join(root, "current");
const postgresContainer = process.env.POSTGRES_CONTAINER;
if (!postgresContainer || !/^[a-zA-Z0-9_.-]+$/.test(postgresContainer)) {
throw new Error("POSTGRES_CONTAINER is required for the database backup");
}
if (Number(process.versions.node.split(".")[0]) !== 24) throw new Error("Node.js 24 is required");
if (
process.env.NODE_ENV !== "production" ||
!process.env.DATABASE_URL ||
!process.env.SESSION_SECRET ||
process.env.SESSION_SECRET.length < 32 ||
!process.env.DEFAULT_BRAND_ID ||
!process.env.LOCAL_MEDIA_ROOT
) {
throw new Error("Production environment is missing required values");
}
if (!path.isAbsolute(process.env.LOCAL_MEDIA_ROOT))
throw new Error("LOCAL_MEDIA_ROOT must be absolute");
if (process.env.API_PREFIX) throw new Error("API_PREFIX must be empty when Traefik strips /api");
const databaseUrl = new URL(process.env.DATABASE_URL);
if (!["127.0.0.1", "localhost"].includes(databaseUrl.hostname)) {
throw new Error("DATABASE_URL must use the loopback-published PostgreSQL port");
}
const traefikDirectory = process.env.TRAEFIK_DYNAMIC_DIR ?? "/home/ubuntu/traefik/dynamic";
const traefikGateway = process.env.TRAEFIK_DOCKER_GATEWAY ?? "172.21.0.1";
const traefikHost = process.env.TRAEFIK_HOST ?? "wechat.app.que01.top";
if (!/^[a-zA-Z0-9.-]+$/.test(traefikHost) || !/^[a-zA-Z0-9.:-]+$/.test(traefikGateway)) {
throw new Error("Invalid Traefik host or gateway setting");
}
const routeFile = path.join(traefikDirectory, "personal-brand-managed.yml");
function run(command, args, cwd = root) {
const result = spawnSync(command, args, { cwd, stdio: "inherit", env: process.env });
if (result.status !== 0) throw new Error(command + " failed with exit " + result.status);
}
async function switchCurrent(target) {
const temporary = current + ".next-" + process.pid;
await symlink(target, temporary);
await rename(temporary, current);
}
async function backupDatabase(destination) {
const temporary = destination + ".tmp";
const child = spawn(
"docker",
[
"exec",
postgresContainer,
"sh",
"-c",
'exec pg_dump -Fc -U "$POSTGRES_USER" -d "$POSTGRES_DB"',
],
{ stdio: ["ignore", "pipe", "inherit"] },
);
const output = createWriteStream(temporary, { flags: "wx", mode: 0o600 });
child.stdout.pipe(output);
await Promise.all([
new Promise((resolve, reject) => {
child.on("error", reject);
child.on("exit", (code) =>
code === 0 ? resolve() : reject(new Error("Database backup failed")),
);
}),
new Promise((resolve, reject) => {
output.on("finish", resolve);
output.on("error", reject);
}),
]);
await rename(temporary, destination);
}
async function copyMissingFiles(sourceDirectory, destinationDirectory) {
await mkdir(destinationDirectory, { recursive: true });
for (const entry of await readdir(sourceDirectory, { withFileTypes: true })) {
if (!entry.isFile()) throw new Error("Unexpected seed media entry: " + entry.name);
try {
await copyFile(
path.join(sourceDirectory, entry.name),
path.join(destinationDirectory, entry.name),
1,
);
} catch (error) {
if (error.code !== "EEXIST") throw error;
}
}
}
async function writeTraefikRoute() {
await mkdir(traefikDirectory, { recursive: true });
const existing = await readFile(routeFile, "utf8").catch((error) => {
if (error.code === "ENOENT") return undefined;
throw error;
});
if (existing && !existing.includes("managed-by-personal-brand-deploy")) {
throw new Error("Refusing to overwrite an unmanaged Traefik route file");
}
const hostRule = "Host(`" + traefikHost + "`)";
const configuration = [
"# managed-by-personal-brand-deploy",
"http:",
" routers:",
" personal-brand-managed-admin:",
" rule: " + JSON.stringify(hostRule + " && !PathPrefix(`/api`) && !PathPrefix(`/media`)"),
" entryPoints:",
" - websecure",
" service: personal-brand-managed-admin",
" priority: 1000",
" tls:",
" certResolver: le",
" personal-brand-managed-api:",
" rule: " + JSON.stringify(hostRule + " && PathPrefix(`/api`)"),
" entryPoints:",
" - websecure",
" middlewares:",
" - personal-brand-managed-strip-api",
" service: personal-brand-managed-api",
" priority: 1000",
" tls:",
" certResolver: le",
" personal-brand-managed-media:",
" rule: " + JSON.stringify(hostRule + " && PathPrefix(`/media`)"),
" entryPoints:",
" - websecure",
" service: personal-brand-managed-api",
" priority: 1000",
" tls:",
" certResolver: le",
" middlewares:",
" personal-brand-managed-strip-api:",
" stripPrefix:",
" prefixes:",
" - /api",
" services:",
" personal-brand-managed-admin:",
" loadBalancer:",
" servers:",
" - url: http://" + traefikGateway + ":3010",
" personal-brand-managed-api:",
" loadBalancer:",
" servers:",
" - url: http://" + traefikGateway + ":" + (process.env.API_PORT ?? "3001"),
"",
].join("\n");
const temporary = routeFile + ".tmp-" + process.pid;
await writeFile(temporary, configuration, { mode: 0o644 });
await rename(temporary, routeFile);
}
async function waitForPublicRelease(release) {
const verifier = path.join(release, "scripts/deploy/verify-public-release.mjs");
for (let attempt = 0; attempt < 12; attempt++) {
const result = spawnSync(process.execPath, [verifier, release], {
cwd: release,
encoding: "utf8",
env: process.env,
timeout: 30000,
});
if (result.status === 0) {
process.stdout.write(result.stdout);
return;
}
if (attempt === 11) {
process.stderr.write(result.stderr ?? "");
throw new Error("Public release verification failed");
}
await new Promise((resolve) => setTimeout(resolve, 5000));
}
}
async function waitForHealth() {
const url = "http://127.0.0.1:" + (process.env.API_PORT ?? "3001") + "/health";
for (let attempt = 0; attempt < 20; attempt++) {
try {
const response = await fetch(url, { signal: AbortSignal.timeout(2000) });
const body = await response.json();
if (response.ok && body.status === "ok") return;
} catch {}
await new Promise((resolve) => setTimeout(resolve, 1000));
}
throw new Error("API health check failed");
}
await mkdir(path.join(root, "shared/backups"), { recursive: true });
await mkdir(path.join(root, "releases"), { recursive: true });
const lockPath = path.join(root, "shared/deploy.lock");
const lock = await open(lockPath, "wx", 0o600);
await lock.writeFile(String(process.pid));
let previous;
let switched = false;
let routeUpdated = false;
let previousRoute;
try {
const manifest = await checkPackage(source);
if (manifest.nodeMajor !== 24 || manifest.packageManager !== "pnpm@9.15.0") {
throw new Error("Unsupported release toolchain");
}
const pnpmVersion = spawnSync("pnpm", ["--version"], { encoding: "utf8" });
if (pnpmVersion.status !== 0 || pnpmVersion.stdout.trim() !== "9.15.0") {
throw new Error("pnpm 9.15.0 is required");
}
previous = await readlink(current).catch((error) => {
if (error.code === "ENOENT") {
throw new Error(
"Initialize DEPLOY_ROOT/current with the working deployment before the first managed release",
);
}
throw error;
});
if (!previous) throw new Error("DEPLOY_ROOT/current must point to the working deployment");
previousRoute = await readFile(routeFile).catch((error) => {
if (error.code === "ENOENT") return undefined;
throw error;
});
const release = path.join(root, "releases", manifest.version);
await mkdir(release, { recursive: false });
await cp(source, release, { recursive: true });
run(
"pnpm",
[
"--filter",
"@personal-brand/api...",
"install",
"--prod",
"--frozen-lockfile",
"--prefer-offline",
"--ignore-scripts",
],
release,
);
run("pnpm", ["--filter", "@personal-brand/api", "exec", "prisma", "generate"], release);
await backupDatabase(path.join(root, "shared/backups", manifest.version + ".dump"));
run("pnpm", ["--filter", "@personal-brand/api", "exec", "prisma", "migrate", "deploy"], release);
const seedDirectory = path.join(process.env.LOCAL_MEDIA_ROOT, "seed");
await copyMissingFiles(path.join(release, "seed-media"), seedDirectory);
await switchCurrent(release);
switched = true;
run("pm2", ["startOrRestart", path.join(release, "deploy/ecosystem.config.cjs"), "--update-env"]);
await waitForHealth();
const staticResponse = await fetch(
"http://127.0.0.1:" + (process.env.ADMIN_STATIC_PORT ?? "3010") + "/admin/",
{ signal: AbortSignal.timeout(5000) },
);
if (!staticResponse.ok) throw new Error("Admin static health check failed");
await writeTraefikRoute();
routeUpdated = true;
if (!process.env.PUBLIC_BASE_URL)
throw new Error("PUBLIC_BASE_URL is required for cutover verification");
await waitForPublicRelease(release);
await writeFile(path.join(root, "shared/previous-release"), previous + "\n");
run("pm2", ["save"]);
console.log("release installed: " + manifest.version);
} catch (error) {
if (routeUpdated) {
if (previousRoute) await writeFile(routeFile, previousRoute);
else await rm(routeFile, { force: true });
}
if (switched) {
await switchCurrent(previous);
run("pm2", [
"startOrRestart",
path.join(source, "deploy/ecosystem.config.cjs"),
"--update-env",
]);
await waitForHealth();
console.error(
"application and route rollback completed; database migrations were not reversed",
);
}
throw error;
} finally {
await lock.close();
await unlink(lockPath);
}
+182
View File
@@ -0,0 +1,182 @@
import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
import { createServer } from "node:http";
import path from "node:path";
import { fileURLToPath } from "node:url";
const contentTypes = new Map([
[".css", "text/css; charset=utf-8"],
[".gif", "image/gif"],
[".html", "text/html; charset=utf-8"],
[".ico", "image/x-icon"],
[".jpeg", "image/jpeg"],
[".jpg", "image/jpeg"],
[".js", "text/javascript; charset=utf-8"],
[".json", "application/json; charset=utf-8"],
[".map", "application/json; charset=utf-8"],
[".png", "image/png"],
[".svg", "image/svg+xml"],
[".webmanifest", "application/manifest+json"],
[".webp", "image/webp"],
[".woff", "font/woff"],
[".woff2", "font/woff2"],
]);
function setSecurityHeaders(response) {
response.setHeader("X-Content-Type-Options", "nosniff");
response.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
response.setHeader("X-Frame-Options", "SAMEORIGIN");
}
function sendError(response, status, message) {
response.writeHead(status, { "content-type": "text/plain; charset=utf-8" });
response.end(message);
}
function resolveInside(root, relativePath) {
const target = path.resolve(root, relativePath);
const relative = path.relative(root, target);
if (relative === ".." || relative.startsWith(".." + path.sep) || path.isAbsolute(relative)) {
return null;
}
return target;
}
function routeFor(pathname, adminRoot) {
if (pathname === "/") return { redirect: "/admin/" };
if (pathname === "/admin") return { redirect: "/admin/" };
if (pathname === "/template-preview") return { redirect: "/template-preview/" };
if (pathname === "/favicon.ico") return { root: adminRoot, relativePath: "favicon.ico" };
if (pathname.startsWith("/admin/")) {
return { root: adminRoot, relativePath: pathname.slice("/admin/".length), spa: true };
}
if (pathname.startsWith("/template-preview/")) {
return {
root: path.join(adminRoot, "template-preview"),
relativePath: pathname.slice("/template-preview/".length),
spa: true,
};
}
if (pathname.startsWith("/assets/")) {
return { root: adminRoot, relativePath: pathname.slice(1) };
}
return null;
}
export function createStaticServer({ adminRoot }) {
const root = path.resolve(adminRoot);
return createServer(async (request, response) => {
setSecurityHeaders(response);
if (request.method !== "GET" && request.method !== "HEAD") {
response.setHeader("Allow", "GET, HEAD");
sendError(response, 405, "Method Not Allowed");
return;
}
let pathname;
try {
pathname = new URL(request.url ?? "/", "http://localhost").pathname;
} catch {
sendError(response, 400, "Bad Request");
return;
}
const route = routeFor(pathname, root);
if (!route) {
sendError(response, 404, "Not Found");
return;
}
if (route.redirect) {
response.writeHead(308, { location: route.redirect });
response.end();
return;
}
let relativePath;
try {
relativePath = decodeURIComponent(route.relativePath);
} catch {
sendError(response, 400, "Bad Request");
return;
}
const target = resolveInside(route.root, relativePath || "index.html");
if (!target) {
sendError(response, 404, "Not Found");
return;
}
let filePath = target;
let fileInfo;
try {
fileInfo = await stat(filePath);
if (fileInfo.isDirectory()) {
filePath = path.join(filePath, "index.html");
fileInfo = await stat(filePath);
}
if (!fileInfo.isFile()) throw new Error("Not a regular file");
} catch {
const wantsHtml = request.headers.accept?.includes("text/html");
if (!route.spa || !wantsHtml || path.extname(relativePath)) {
sendError(response, 404, "Not Found");
return;
}
filePath = path.join(route.root, "index.html");
try {
fileInfo = await stat(filePath);
} catch {
sendError(response, 404, "Not Found");
return;
}
}
const etag =
'"' + fileInfo.size.toString(16) + "-" + Math.trunc(fileInfo.mtimeMs).toString(16) + '"';
response.setHeader("ETag", etag);
if (request.headers["if-none-match"] === etag) {
response.writeHead(304);
response.end();
return;
}
const extension = path.extname(filePath).toLowerCase();
response.setHeader("Content-Type", contentTypes.get(extension) ?? "application/octet-stream");
response.setHeader("Content-Length", fileInfo.size);
response.setHeader(
"Cache-Control",
extension === ".html"
? "no-cache"
: /(?:^|[.-])[a-zA-Z0-9_-]{8,}(?:[.-])/.test(path.basename(filePath))
? "public, max-age=31536000, immutable"
: "public, max-age=300",
);
response.writeHead(200);
if (request.method === "HEAD") {
response.end();
return;
}
const stream = createReadStream(filePath);
stream.on("error", () => {
if (!response.headersSent) sendError(response, 500, "Internal Server Error");
else response.destroy();
});
stream.pipe(response);
});
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const port = Number(process.env.ADMIN_STATIC_PORT ?? 3010);
const adminRoot = process.env.ADMIN_STATIC_ROOT ?? path.resolve("apps/admin/dist");
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error("ADMIN_STATIC_PORT must be between 1 and 65535");
}
const server = createStaticServer({ adminRoot });
server.listen(port, "0.0.0.0");
server.on("error", (error) => {
console.error("admin static server failed", error);
process.exitCode = 1;
});
for (const signal of ["SIGINT", "SIGTERM"]) {
process.on(signal, () => server.close(() => process.exit(0)));
}
}
+59
View File
@@ -0,0 +1,59 @@
import assert from "node:assert/strict";
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import test from "node:test";
import { createStaticServer } from "./static-server.mjs";
test("static server serves the admin, template preview, and root public assets", async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), "personal-brand-static-"));
const adminRoot = path.join(directory, "dist");
await mkdir(path.join(adminRoot, "assets", "owner"), { recursive: true });
await mkdir(path.join(adminRoot, "template-preview"), { recursive: true });
await writeFile(path.join(adminRoot, "index.html"), "admin entry");
await writeFile(path.join(adminRoot, "template-preview", "index.html"), "preview entry");
await writeFile(path.join(adminRoot, "assets", "app-12345678.js"), "console.log('ok')");
await writeFile(path.join(adminRoot, "assets", "owner", "portrait.jpg"), "portrait");
const server = createStaticServer({ adminRoot });
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
const baseUrl = "http://127.0.0.1:" + address.port;
try {
const admin = await fetch(baseUrl + "/admin/");
assert.equal(admin.status, 200);
assert.match(admin.headers.get("content-type"), /text\/html/);
assert.equal(await admin.text(), "admin entry");
const adminRoute = await fetch(baseUrl + "/admin/brand", {
headers: { accept: "text/html" },
});
assert.equal(await adminRoute.text(), "admin entry");
const preview = await fetch(baseUrl + "/template-preview/");
assert.equal(await preview.text(), "preview entry");
const script = await fetch(baseUrl + "/admin/assets/app-12345678.js");
assert.match(script.headers.get("content-type"), /javascript/);
assert.match(script.headers.get("cache-control"), /immutable/);
const image = await fetch(baseUrl + "/assets/owner/portrait.jpg");
assert.equal(image.headers.get("content-type"), "image/jpeg");
assert.equal(await image.text(), "portrait");
const missingAsset = await fetch(baseUrl + "/admin/assets/missing.js");
assert.equal(missingAsset.status, 404);
assert.match(missingAsset.headers.get("content-type"), /text\/plain/);
const traversal = await fetch(baseUrl + "/admin/%2e%2e/%2e%2e/etc/passwd");
assert.equal(traversal.status, 404);
const unsupportedMethod = await fetch(baseUrl + "/admin/", { method: "POST" });
assert.equal(unsupportedMethod.status, 405);
} finally {
await new Promise((resolve, reject) =>
server.close((error) => (error ? reject(error) : resolve())),
);
await rm(directory, { recursive: true, force: true });
}
});
+42
View File
@@ -0,0 +1,42 @@
http:
routers:
personal-brand-admin-vps:
rule: "Host(`wechat.app.que01.top`) && !PathPrefix(`/api`) && !PathPrefix(`/media`)"
entryPoints:
- websecure
service: personal-brand-admin-vps
priority: 1000
tls:
certResolver: le
personal-brand-api-vps:
rule: "Host(`wechat.app.que01.top`) && PathPrefix(`/api`)"
entryPoints:
- websecure
middlewares:
- personal-brand-api-strip-vps
service: personal-brand-api-vps
priority: 1000
tls:
certResolver: le
personal-brand-media-vps:
rule: "Host(`wechat.app.que01.top`) && PathPrefix(`/media`)"
entryPoints:
- websecure
service: personal-brand-api-vps
priority: 1000
tls:
certResolver: le
middlewares:
personal-brand-api-strip-vps:
stripPrefix:
prefixes:
- /api
services:
personal-brand-admin-vps:
loadBalancer:
servers:
- url: http://172.21.0.1:3010
personal-brand-api-vps:
loadBalancer:
servers:
- url: http://172.21.0.1:3001