import { createServer } from "node:http"; import { cp, lstat, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises"; import { dirname, join, resolve, posix, relative } from "node:path"; import { fileURLToPath } from "node:url"; import { randomBytes } from "node:crypto"; import { createSiteApplication } from "./site-app.mjs"; const cmsRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); const projectsRoot = resolve(process.env.CMS_PROJECTS_ROOT || join(cmsRoot, "projects")); // New workspaces share the existing persistent projects mount, not a site's tree. const sitesRoot = resolve(process.env.CMS_SITES_ROOT || join(projectsRoot, "sites")); const defaultId = process.env.CMS_PROJECT || "nodedc"; const applications = new Map(); let registryQueue = Promise.resolve(); const fail = (message, status = 400) => Object.assign(new Error(message), { status }); function validId(id) { if (typeof id !== "string" || !/^[a-z][a-z0-9-]{0,47}$/.test(id)) throw fail("ID: латинская буква, затем буквы, цифры или дефис (до 48 символов)"); return id; } function transaction(fn) { const result = registryQueue.then(fn); registryQueue = result.catch(() => {}); return result; } async function atomicJson(path, value) { const tmp = `${path}.${randomBytes(6).toString("hex")}.tmp`; try { await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`, { flag: "wx", mode: 0o600 }); await rename(tmp, path); } finally { await rm(tmp, { force: true }); } } const writeConfig = (id, value) => atomicJson(join(projectsRoot, `${validId(id)}.json`), value); async function projectIds() { return (await readdir(projectsRoot)).filter(name => /^[a-z][a-z0-9-]{0,47}\.json$/.test(name)).map(name => name.slice(0, -5)).sort(); } function destination(config) { const d = config.deploy || {}; return { server: [String(d.host || "").trim().toLowerCase(), Number(d.port || 22), String(d.username || "").trim()].join("|"), path: posix.normalize(`/${String(d.remotePath || "httpdocs").replace(/\\/g, "/")}`).replace(/\/$/, "") || "/", }; } async function validateDeploy(id, config) { if (!config.deploy?.enabled) return; const own = destination(config); for (const otherId of await projectIds()) { if (id === otherId) continue; const other = (await application(otherId)).config(); if (!other.deploy?.enabled) continue; const target = destination(other); const overlap = own.path === "/" || target.path === "/" || own.path === target.path || own.path.startsWith(`${target.path}/`) || target.path.startsWith(`${own.path}/`); if (own.server === target.server && overlap) throw fail(`Папка публикации пересекается с сайтом «${other.name}». Перенесите настройки деплоя или отключите публикацию другого сайта.`, 409); } } async function application(id) { validId(id); if (!applications.has(id)) { const pending = createSiteApplication({ projectId: id, projectsRoot, projectRoot: id === defaultId ? process.env.SITE_ROOT : undefined, hooks: { transaction, validateDeploy, writeConfig }, }).then(app => { app.writes = 0; return app; }); applications.set(id, pending); pending.catch(() => applications.delete(id)); } try { return await applications.get(id); } catch (error) { if (error.code === "ENOENT") throw fail("Сайт не найден", 404); throw error; } } function ensureIdle(app) { if (app.writes || app.isPublishing()) throw fail("Сайт занят сохранением, импортом или публикацией. Повторите после завершения.", 409); } async function siteList() { return Promise.all((await projectIds()).map(async id => { const config = (await application(id)).publicConfig(); return { id, name: config.name, publicUrl: config.publicUrl, deployEnabled: Boolean(config.deploy?.enabled), ready: config.site.ready, adminUrl: `/s/${id}/`, previewUrl: `/s/${id}/index.html` }; })); } const excluded = new Set([".git", ".cms-backups", ".trash", "node_modules", ".DS_Store", ".env"]); async function createSite(payload) { return transaction(async () => { const id = validId(payload.id); if ((await projectIds()).includes(id)) throw fail("Сайт с таким ID уже существует", 409); const source = await application(validId(payload.copyFrom)); ensureIdle(source); await mkdir(sitesRoot, { recursive: true }); const root = join(sitesRoot, id); await mkdir(root); // Reservation: never overwrite an existing tree. source.writes++; try { if ((await lstat(source.root)).isSymbolicLink()) throw fail("Копирование сайта с символическими ссылками не поддерживается"); // The destination root is our reservation. Node 24 rejects cp onto an // existing directory with errorOnExist, so copy its children separately. for (const entry of await readdir(source.root)) await cp(join(source.root, entry), join(root, entry), { recursive: true, force: false, errorOnExist: true, filter: async path => { const parts = relative(source.root, path).split(/[\\/]/); if (parts.some(part => excluded.has(part) || part.startsWith("._") || part.endsWith(".secrets.json"))) return false; if ((await lstat(path)).isSymbolicLink()) throw fail("Копирование сайта с символическими ссылками не поддерживается"); return true; }, }); const config = { ...source.config(), id, name: String(payload.name || id).trim().slice(0, 160), siteRoot: root, previewUrl: "", publicUrl: String(payload.publicUrl || "").trim(), deploy: { enabled: false, deployOnRender: false, method: "sftp", host: "", port: 22, username: "", remotePath: "" } }; await writeConfig(id, config); return (await application(id)).publicConfig(); } catch (error) { await rm(root, { recursive: true, force: true }); await rm(join(projectsRoot, `${id}.json`), { force: true }); applications.delete(id); throw error; } finally { source.writes--; } }); } async function transferDeploy(id, fromId) { return transaction(async () => { if (id === fromId) throw fail("Выберите другой сайт"); const target = await application(validId(id)); const source = await application(validId(fromId)); ensureIdle(source); ensureIdle(target); const before = source.config(); const next = target.config(); if (next.deploy?.enabled || next.deploy?.host) throw fail("У получателя уже есть настройки деплоя; перенос не перезаписывает их", 409); if (!before.deploy?.host) throw fail("У исходного сайта не настроен хостинг"); source.writes++; target.writes++; try { // Disable source on disk first. On interruption both may be disabled, // but never two active publishers for the same folder. await writeConfig(fromId, { ...before, deploy: { ...before.deploy, enabled: false, deployOnRender: false } }); await source.reloadConfig(); try { await atomicJson(target.secretsPath, JSON.parse(await readFile(source.secretsPath, "utf8"))); } catch (error) { if (error.code !== "ENOENT") throw error; } next.deploy = { ...before.deploy, enabled: false, deployOnRender: false }; await writeConfig(id, next); await target.reloadConfig(); return target.publicConfig(); } finally { source.writes--; target.writes--; } }); } async function body(req) { let result = ""; for await (const chunk of req) { result += chunk; if (result.length > 65536) throw fail("Слишком большой запрос", 413); } try { return JSON.parse(result || "{}"); } catch { throw fail("Некорректный JSON"); } } function json(res, status, payload) { res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" }); res.end(JSON.stringify(payload)); } await mkdir(projectsRoot, { recursive: true }); const auth = await application(defaultId); const server = createServer(async (req, res) => { try { const url = new URL(req.url, "http://cms.local"); if (await auth.handleAuthRoute(req, res, url)) return; if (!auth.authorizeRequest(req, res, url)) return; if (!["GET", "HEAD", "OPTIONS"].includes(req.method)) { const origin = req.headers.origin; const expected = new URL(process.env.CMS_BASE_URL || `http://${req.headers.host}`).origin; if (req.headers["sec-fetch-site"] === "cross-site" || (origin && origin !== expected)) throw fail("Недопустимый источник запроса", 403); } if (url.pathname === "/api/sites") { if (req.method === "GET") return json(res, 200, { ok: true, sites: await siteList() }); if (req.method === "POST") return json(res, 201, { ok: true, project: await createSite(await body(req)) }); throw fail("Метод не поддерживается", 405); } const transfer = /^\/api\/sites\/([a-z][a-z0-9-]{0,47})\/deploy-transfer$/.exec(url.pathname); if (transfer && req.method === "POST") return json(res, 200, { ok: true, project: await transferDeploy(transfer[1], (await body(req)).fromSiteId) }); if (["/", "/admin", "/admin/"].includes(url.pathname)) { res.writeHead(302, { location: `/s/${defaultId}/`, "cache-control": "no-store" }); return res.end(); } const match = /^\/s\/([a-z][a-z0-9-]{0,47})(\/.*)?$/.exec(url.pathname); if (url.pathname.startsWith("/s/") && !match) throw fail("Сайт не найден", 404); const app = match ? await application(match[1]) : auth; if (match && !match[2]) { res.writeHead(302, { location: `/s/${match[1]}/` }); return res.end(); } if (match) { req.cmsSitePrefix = `/s/${match[1]}`; req.url = `${match[2] || "/"}${url.search}`; } if (!["GET", "HEAD", "OPTIONS"].includes(req.method)) { ensureIdle(app); app.writes++; try { await app.handle(req, res); } finally { app.writes--; } } else await app.handle(req, res); } catch (error) { if (!res.headersSent) json(res, error.status || 500, { ok: false, error: error.message }); else res.end(); } }); server.listen(Number(process.env.PORT || 8090), process.env.HOST || "127.0.0.1", () => { console.log(`DC CMS multisite: ${JSON.stringify(server.address())}`); });