diff --git a/deploy/chatgpt-imagegen-mcp.service b/deploy/chatgpt-imagegen-mcp.service new file mode 100644 index 0000000..6cc98c3 --- /dev/null +++ b/deploy/chatgpt-imagegen-mcp.service @@ -0,0 +1,25 @@ +[Unit] +Description=ChatGPT image generation MCP server +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=mcp +Group=mcp +WorkingDirectory=/opt/chatgpt-imagegen-mcp +EnvironmentFile=/opt/chatgpt-imagegen-mcp/.env +ExecStart=/usr/bin/xvfb-run -a --server-args="-screen 0 1440x900x24" /usr/bin/node dist/index.js +Restart=on-failure +RestartSec=10 +TimeoutStopSec=30 + +# Hardening that keeps Chromium and the sudo-based update restart working. +# Do not set NoNewPrivileges=true: it breaks `sudo systemctl restart` in scripts/update.sh. +ProtectSystem=full +ProtectHome=true +PrivateTmp=true +ReadWritePaths=/opt/chatgpt-imagegen-mcp + +[Install] +WantedBy=multi-user.target diff --git a/deploy/nginx-location.conf b/deploy/nginx-location.conf new file mode 100644 index 0000000..de28a56 --- /dev/null +++ b/deploy/nginx-location.conf @@ -0,0 +1,26 @@ +# Include inside the `server { ... }` block of your TLS vhost. + +location /chatgptimagegen/public-media/ { + proxy_pass http://127.0.0.1:8088/public-media/; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_read_timeout 300s; +} + +location /chatgptimagegen/ { + proxy_pass http://127.0.0.1:8088/; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header Connection ""; + proxy_buffering off; + proxy_request_buffering off; + proxy_read_timeout 3600s; + proxy_send_timeout 3600s; + client_max_body_size 40m; +} diff --git a/deploy/sudoers.chatgpt-imagegen-mcp b/deploy/sudoers.chatgpt-imagegen-mcp new file mode 100644 index 0000000..990bb72 --- /dev/null +++ b/deploy/sudoers.chatgpt-imagegen-mcp @@ -0,0 +1,2 @@ +# Install as /etc/sudoers.d/chatgpt-imagegen-mcp (mode 0440), validate with: visudo -cf +mcp ALL=(root) NOPASSWD: /usr/bin/systemctl restart chatgpt-imagegen-mcp.service diff --git a/scripts/update.sh b/scripts/update.sh new file mode 100755 index 0000000..1dd2f8b --- /dev/null +++ b/scripts/update.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +# Idempotent update for the install living in the parent directory of this script. +# Output goes to stdout with timestamps; the caller redirects it to a log file. +# There are no database migrations: all state is plain files on disk (media, profile, jobs). +set -Eeuo pipefail + +SERVICE_NAME="${SERVICE_NAME:-chatgpt-imagegen-mcp.service}" +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" + +log() { printf '[%s] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*"; } + +BACKUP="" +BUILD_STARTED=0 +on_error() { + local code=$? + trap - ERR + if [[ "$BUILD_STARTED" == 1 && -n "$BACKUP" && -d "$BACKUP" ]]; then + log "restoring previous dist" + rm -rf "$ROOT/dist" + cp -a "$BACKUP" "$ROOT/dist" + fi + log "UPDATE_FAILED $(date -u +%Y-%m-%dT%H:%M:%SZ) (exit $code, service not restarted)" + exit "$code" +} +trap on_error ERR + +exec 9>"$ROOT/.update.lock" +if ! flock -n 9; then + log "another update is already running" + trap - ERR + exit 1 +fi + +log "update started in $ROOT" +log "git fetch + pull --ff-only" +git fetch --prune +git pull --ff-only + +log "npm ci" +npm ci + +log "installing Playwright Chromium (system libraries are not installed here; see docs/deployment.md)" +npx playwright install chromium + +if [[ -d dist ]]; then + BACKUP="$(mktemp -d "$ROOT/.dist-backup.XXXXXX")" + cp -a dist/. "$BACKUP/" +fi +BUILD_STARTED=1 +log "npm run build" +npm run build + +log "npm test" +npm test + +rm -rf "$BACKUP" +BACKUP="" +BUILD_STARTED=0 + +log "restarting $SERVICE_NAME" +echo "UPDATE_SUCCEEDED $(date -u +%Y-%m-%dT%H:%M:%SZ)" +trap - ERR +sudo -n systemctl restart "$SERVICE_NAME" || { log "UPDATE_FAILED $(date -u +%Y-%m-%dT%H:%M:%SZ) (restart failed)"; exit 1; } diff --git a/src/update.ts b/src/update.ts new file mode 100644 index 0000000..6d04a63 --- /dev/null +++ b/src/update.ts @@ -0,0 +1,164 @@ +import { spawn } from "node:child_process"; +import { createHash, timingSafeEqual } from "node:crypto"; +import { closeSync, existsSync, mkdirSync, openSync, readFileSync } from "node:fs"; +import path from "node:path"; +import type express from "express"; +import { audit, auditError } from "./log.js"; + +export type UpdateState = "idle" | "running" | "succeeded" | "failed"; + +export interface UpdateStatus { + state: UpdateState; + startedAt: string | null; + finishedAt: string | null; + exitCode: number | null; +} + +const MIN_TOKEN_LENGTH = 32; +const SUCCESS_MARKER = "UPDATE_SUCCEEDED"; +const FAILURE_MARKER = "UPDATE_FAILED"; +const LOG_TAIL_LINES = 50; + +export function tokenValid(provided: string | undefined, expected: string | undefined): boolean { + if (!expected || expected.length < MIN_TOKEN_LENGTH || !provided) return false; + const a = createHash("sha256").update(provided).digest(); + const b = createHash("sha256").update(expected).digest(); + return timingSafeEqual(a, b); +} + +export function bearerToken(header: string | undefined): string | undefined { + const match = /^Bearer\s+(.+)$/i.exec(header ?? ""); + return match?.[1]?.trim() || undefined; +} + +export class RateLimiter { + private readonly hits = new Map(); + + constructor(private readonly max: number, private readonly windowMs: number) {} + + check(key: string, now = Date.now()): { allowed: boolean; retryAfterSeconds: number } { + const recent = this.recent(key, now); + if (recent.length >= this.max) return { allowed: false, retryAfterSeconds: Math.max(1, Math.ceil(((recent[0] ?? now) + this.windowMs - now) / 1000)) }; + return { allowed: true, retryAfterSeconds: 0 }; + } + + record(key: string, now = Date.now()): void { + const recent = this.recent(key, now); + recent.push(now); + this.hits.set(key, recent); + } + + private recent(key: string, now: number): number[] { + const recent = (this.hits.get(key) ?? []).filter((time) => now - time < this.windowMs); + if (recent.length) this.hits.set(key, recent); + else this.hits.delete(key); + return recent; + } +} + +export function parseLastMarker(logText: string): { state: "succeeded" | "failed"; finishedAt: string | null } | undefined { + const lines = logText.split("\n").map((line) => line.trim()).filter(Boolean); + const last = lines[lines.length - 1] ?? ""; + const success = last.indexOf(SUCCESS_MARKER); + if (success >= 0) return { state: "succeeded", finishedAt: last.slice(success + SUCCESS_MARKER.length).trim() || null }; + const failure = last.indexOf(FAILURE_MARKER); + if (failure >= 0) return { state: "failed", finishedAt: last.slice(failure + FAILURE_MARKER.length).trim() || null }; + return undefined; +} + +function tailLines(file: string, count: number): string[] { + try { + const text = readFileSync(file, "utf8"); + return text.split("\n").filter((line) => line.length > 0).slice(-count); + } catch { + return []; + } +} + +function positiveNumber(value: string | undefined, fallback: number): number { + const parsed = Number(value); + return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback; +} + +export function registerUpdateRoutes(app: express.Express): void { + const logFile = () => process.env.UPDATE_LOG_FILE || path.join(process.cwd(), "logs", "update.log"); + const scriptPath = () => process.env.UPDATE_SCRIPT || path.join(process.cwd(), "scripts", "update.sh"); + const maxRequests = positiveNumber(process.env.UPDATE_RATE_LIMIT_MAX, 30); + const windowMs = positiveNumber(process.env.UPDATE_RATE_LIMIT_WINDOW_SECONDS, 900) * 1000; + const requests = new RateLimiter(maxRequests, windowMs); + const failures = new RateLimiter(Math.min(5, maxRequests), windowMs); + + let status: UpdateStatus = { state: "idle", startedAt: null, finishedAt: null, exitCode: null }; + try { + const marker = parseLastMarker(readFileSync(logFile(), "utf8")); + if (marker) status = { state: marker.state, startedAt: null, finishedAt: marker.finishedAt, exitCode: marker.state === "succeeded" ? 0 : 1 }; + } catch { + // no previous log + } + + const view = () => ({ ...status, logTail: tailLines(logFile(), LOG_TAIL_LINES).join("\n") }); + + const guard: express.RequestHandler = (req, res, next) => { + const expected = process.env.UPDATE_TOKEN; + if (!expected || expected.length < MIN_TOKEN_LENGTH) { + res.status(503).json({ error: "update_not_configured" }); + return; + } + const client = req.ip || "unknown"; + const limits = [requests.check(client), failures.check(client)]; + const blocked = limits.find((limit) => !limit.allowed); + if (blocked) { + audit("update_rate_limited", { client, path: req.path }); + res.setHeader("Retry-After", String(blocked.retryAfterSeconds)); + res.status(429).json({ error: "rate_limited", retryAfterSeconds: blocked.retryAfterSeconds }); + return; + } + requests.record(client); + if (!tokenValid(bearerToken(req.header("authorization")), expected)) { + failures.record(client); + audit("update_auth_failed", { client, path: req.path }); + res.setHeader("WWW-Authenticate", "Bearer"); + res.status(401).json({ error: "unauthorized" }); + return; + } + next(); + }; + + app.post("/admin/update", guard, (req, res) => { + if (status.state === "running") { + res.status(409).json({ error: "update_already_running", ...view() }); + return; + } + try { + const file = logFile(); + mkdirSync(path.dirname(file), { recursive: true }); + const script = scriptPath(); + if (!existsSync(script)) { + res.status(500).json({ error: "update_script_missing" }); + return; + } + const fd = openSync(file, "a"); + const child = spawn(script, [], { cwd: process.cwd(), detached: true, stdio: ["ignore", fd, fd] }); + closeSync(fd); + status = { state: "running", startedAt: new Date().toISOString(), finishedAt: null, exitCode: null }; + audit("update_started", { client: req.ip, pid: child.pid }); + child.on("error", (error) => { + auditError("update_spawn_failed", error); + status = { ...status, state: "failed", finishedAt: new Date().toISOString(), exitCode: null }; + }); + child.on("exit", (code, signal) => { + status = { ...status, state: code === 0 ? "succeeded" : "failed", finishedAt: new Date().toISOString(), exitCode: code }; + audit("update_finished", { exitCode: code, signal }); + }); + child.unref(); + res.status(202).json(view()); + } catch (error) { + auditError("update_start_failed", error); + res.status(500).json({ error: "update_start_failed" }); + } + }); + + app.get("/admin/update/status", guard, (_req, res) => { + res.json(view()); + }); +} diff --git a/test/update.test.ts b/test/update.test.ts new file mode 100644 index 0000000..f6276de --- /dev/null +++ b/test/update.test.ts @@ -0,0 +1,105 @@ +import assert from "node:assert/strict"; +import { chmodSync, mkdtempSync, writeFileSync } from "node:fs"; +import type { AddressInfo } from "node:net"; +import os from "node:os"; +import path from "node:path"; +import { after, before, describe, it } from "node:test"; +import express from "express"; +import { RateLimiter, bearerToken, parseLastMarker, registerUpdateRoutes, tokenValid } from "../src/update.js"; + +const token = "t".repeat(40); + +describe("tokenValid", () => { + it("rejects missing, short and wrong tokens", () => { + assert.equal(tokenValid(undefined, token), false); + assert.equal(tokenValid(token, undefined), false); + assert.equal(tokenValid("short", "short"), false); + assert.equal(tokenValid("x".repeat(40), token), false); + assert.equal(tokenValid(token.slice(1), token), false); + }); + it("accepts the right token", () => { + assert.equal(tokenValid(token, token), true); + }); + it("parses bearer headers", () => { + assert.equal(bearerToken("Bearer abc"), "abc"); + assert.equal(bearerToken("Basic abc"), undefined); + assert.equal(bearerToken(undefined), undefined); + }); +}); + +describe("RateLimiter", () => { + it("blocks after max hits and recovers when the window passes", () => { + const limiter = new RateLimiter(2, 1000); + limiter.record("a", 0); + limiter.record("a", 100); + const blocked = limiter.check("a", 200); + assert.equal(blocked.allowed, false); + assert.equal(blocked.retryAfterSeconds, 1); + assert.equal(limiter.check("b", 200).allowed, true); + assert.equal(limiter.check("a", 1001).allowed, true); + }); +}); + +describe("parseLastMarker", () => { + it("reads the last line only", () => { + assert.deepEqual(parseLastMarker("a\n[x] UPDATE_SUCCEEDED 2026-01-01T00:00:00Z\n"), { state: "succeeded", finishedAt: "2026-01-01T00:00:00Z" }); + assert.equal(parseLastMarker("UPDATE_SUCCEEDED t\nrestarting\n"), undefined); + assert.equal(parseLastMarker("UPDATE_FAILED t")?.state, "failed"); + }); +}); + +describe("update routes", () => { + const dir = mkdtempSync(path.join(os.tmpdir(), "update-test-")); + const script = path.join(dir, "fake-update.sh"); + let base = ""; + let server: ReturnType; + + before(async () => { + writeFileSync(script, "#!/bin/bash\necho fake-update-start\nsleep 1\necho \"UPDATE_SUCCEEDED $(date -u +%FT%TZ)\"\n"); + chmodSync(script, 0o755); + process.env.UPDATE_SCRIPT = script; + process.env.UPDATE_LOG_FILE = path.join(dir, "logs", "update.log"); + process.env.UPDATE_TOKEN = token; + const app = express(); + registerUpdateRoutes(app); + server = app.listen(0, "127.0.0.1"); + await new Promise((resolve) => server.once("listening", resolve)); + base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + }); + + after(() => { + server.close(); + delete process.env.UPDATE_TOKEN; + }); + + const call = (method: string, route: string, auth?: string) => fetch(base + route, { method, headers: auth ? { Authorization: auth } : {} }); + + it("returns 503 when the token is not configured", async () => { + process.env.UPDATE_TOKEN = "short"; + assert.equal((await call("POST", "/admin/update", "Bearer short")).status, 503); + process.env.UPDATE_TOKEN = token; + }); + + it("returns 401 for missing or wrong tokens", async () => { + assert.equal((await call("POST", "/admin/update")).status, 401); + assert.equal((await call("GET", "/admin/update/status", "Bearer nope")).status, 401); + }); + + it("starts an update, rejects a concurrent one and reports status", async () => { + const started = await call("POST", "/admin/update", `Bearer ${token}`); + assert.equal(started.status, 202); + assert.equal(((await started.json()) as { state: string }).state, "running"); + assert.equal((await call("POST", "/admin/update", `Bearer ${token}`)).status, 409); + for (let i = 0; i < 50; i++) { + const status = (await (await call("GET", "/admin/update/status", `Bearer ${token}`)).json()) as { state: string; exitCode: number; logTail: string }; + if (status.state !== "running") { + assert.equal(status.state, "succeeded"); + assert.equal(status.exitCode, 0); + assert.match(status.logTail, /fake-update-start/); + return; + } + await new Promise((resolve) => setTimeout(resolve, 200)); + } + assert.fail("update did not finish"); + }); +});