docs: add README, session, architecture, deployment and update guides

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-07 17:09:51 +02:00
1 parent 981dc3b941
commit d751acfe63
7 files changed
+278

No files matched your search

+32
View File
@@ -0,0 +1,32 @@
# Architecture
```
MCP client ──POST /mcp──▶ tools.ts ──▶ JobManager (serial queue, pacing, circuit breaker)
│
▼
ChatGptImageProvider ──▶ BrowserSession (persistent Chromium profile)
│ │
▼ ▼
media.ts (disk + manifests) chatgpt.com
```
## Generation flow (one image)
1. Open `CHATGPT_URL` (a new empty chat). Fail with `SESSION_NOT_READY` if login markers are visible.
2. Record the image `src`s already on the page (baseline).
3. Upload reference images through the hidden file input and wait for the upload to finish.
4. Type the wrapped prompt (`src/chatgpt/prompts.ts`) into the composer and send it.
5. Wait for the turn: the stop button appears and then stays gone for two polls.
6. Wait for a new image outside the user message, at least 256 px per side, fully loaded, with a `src` that stays the same for 3 polls and no "creating image" text. ChatGPT shows blurred partial previews first, so the first image seen is not the final one.
7. Download it through the browser request context (it carries the session cookies), validate size and format, store it as `<generationId>-<index>.<ext>`.
`image_count > 1` repeats this in a new chat per image. Every job runs alone because the profile can only be used by one browser.
## Lineage
Ported from ZenvairoProspect's `imagegen` package (Python, branch `legacy/whatsapp-mockup`): selectors as ordered fallback lists, the persistent profile with a manual login, turn detection through the stop button, usage-limit detection by text, downloads through `page.request`, HTML diagnostics and random pacing. The MCP surface, media storage and signed URLs follow ZenvairoMediaGenerator-MCP so clients can switch backends.
Changes from Prospect:
- Limit and error texts are matched only against error banners and the assistant reply, never against the whole page. The user's prompt is on the page too.
- The final image is detected by `src` stability, and uploaded references are excluded.
- A circuit breaker rejects new jobs right away, instead of the queue sleeping for an hour.
+46
View File
@@ -0,0 +1,46 @@
# ChatGPT session
The server drives chatgpt.com with a persistent Chromium profile (`CHATGPT_PROFILE_DIR`). That profile must be logged in once by a human; the server never handles passwords.
Chromium locks the profile directory, so **stop the service before** running any of the commands below.
## Log in on a machine with a display
```bash
npm run login # dev (tsx)
npm run login:prod # after npm run build
```
A visible browser opens chatgpt.com. Log in by hand (2FA included). The window closes by itself once the session is detected (up to 10 minutes).
Check the profile without opening a window:
```bash
npm run login -- --check
```
## Log in for a headless server
Pick one:
1. **Log in locally, copy the profile.** Run `npm run login` on your desktop with the same Playwright version, then copy the directory to the server (`rsync -a profiles/chatgpt/ server:/opt/chatgpt-imagegen-mcp/profiles/chatgpt/`) and `chown -R mcp:mcp` it. Playwright's Chromium stores cookies with the `basic` password store, so the profile works on another machine.
2. **Log in on the server through X forwarding.** `ssh -X` to the server and run `sudo -u mcp --preserve-env=DISPLAY,XAUTHORITY npm run login:prod`.
Then start the service and confirm with the `check_session` MCP tool or `GET /health` (`session.loggedIn`).
## When the session expires
Jobs fail with `SESSION_NOT_READY` and the circuit breaker rejects new jobs for `CHATGPT_SESSION_RECHECK_MINUTES`. Stop the service, log in again, start it.
## Usage limits
The account's own image quota applies. When chatgpt.com shows a limit notice the job fails with `USAGE_LIMIT_REACHED` (`retryable: true`, `retryAfter`) and new jobs are rejected for `CHATGPT_USAGE_LIMIT_COOLDOWN_MINUTES`. Random pacing between generations (`CHATGPT_MIN/MAX_INTERVAL_SECONDS`) keeps the traffic human-like.
## When chatgpt.com changes its markup
All DOM knowledge lives in `src/chatgpt/selectors.ts`: ordered lists of alternative selectors. On a UI failure the server writes an HTML dump and a screenshot to `DIAGNOSTICS_DIR` (newest `MAX_DIAGNOSTICS` kept). Inspect them, add the new selector **at the front** of the matching list, and update the fixtures in `test/fixtures/`. Diagnostics may contain conversation text: never commit them.
## Notes
- This automates a consumer web UI. It is unofficial, may break without notice, and must comply with OpenAI's terms for the account used.
- Never put the profile directory in git or logs: it holds the session cookies.
+57
View File
@@ -0,0 +1,57 @@
# Deployment
Target: Debian or Ubuntu (one of the last three major releases) in an LXC container or VPS, running under systemd behind nginx. Docker is not used for deployment.
## 1. System packages
```bash
apt update && apt install -y git xvfb curl ca-certificates
# Node.js >= 20 via NodeSource (see https://github.com/nodesource/distributions)
curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && apt install -y nodejs
```
`xvfb` provides the virtual display: Chromium runs headed inside Xvfb by default because ChatGPT/Cloudflare blocks headless Chromium more often.
## 2. User and code
```bash
useradd --system --create-home --home-dir /opt/chatgpt-imagegen-mcp --shell /bin/bash mcp
sudo -u mcp git clone <repo-url> /opt/chatgpt-imagegen-mcp
cd /opt/chatgpt-imagegen-mcp
sudo -u mcp npm ci
npx playwright install-deps chromium # as root: installs Chromium system libraries
sudo -u mcp npx playwright install chromium # as mcp: downloads the browser
sudo -u mcp npm run build
```
## 3. Configuration
```bash
sudo -u mcp cp .env.example .env && chmod 600 .env
```
Edit `.env` (bearer token, `UPDATE_TOKEN`, media/profile paths, ...). Generate secrets with `openssl rand -hex 32`.
## 4. ChatGPT login
The persistent Chromium profile must be logged in to chatgpt.com once. See [chatgpt-session.md](chatgpt-session.md).
## 5. systemd and sudoers
```bash
cp deploy/chatgpt-imagegen-mcp.service /etc/systemd/system/
install -m 0440 deploy/sudoers.chatgpt-imagegen-mcp /etc/sudoers.d/chatgpt-imagegen-mcp
visudo -cf /etc/sudoers.d/chatgpt-imagegen-mcp
systemctl daemon-reload && systemctl enable --now chatgpt-imagegen-mcp.service
journalctl -u chatgpt-imagegen-mcp.service -f
```
The sudoers rule only lets `mcp` restart this one service; the update script needs it. Adjust paths in the unit if you install elsewhere (and add any custom media/profile/log directories to `ReadWritePaths`).
## 6. nginx
Include `deploy/nginx-location.conf` in your TLS `server` block, then `nginx -t && systemctl reload nginx`. The service listens on `127.0.0.1:8088`; the MCP endpoint is `https://<host>/chatgptimagegen/mcp` with bearer auth. Set `TRUST_PROXY=1` in `.env` so rate limiting sees real client IPs.
## 7. Updates
See [update.md](update.md).
+56
View File
@@ -0,0 +1,56 @@
# Updating
## Script
`scripts/update.sh` updates the install it lives in. It is idempotent and logs timestamped lines to stdout.
1. Takes a lock (`flock` on `.update.lock`); fails if another update is running.
2. `git fetch` + `git pull --ff-only`.
3. `npm ci`, then `npx playwright install chromium` (system libraries need `npx playwright install-deps chromium` as root, see [deployment.md](deployment.md)).
4. Backs up `dist/`, runs `npm run build` and `npm test`. On failure the previous `dist/` is restored and the service is not restarted.
5. Prints `UPDATE_SUCCEEDED <iso timestamp>` and restarts the service with `sudo -n systemctl restart $SERVICE_NAME` (default `chatgpt-imagegen-mcp.service`).
On error the last line is `UPDATE_FAILED <iso timestamp> ...` and the exit code is non-zero. There are no database migrations: state is plain files on disk.
Run manually: `sudo -u mcp scripts/update.sh >> logs/update.log 2>&1`.
## Endpoint
Enabled only when `UPDATE_TOKEN` is set to a secret of at least 32 characters (otherwise both routes return `503 {"error":"update_not_configured"}`). Authenticate with `Authorization: Bearer $UPDATE_TOKEN`. These routes are not covered by the MCP bearer token.
```bash
curl -X POST -H "Authorization: Bearer $UPDATE_TOKEN" https://host/chatgptimagegen/admin/update
curl -H "Authorization: Bearer $UPDATE_TOKEN" https://host/chatgptimagegen/admin/update/status
```
| Request | Result |
| --- | --- |
| `POST /admin/update` | `202` update started, `409` already running |
| `GET /admin/update/status` | `{ state, startedAt, finishedAt, exitCode, logTail }` |
| missing/wrong token | `401` |
| token not configured | `503` |
| too many requests | `429` with `Retry-After` |
`state` is `idle`, `running`, `succeeded` or `failed`. `logTail` is the last 50 lines of the log.
The script restarts the service at the end, which kills the server process. After the restart the server reads the last log line: if it holds the `UPDATE_SUCCEEDED` (or `UPDATE_FAILED`) marker, status reports `succeeded` (or `failed`) with that timestamp (`startedAt` is null and `exitCode` is synthetic). Poll the status endpoint until it answers again.
## Rate limiting
In memory, per client IP (`req.ip`), reset on restart. Behind nginx set `TRUST_PROXY=1` (or the number of proxy hops) so the real client IP is used; otherwise every request appears to come from nginx.
- `UPDATE_RATE_LIMIT_MAX` (default 30) requests per window, any outcome.
- Failed authentication attempts are limited to 5 per window (or `UPDATE_RATE_LIMIT_MAX` if lower).
- `UPDATE_RATE_LIMIT_WINDOW_SECONDS` (default 900).
## Configuration
| Variable | Default | Purpose |
| --- | --- | --- |
| `UPDATE_TOKEN` | unset (endpoint disabled) | Bearer secret, min 32 chars |
| `UPDATE_SCRIPT` | `<cwd>/scripts/update.sh` | Script run by the endpoint |
| `UPDATE_LOG_FILE` | `<cwd>/logs/update.log` | Appended stdout/stderr of the script |
| `UPDATE_RATE_LIMIT_MAX` | 30 | Requests per window per IP |
| `UPDATE_RATE_LIMIT_WINDOW_SECONDS` | 900 | Window length |
| `TRUST_PROXY` | unset | Express `trust proxy` value |
| `SERVICE_NAME` | `chatgpt-imagegen-mcp.service` | Service restarted by the script |