diff --git a/.github/workflows/test-unit.yml b/.github/workflows/test-unit.yml index 071a4fb..a759420 100644 --- a/.github/workflows/test-unit.yml +++ b/.github/workflows/test-unit.yml @@ -31,11 +31,14 @@ jobs: - name: Checkout uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - - name: Install shellcheck - run: sudo apt-get install -y shellcheck + - name: Install test tools + run: sudo apt-get install -y shellcheck gettext-base - name: Run unit tests run: bash tests/run.sh unit --verbose - name: Run static tests run: bash tests/run.sh static --verbose + + - name: Verify Plunk gateway routing across address changes + run: bash tests/e2e/plunk-gateway.sh diff --git a/.gitignore b/.gitignore index db68b89..557cc29 100644 --- a/.gitignore +++ b/.gitignore @@ -29,3 +29,6 @@ tests/e2e/results/ # Superpowers — specs, plans, working notes. Local only, never committed. docs/superpowers/ + +# Private task tracking (never committed) +priv/ diff --git a/AGENTS.md b/AGENTS.md index fbbc896..51d40d8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,7 +27,7 @@ local/ -> User scripts (deploy, backup, setup) apps// -> App installers (install.sh + README.md) lib/ -> Helper libraries (cli-parser, db-setup, domain-setup, server-exec, port-utils) lib/providers/ -> Provider plugins (mikrus/, generic hooks via detect.sh) -locale/ -> i18n language files (en.sh, pl.sh) — 1325 MSG_* keys each +locale/ -> i18n language files (en.sh, pl.sh) system/ -> System scripts (docker, caddy, backup-core) installers/ -> Template + build.sh for stackpilot.techskills.academy/ oneliner endpoints tests/ -> Test suites (unit/, static/, e2e/) @@ -67,7 +67,7 @@ Provider-specific code lives in `lib/providers//`. Detection is in `li ```bash ./tests/run.sh # unit + static (default) -./tests/run.sh unit # 66 unit tests +./tests/run.sh unit # unit tests ./tests/run.sh static # shellcheck, install contract, compose syntax, locale coverage ./tests/run.sh e2e --ssh=HOST # E2E integration tests on a real server ``` @@ -310,11 +310,11 @@ On the server, the helper is `sp-redirect add|remove|list [ [.caddy`. The main `/etc/caddy/Caddyfile` only contains `import /etc/caddy/conf.d/*.caddy`. Each call to `add-static-hosting.sh`, `add-php-hosting.sh`, or `add-redirect.sh` updates exactly one file in `conf.d/`. -## Applications (37) +## Applications All located in `apps//install.sh`. Run via `deploy.sh`, not directly. -affine, cap, captions-cli, convertx, cookie-hub, coolify, countdown-timer, crawl4ai, dockge, filebrowser, gotenberg, immich, keila, linkstack, listmonk, littlelink, mailstack, mcp-docker, minio, n8n, nocodb, ntfy, picoclaw, postiz, poststack, redis, routepix, sellf, sgtm, social-media-generator, stirling-pdf, supabase, typebot, umami, uptime-kuma, vaultwarden, watchtower, wordpress +affine, cap, captions-cli, convertx, cookie-hub, coolify, countdown-timer, crawl4ai, dockge, filebrowser, gotenberg, immich, keila, ksef-gateway, linkstack, listmonk, littlelink, mailcheap, mailstack, mcp-docker, minio, n8n, nocodb, notifuse, ntfy, picoclaw, plunk, postiz, poststack, redis, routepix, sellf, sgtm, social-media-generator, stirling-pdf, supabase, typebot, umami, uptime-kuma, vaultwarden, watchtower, wordpress Plus static site hosting (Astro, Next.js static export, Hugo, Eleventy, SvelteKit, Gatsby, Docusaurus, VitePress, MkDocs) via `local/deploy-static.sh` — see GUIDE.md. @@ -322,7 +322,7 @@ Details for a specific app (ports, requirements, DB) -> `apps//README.md` o ### Coolify (special flow) -Coolify is a full PaaS (private Heroku) -- **only for servers with 8GB+ RAM and 80GB+ disk**. +Coolify is a full PaaS (private Heroku) -- **only for servers with 4GB+ RAM (enforced by the installer); 8GB RAM and 80GB disk recommended**. Does not use `DOMAIN_TYPE`, `DB_*`, or `/opt/stacks/`. Delegates to the official Coolify installer (`curl | bash`), which installs Docker, Traefik, PostgreSQL, Redis and creates `/data/coolify/`. Takes over ports 80/443 -- **do not mix with other toolbox apps.** @@ -435,15 +435,3 @@ Detailed documentation -> **`GUIDE.md`** (operational reference): Other sources: - `apps//README.md` - per-application details - `docs/CLI-REFERENCE.md` - full CLI parameter reference - -## Active Refactor - -**STATUS:** The refactor plan in `REFACTOR-PLAN.md` tracks the merge of mikrus-toolbox into stackpilot. - -**Completed:** Phase 1 (i18n), Phase 2 (providers), Phase 3 (unit tests), Phase 4 (static validation), Phase 6 (test runner + CI). -**Remaining:** Phase 5 (E2E integration tests), Phase 7 (finalization — archive mikrus-toolbox, production test on Mikrus). - -At the start of every session involving this project, READ `REFACTOR-PLAN.md` first to: -1. Check current progress (look for `- [x]` vs `- [ ]`) -2. Continue from the first uncompleted task -3. Update checkboxes as work is completed diff --git a/GUIDE.md b/GUIDE.md index 42592bd..5a2e228 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -92,6 +92,9 @@ Applications are located in `apps//install.sh`: | **nocodb** | Database (alt. Airtable) | PostgreSQL | 8080 | | **listmonk** | Newsletter and mailing | PostgreSQL* | 9000 | | **mailstack** | Forms and transactional email (profiles a/b/c, see its README) | SQLite or D1 | none (Tunnel) | +| **plunk** | Transactional and marketing email (AWS SES) | Bundled PostgreSQL + Redis + MinIO | 3560 | +| **mailcheap** | Newsletters and API/MCP (local image build required) | Bundled MongoDB | 3000 | +| **notifuse** | Email marketing and transactional email | Bundled PostgreSQL 17 | 8081 | | **keila** | Email marketing (alt. Mailchimp/Brevo) | PostgreSQL | 4500 | | **typebot** | Chatbot builder | PostgreSQL* | 8081/8082 | | **affine** | Knowledge base (alt. Notion/Miro) | PostgreSQL | 3010 | @@ -118,8 +121,9 @@ Applications are located in `apps//install.sh`: | **routepix** | Visualize travel routes from geotagged photos | - | 3000 | | **immich** | Self-hosted photo/video library (alt. Google Photos) | PostgreSQL | 2283 | | **supabase** | Self-hosted PostgreSQL + Auth + Storage + Studio | PostgreSQL | 54321 | -| **coolify** | Full PaaS with 280+ one-click apps (requires 8GB+ RAM) | PostgreSQL | 8000 | +| **coolify** | Full PaaS with 280+ one-click apps (requires 4GB+ RAM, 8GB recommended) | PostgreSQL | 8000 | | **countdown-timer** | Animated countdown GIF generator for emails/web (PHP) | - | 8086 | +| **ksef-gateway** | REST API for Poland's KSeF e-invoicing system | - | 8080 | *PostgreSQL with an asterisk requires `gen_random_uuid()` (PG 13+). Applies to: n8n, umami, listmonk, typebot, postiz, affine. Use `bundled` or a dedicated database (PG 13+). diff --git a/README.md b/README.md index ac95c05..a890308 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ # StackPilot -**The AI-native self-hosting toolkit. Deploy 36+ production-optimized apps plus static sites (Astro, Next.js, Hugo, Eleventy, …) to any VPS — or to Cloudflare Pages — with a single command.** +**The AI-native self-hosting toolkit. Deploy 40+ production-optimized apps plus static sites (Astro, Next.js, Hugo, Eleventy, …) to any VPS — or to Cloudflare Pages — with a single command.** ![License: MIT](https://img.shields.io/badge/License-MIT-green.svg) -![Apps: 36+](https://img.shields.io/badge/Apps-36%2B-blue) +![Apps: 40+](https://img.shields.io/badge/Apps-40%2B-blue) ![Any VPS](https://img.shields.io/badge/Platform-Any%20VPS-orange) [![GitHub Stars](https://img.shields.io/github/stars/jurczykpawel/stackpilot?style=social)](https://github.com/jurczykpawel/stackpilot) @@ -26,7 +26,7 @@ cd stackpilot - **One command, production-ready**: Each app is deployed with a single `deploy.sh` call. Memory limits, log rotation, health checks, security headers, and database provisioning are handled automatically. - **Zero platform overhead**: No web dashboard to maintain, no background services eating RAM. Just Bash scripts, SSH, and Docker. Your server resources go to your apps, not the platform. - **Database flexibility**: Bundled containers (auto-provisioned, zero config) or external databases. WordPress also supports SQLite. Your choice, per app. -- **36+ curated apps**: Not a marketplace of untested community templates. Every app config is tuned and tested for small VPS environments (512MB--2GB RAM). +- **40+ curated apps**: Not a marketplace of untested community templates. Every app config is tuned and tested for small VPS environments (512MB--2GB RAM). --- @@ -86,6 +86,9 @@ cd stackpilot | :--- | :--- | :--- | | [Listmonk](apps/listmonk/) | Mailchimp | High-performance newsletter and mailing list manager. | | [Mailstack](apps/mailstack/) | Web3Forms | Forms and transactional email with an encrypted delivery log; Pro panel and webhooks, on Cloudflare Workers or your server (`--plan=`). | +| [Plunk](apps/plunk/) | SendGrid / Resend | Transactional and marketing email on AWS SES; bundled PostgreSQL, Redis and storage. | +| [MailCheap](apps/mailcheap/) | Mailchimp / beehiiv | Newsletter platform with API/MCP; locally built image and bundled MongoDB. | +| [Notifuse](apps/notifuse/) | Mailchimp / Brevo | Email marketing and transactional email with bundled PostgreSQL. | | [Keila](apps/keila/) | Mailchimp / Brevo | Email marketing platform. Campaigns, newsletters, subscriber management. | | [Typebot](apps/typebot/) | Typeform | Conversational forms and chatbots. Lead capture, surveys. | | [Postiz](apps/postiz/) | Buffer / Hootsuite | Schedule posts to X, LinkedIn, Instagram, Facebook, TikTok. | @@ -127,8 +130,9 @@ cd stackpilot | [Supabase](apps/supabase/) | Firebase / Neon | Self-hosted PostgreSQL + Auth + Storage + Realtime + Studio. | | [MCP Docker](apps/mcp-docker/) | - | Let AI assistants manage Docker containers on your server. | | [sGTM](apps/sgtm/) | - | Server-side Google Tag Manager. 1st-party analytics, reliable tracking without ad blockers. | +| [KSeF Gateway](apps/ksef-gateway/) | - | REST API for Poland's national e-invoicing system (KSeF): send and receive invoices, PDFs with a verification QR code. | | [Countdown Timer](apps/countdown-timer/) | - | Animated countdown GIF generator for emails and landing pages. (PHP, no Docker) | -| [Coolify](apps/coolify/) | Heroku / Vercel / Netlify | Self-hostable PaaS — deploy apps, databases, and services from Git. Requires 8GB+ RAM (takes over ports 80/443). | +| [Coolify](apps/coolify/) | Heroku / Vercel / Netlify | Self-hostable PaaS — deploy apps, databases, and services from Git. Requires 4GB+ RAM, 8GB recommended (takes over ports 80/443). | ### AI and Data @@ -136,8 +140,6 @@ cd stackpilot | :--- | :--- | :--- | | [PicoClaw](apps/picoclaw/) | OpenClaw | Ultra-lightweight AI assistant (Telegram/Discord/Slack). ~10MB image, 64MB RAM. Security-hardened. | | [Crawl4AI](apps/crawl4ai/) | Firecrawl | Web crawler that turns sites into clean Markdown for LLMs and RAG pipelines. | -| [Crawl4AI](apps/crawl4ai/) | ScrapingBee | AI web scraper with REST API. Markdown output, JS rendering. | -| [Coolify](apps/coolify/) | Heroku / Vercel | Full PaaS with 280+ one-click apps. Requires 8GB+ RAM. | > Every app has its own `README.md` with detailed docs, requirements, and configuration options. @@ -422,7 +424,7 @@ Any provider that gives you a Linux VPS with SSH access: Hetzner, DigitalOcean, Yes. Static sites hosted on Mikrus (a $5/month Polish VPS) behind Cloudflare CDN can achieve perfect Lighthouse scores (Performance, Accessibility, Best Practices, SEO — all 100). The key is proper development: defer non-critical resources (fonts, analytics) after `window.load`, avoid CPU-intensive CSS like SVG `feTurbulence`, inline small assets as base64 to eliminate LCP from external network requests, and use `font-display: optional` to prevent font-swap LCP spikes. **How much RAM do I need?** -512MB handles Caddy + 1 lightweight app. 1GB runs n8n + 2--3 smaller services comfortably. 2GB supports a full stack of 10+ apps. Coolify requires 8GB+. +512MB handles Caddy + 1 lightweight app. 1GB runs n8n + 2--3 smaller services comfortably. 2GB supports a full stack of 10+ apps. Coolify requires 4GB+ (8GB recommended). **How do databases work?** Apps that need PostgreSQL or MySQL can use a bundled database container (auto-provisioned, zero config) or connect to an external database you provide. WordPress also supports SQLite for simple sites. @@ -437,7 +439,7 @@ Run `deploy.sh` again. The script detects existing installations and pulls the l Yes. Add your own `apps//install.sh` installer (see GUIDE.md) -- you are not limited to the built-in apps. **How is this different from Coolify?** -Coolify is a full PaaS platform (like a self-hosted Heroku) with a web dashboard, built-in Traefik, and its own PostgreSQL/Redis. It is powerful but heavyweight. StackPilot is minimal: Bash scripts + SSH + Docker. No platform overhead, no web UI to maintain. Note: Coolify itself can be deployed *via* StackPilot on servers with 8GB+ RAM. +Coolify is a full PaaS platform (like a self-hosted Heroku) with a web dashboard, built-in Traefik, and its own PostgreSQL/Redis. It is powerful but heavyweight. StackPilot is minimal: Bash scripts + SSH + Docker. No platform overhead, no web UI to maintain. Note: Coolify itself can be deployed *via* StackPilot on servers with 4GB+ RAM (8GB recommended). --- @@ -445,7 +447,7 @@ Coolify is a full PaaS platform (like a self-hosted Heroku) with a web dashboard ### Completed -- [x] 36+ production-optimized app deployments +- [x] 40+ production-optimized app deployments - [x] CLI deploy with interactive prompts - [x] Caddy auto-HTTPS and Cloudflare DNS integration - [x] Bundled database provisioning (PostgreSQL, MySQL, SQLite) @@ -550,16 +552,22 @@ StackPilot includes a comprehensive test suite: ./tests/run.sh e2e --ssh=your-vps --suite=deploy-no-db ./tests/run.sh e2e --ssh=your-vps --app=ntfy +# Email apps: fresh deployment, HTTP and database persistence across restart +./tests/run.sh e2e --ssh=your-vps --suite=email-apps +# Optional public HTTPS checks through the existing Cloudflare/Caddy flow +./tests/run.sh e2e --ssh=your-vps --suite=email-apps \ + --domain-type=cloudflare --domain-suffix=sp-test.example.com + # Run everything ./tests/run.sh all --ssh=your-vps ``` -| Suite | Tests | Runtime | What it checks | -| :--- | :--- | :--- | :--- | -| Unit | 67 | <1s | CLI parser, i18n, DB setup, domain setup, ports, resources, providers | -| Static | 4 | ~8s | ShellCheck (95 files), install.sh contract, compose syntax, locale coverage | -| E2E (quick) | ~15 | ~15min | Core apps on a real server: deploy, health, cleanup | -| E2E (full) | ~37 | ~45-60min | All 37 apps — auto-skips apps that exceed server resources | +| Suite | What it checks | +| :--- | :--- | +| Unit | CLI parser, i18n, database/domain setup, ports, resources, providers, installer configuration and runner behavior | +| Static | ShellCheck, installer contract, generated Compose syntax and locale coverage | +| E2E (quick/full) | Real-server deployment, health and cleanup across the selected application suites | +| E2E `email-apps` | Fresh deployment, HTTP health and console, optional public HTTPS, database persistence and unchanged credentials across restart | **E2E suites:** @@ -567,6 +575,7 @@ StackPilot includes a comprehensive test suite: | :--- | :--- | :--- | | `deploy-no-db` | ntfy, uptime-kuma, filebrowser, minio, gotenberg, linkstack | SSH access | | `deploy-postgres` | umami, nocodb, listmonk, n8n, typebot, affine, postiz | SSH access | +| `email-apps` | plunk, mailcheap, notifuse; HTTP and DB persistence | Fresh stack names; Plunk SES bootstrap config and prebuilt MailCheap image; optional Cloudflare credentials | | `deploy-mysql` | wordpress | SSH access | | `deploy-tcp` | redis, mcp-docker | SSH access | | `domain-cloudflare` | ntfy, littlelink, cookie-hub | Cloudflare API token | @@ -582,6 +591,8 @@ StackPilot includes a comprehensive test suite: Apps that require more RAM/disk than the server has are automatically **skipped** (not failed). On a 1GB VPS the heavy apps (typebot, affine, postiz, crawl4ai) skip; on a 2-4GB VPS they run. +The `email-apps` suite refuses existing stacks and cleans only resources it created. Public test names are `-` (for example `notifuse-sp-test.example.com`). It does not send emails; complete provider setup and delivery checks separately before using campaigns. See each app README for prerequisites. + CI runs unit + static tests on every push and PR. E2E tests run nightly or on-demand. --- @@ -654,6 +665,6 @@ MIT -- see [LICENSE](LICENSE) for details. --- -*Self-hosted infrastructure toolkit. Deploy 36+ open-source apps (n8n, WordPress, Listmonk, Typebot, NocoDB, Vaultwarden, and more) to any VPS with one command. Replace $300+/month in SaaS subscriptions with a $5/month server.* +*Self-hosted infrastructure toolkit. Deploy 40+ open-source apps (n8n, WordPress, Listmonk, Typebot, NocoDB, Vaultwarden, and more) to any VPS with one command. Replace $300+/month in SaaS subscriptions with a $5/month server.* ![](https://stats.techskills.academy/pixels/github?url=/readme/stackpilot) diff --git a/apps/listmonk/install.sh b/apps/listmonk/install.sh index cd32ea2..70ed4be 100755 --- a/apps/listmonk/install.sh +++ b/apps/listmonk/install.sh @@ -19,7 +19,7 @@ set -e APP_NAME="listmonk" -STACK_DIR="/opt/stacks/$APP_NAME" +STACK_DIR="${STACK_DIR:-/opt/stacks/$APP_NAME}" PORT=${PORT:-9000} echo "--- 📧 Listmonk Setup ---" @@ -135,7 +135,8 @@ sudo docker compose run --rm listmonk ./listmonk --install --yes || echo "Migrat sudo docker compose up -d # Health check -source /opt/stackpilot/lib/health-check.sh 2>/dev/null || true +_HC=/opt/stackpilot/lib/health-check.sh +[ -f "$_HC" ] && source "$_HC" if type wait_for_healthy &>/dev/null; then wait_for_healthy "$APP_NAME" "$PORT" 60 || { echo "❌ Installation failed!"; exit 1; } else @@ -147,16 +148,23 @@ else fi fi -# Enable daily database vacuum (prevents DB bloat) -echo "Enabling daily database vacuum..." -VACUUM_SQL="UPDATE settings SET value='{\"vacuum\": true, \"vacuum_cron_interval\": \"0 2 * * *\"}' WHERE key='maintenance.db';" -{ +# Daily vacuum (prevents DB bloat) and bounce processing (without it the bounce webhook returns 503 and bounces are lost) +echo "Enabling daily database vacuum and bounce processing..." +SETTINGS_SQL="UPDATE settings SET value='{\"vacuum\": true, \"vacuum_cron_interval\": \"0 2 * * *\"}' WHERE key='maintenance.db'; +UPDATE settings SET value='true' WHERE key IN ('bounce.enabled', 'bounce.webhooks_enabled', 'bounce.ses_enabled');" +if { if [ -n "$BUNDLED_DB_TYPE" ]; then - sudo docker compose exec -T db psql -U "$DB_USER" -d "$DB_NAME" -c "$VACUUM_SQL" + sudo docker compose exec -T db psql -U "$DB_USER" -d "$DB_NAME" -c "$SETTINGS_SQL" else - PGPASSWORD="$DB_PASS" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -c "$VACUUM_SQL" + PGPASSWORD="$DB_PASS" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -c "$SETTINGS_SQL" fi -} >/dev/null 2>&1 && echo "✅ Daily vacuum enabled (2:00 AM)" || echo "⚠️ Could not enable vacuum — configure in Settings → Maintenance" +} >/dev/null 2>&1; then + # Listmonk reads settings only at startup. + sudo docker compose restart listmonk >/dev/null + echo "✅ Daily vacuum (2:00 AM) and bounce processing enabled" +else + echo "⚠️ Could not apply settings — enable them in Settings → Maintenance and Settings → Bounces" +fi # Caddy/HTTPS - configure reverse proxy if domain is set if [ -n "$DOMAIN" ]; then diff --git a/apps/mailcheap/Dockerfile b/apps/mailcheap/Dockerfile new file mode 100644 index 0000000..ee42b0b --- /dev/null +++ b/apps/mailcheap/Dockerfile @@ -0,0 +1,21 @@ +FROM node:22-bookworm-slim AS build +WORKDIR /app +COPY package.json package-lock.json ./ +RUN npm ci --no-audit --no-fund +COPY . . +RUN sed -i '/const nextConfig = {/a\ output: "standalone",' next.config.mjs +ENV NEXT_TELEMETRY_DISABLED=1 +RUN npm run build + +FROM node:22-bookworm-slim +ARG SOURCE_REF +LABEL org.opencontainers.image.source="https://github.com/marclou/mailcheap" \ + org.opencontainers.image.revision="$SOURCE_REF" +WORKDIR /app +ENV NODE_ENV=production NEXT_TELEMETRY_DISABLED=1 HOSTNAME=0.0.0.0 PORT=3000 +COPY --from=build --chown=node:node /app/.next/standalone ./ +COPY --from=build --chown=node:node /app/.next/static ./.next/static +COPY --from=build --chown=node:node /app/public ./public +USER node +EXPOSE 3000 +CMD ["node", "server.js"] diff --git a/apps/mailcheap/README.md b/apps/mailcheap/README.md new file mode 100644 index 0000000..611659e --- /dev/null +++ b/apps/mailcheap/README.md @@ -0,0 +1,35 @@ +# MailCheap + +Newsletter editor, archives, contacts and API/MCP, self-hosted without cloud billing. + +Upstream: [marclou/mailcheap](https://github.com/marclou/mailcheap), AGPL-3.0. The installer pins source commit `f8b0b7fbc93ce09c1221c8bdc073b729c0efe237` and bundles MongoDB 7.0.45. Default port: **3000**, app and database memory limits: **512 MiB each**. MongoDB data is kept in a named volume; its port is internal only. + +## Prepare the application image + +Upstream provides Node.js source rather than a published container. Build it **locally** with Docker, then pass the archive to StackPilot’s existing `--build-file` deployment option. No Node build runs on the VPS. + +```bash +# Run from the StackPilot repository; amd64 is the default VPS architecture. +apps/mailcheap/build.sh /tmp/mailcheap-image.tar +./local/deploy.sh mailcheap --build-file=/tmp/mailcheap-image.tar --ssh=vps --domain-type=cloudflare --domain=mail.example.com --yes +``` + +For an ARM64 server, set `PLATFORM=linux/arm64` when building. Building requires enough local disk and RAM for Next.js and its dependencies. A custom `SOURCE_REF` must be a full upstream commit SHA; set the matching `MAILCHEAP_IMAGE=stackpilot/mailcheap:` on the server when running the installer directly, or change the installer's pinned default for a release. + +The existing StackPilot deployment flow handles DNS, Caddy and HTTPS. For tunnel access use `--domain-type=local`; Cytrus uses the existing provider support. Domain setup does not configure the separate sending-domain records required by SES/PostShiba. + +## Configure sign-in and sending + +The installer creates `/opt/stacks/mailcheap/.env` with mode `600` before writing independent random secrets and preserves them on subsequent runs. An incomplete configuration stops installation before containers start; restore its missing keys from backup instead of replacing existing ones. It starts the app with sending disabled. Before the first sign-in, edit this file on the server: + +- `ADMIN_EMAILS`: your administrator email address, optionally `ALLOWED_EMAILS` for other users. +- `EMAIL_FROM`: an address on a domain verified by the sending provider. +- `RESEND_API_KEY` for sign-in codes, or the SES/PostShiba configuration described upstream. Generic SMTP is not supported by this app. + +Apply changes with `cd /opt/stacks/mailcheap && sudo docker compose up -d`, then open `/signin`. An empty allowlist permits nobody to sign in. Container readiness and the installer require `/signin` to return the sign-in page, which initializes the app's database connection; the installer also verifies `/api/health`. These checks do not prove sign-in email delivery or a successful authenticated session. + +Campaign delivery additionally needs SES or PostShiba, its webhook configuration, and Upstash QStash (`QSTASH_TOKEN`, `QSTASH_CURRENT_SIGNING_KEY`, `QSTASH_NEXT_SIGNING_KEY`). QStash calls the app's public HTTPS URL. Complete the [upstream self-hosting guide](https://github.com/marclou/mailcheap#self-hosting), configure sending-domain records, and set `SENDING_ENABLED=true` only when ready. Image uploads optionally use S3 or Vercel Blob; Upstash Redis optionally shares rate limits across instances. + +`APP_URL` follows the domain selected by StackPilot on every install. Auth and suppression keys must remain stable: replacing them invalidates sessions, links in sent emails and suppression hashes. Back up `.env` together with the MongoDB volume. + +MongoDB 7.0 remains supported until August 31, 2027 and runs on the tested VPS kernels. MongoDB 8.x is incompatible with Linux kernels 6.19 through 7.0.13 ([upstream platform notes](https://www.mongodb.com/docs/manual/administration/production-notes/)). Do not change the database major version on an existing data volume without following MongoDB's migration procedure. diff --git a/apps/mailcheap/build.sh b/apps/mailcheap/build.sh new file mode 100755 index 0000000..dfea965 --- /dev/null +++ b/apps/mailcheap/build.sh @@ -0,0 +1,16 @@ +#!/bin/bash +# Build on the operator's computer, never on a small VPS. +set -e +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SOURCE_REF="${SOURCE_REF:-f8b0b7fbc93ce09c1221c8bdc073b729c0efe237}" +PLATFORM="${PLATFORM:-linux/amd64}" +OUTPUT="${1:-$PWD/mailcheap-image.tar}" +case "$SOURCE_REF" in *[!0-9a-f]*|'') echo 'SOURCE_REF must be a full commit SHA.' >&2; exit 1 ;; esac +[ "${#SOURCE_REF}" -eq 40 ] || { echo 'SOURCE_REF must be a full commit SHA.' >&2; exit 1; } +BUILD_DIR=$(mktemp -d) +trap 'rm -rf "$BUILD_DIR"' EXIT +curl -fsSL "https://codeload.github.com/marclou/mailcheap/tar.gz/$SOURCE_REF" | tar -xz --strip-components=1 -C "$BUILD_DIR" +cp "$SCRIPT_DIR/Dockerfile" "$BUILD_DIR/Dockerfile" +docker build --platform "$PLATFORM" --build-arg "SOURCE_REF=$SOURCE_REF" -t "stackpilot/mailcheap:$SOURCE_REF" "$BUILD_DIR" +docker save -o "$OUTPUT" "stackpilot/mailcheap:$SOURCE_REF" +echo "Image archive: $OUTPUT ($PLATFORM); deploy using local/deploy.sh mailcheap --build-file=$OUTPUT." diff --git a/apps/mailcheap/install.sh b/apps/mailcheap/install.sh new file mode 100755 index 0000000..0e9b8a8 --- /dev/null +++ b/apps/mailcheap/install.sh @@ -0,0 +1,114 @@ +#!/bin/bash +# StackPilot - MailCheap +# Newsletter platform with contacts, archives and API/MCP. +# IMAGE_SIZE_MB=1600 +# DB_BUNDLED=true +set -e +APP_NAME="mailcheap" +STACK_DIR="${STACK_DIR:-/opt/stacks/$APP_NAME}" +PORT=${PORT:-3000} +IMAGE="${MAILCHEAP_IMAGE:-stackpilot/mailcheap:f8b0b7fbc93ce09c1221c8bdc073b729c0efe237}" + +if [ -n "${BUILD_FILE:-}" ]; then + [ -f "$BUILD_FILE" ] || { echo 'Error: BUILD_FILE does not exist.' >&2; exit 1; } + sudo docker load -i "$BUILD_FILE" +fi +if ! sudo docker image inspect "$IMAGE" >/dev/null 2>&1; then + echo "Error: build MailCheap locally with apps/mailcheap/build.sh, then sync and load its image on this server (see apps/mailcheap/README.md)." + exit 1 +fi +BIND_ADDR="127.0.0.1:" +[ "${DOMAIN_TYPE:-}" != cytrus ] || BIND_ADDR="" +APP_URL="http://localhost:$PORT" +if [ -n "${DOMAIN:-}" ] && [ "$DOMAIN" != '-' ]; then + APP_URL="https://$DOMAIN" +fi +sudo mkdir -p "$STACK_DIR" +cd "$STACK_DIR" +if [ ! -f .env ]; then + sudo install -m 600 /dev/null .env + cat </dev/null +MONGO_ROOT_PASSWORD=$(openssl rand -hex 24) +BETTER_AUTH_SECRET=$(openssl rand -hex 32) +SUPPRESSION_HASH_KEY=$(openssl rand -hex 32) +CREDENTIALS_ENCRYPTION_KEY=$(openssl rand -base64 32) +CRON_SECRET=$(openssl rand -hex 32) +NODE_ENV=production +MAILCHEAP_CLOUD=false +SENDING_ENABLED=false +ADMIN_EMAILS= +ALLOWED_EMAILS= +EMAIL_FROM= +# Sign-in requires RESEND_API_KEY, or the SES/PostShiba variables from upstream .env.example. +# Campaign delivery additionally requires QSTASH_TOKEN and both QSTASH signing keys. +ENV +fi +sudo chmod 600 .env +for KEY in MONGO_ROOT_PASSWORD BETTER_AUTH_SECRET SUPPRESSION_HASH_KEY CREDENTIALS_ENCRYPTION_KEY CRON_SECRET; do + VALUE=$(sudo awk -v key="$KEY" 'index($0, key "=") == 1 { print substr($0, length(key) + 2); exit }' .env) + if [ "${#VALUE}" -lt 32 ]; then + echo "Error: $KEY is missing or too short in $STACK_DIR/.env. Restore the existing configuration; deployed secrets must remain stable." + exit 1 + fi +done +cat </dev/null +services: + mailcheap: + image: "$IMAGE" + pull_policy: never + restart: unless-stopped + env_file: .env + environment: + APP_URL: "$APP_URL" + PORT: "3000" + HOSTNAME: "0.0.0.0" + MONGODB_URI: "mongodb://root:\${MONGO_ROOT_PASSWORD}@mongo:27017/mailcheap?authSource=admin" + ports: + - "${BIND_ADDR}${PORT}:3000" + depends_on: + mongo: + condition: service_healthy + healthcheck: + test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:3000/signin').then(async r=>process.exit(r.ok&&(await r.text()).includes('Sign in to MailCheap')?0:1)).catch(()=>process.exit(1))"] + interval: 5s + timeout: 5s + start_period: 30s + retries: 12 + deploy: + resources: + limits: + memory: 512M + mongo: + image: mongo:7.0.45 + restart: unless-stopped + environment: + MONGO_INITDB_ROOT_USERNAME: root + MONGO_INITDB_ROOT_PASSWORD: \${MONGO_ROOT_PASSWORD} + command: ["mongod", "--wiredTigerCacheSizeGB", "0.25"] + volumes: + - mongo-data:/data/db + healthcheck: + test: ["CMD", "mongosh", "--quiet", "--eval", "quit(db.adminCommand('ping').ok ? 0 : 1)"] + interval: 5s + timeout: 10s + retries: 20 + deploy: + resources: + limits: + memory: 512M +volumes: + mongo-data: +COMPOSE +sudo docker compose up -d --wait --wait-timeout 180 +if ! curl -fsS --max-time 10 "http://127.0.0.1:$PORT/api/health" >/dev/null; then + echo "Error: MailCheap health check failed." + exit 1 +fi +if ! SIGNIN_HTML=$(curl -fsS --max-time 10 "http://127.0.0.1:$PORT/signin") || [[ "$SIGNIN_HTML" != *'Sign in to MailCheap'* ]]; then + echo "Error: MailCheap sign-in page is not ready." + exit 1 +fi +printf '%s\n' "$PORT" | sudo tee "$STACK_DIR/.stackpilot-port" >/dev/null +echo "MailCheap installed: $APP_URL/signin" +echo "Configure ADMIN_EMAILS, EMAIL_FROM and your sign-in email provider in $STACK_DIR/.env, then run docker compose up -d." +echo "Before campaigns, configure SES/PostShiba and QStash using the upstream self-hosting guide; SENDING_ENABLED stays false until you enable it." diff --git a/apps/notifuse/README.md b/apps/notifuse/README.md new file mode 100644 index 0000000..b523b18 --- /dev/null +++ b/apps/notifuse/README.md @@ -0,0 +1,20 @@ +# Notifuse + +Self-hosted newsletter, transactional email and automation platform (Go + React), with a bundled dedicated PostgreSQL 17 database. Uses the upstream prebuilt `notifuse/notifuse:v42.1` image; no build runs on the VPS. + +```bash +./local/deploy.sh notifuse --ssh=vps --domain-type=cloudflare --domain=mail.example.com --yes +./local/deploy.sh notifuse --ssh=vps --domain-type=local --yes +``` + +The default host port is **8081**. For local access, forward it with `ssh -L 8081:localhost:8081 vps` and open `http://localhost:8081/console`. Domain setup uses StackPilot's existing deployment flow. HTTP binds to localhost except for Cytrus, which requires direct access. PostgreSQL and the optional SMTP bridge have no published ports. + +The installer generates `SECRET_KEY` and `DB_PASSWORD` once in `/opt/stacks/notifuse/.env` (mode 600). Reinstalling preserves them and the persistent named volumes (`postgres-data`, `notifuse-data`); the API endpoint follows the domain passed by `deploy.sh`. An incomplete existing `.env` stops the installer instead of replacing keys. Back up the configuration and both volumes together. Never replace `SECRET_KEY` on its own after saving credentials. + +Open `/console` and complete the upstream setup wizard: root email and SMTP for system emails. Then configure an email sending provider in the workspace. Installing does not send email or configure mail-provider DNS. Configure SPF, DKIM and DMARC according to the chosen provider. The application needs PostgreSQL administrative credentials because each workspace gets its own database; StackPilot bundles an isolated PostgreSQL instance for this reason. + +The compose memory limits are 512 MiB for Notifuse and 256 MiB for PostgreSQL; allow additional RAM for the OS and other applications. The installer waits for both services to become healthy and verifies `/healthz` on the published port before returning success. + +To update, rerun the deployment after reviewing upstream changes and backing up. To select a different application image when running the installer on-server, set `IMAGE_TAG`; do not change the PostgreSQL major version without migrating its data. + +Notifuse v40+ uses Business Source License 1.1 with some paid capabilities; a licence key is optional for the free tier. See the upstream [installation guide](https://docs.notifuse.com/self-hosting/installation), [environment configuration](https://github.com/Notifuse/notifuse/blob/main/env.example), and [licensing](https://github.com/Notifuse/notifuse/blob/main/LICENSING.md). diff --git a/apps/notifuse/install.sh b/apps/notifuse/install.sh new file mode 100755 index 0000000..96b00a6 --- /dev/null +++ b/apps/notifuse/install.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# StackPilot - Notifuse +# Email marketing and transactional email with a dedicated database. +# IMAGE_SIZE_MB=900 +# DB_BUNDLED=true +# https://docs.notifuse.com/self-hosting/installation +set -e + +APP_NAME="notifuse" +STACK_DIR="${STACK_DIR:-/opt/stacks/$APP_NAME}" +PORT=${PORT:-8081} +IMAGE_TAG="${IMAGE_TAG:-v42.1}" + +if [ "${DOMAIN_TYPE:-}" = "cytrus" ]; then + BIND_ADDR="" +else + BIND_ADDR="127.0.0.1:" +fi +if [ -n "${DOMAIN:-}" ] && [ "$DOMAIN" != "-" ]; then + API_ENDPOINT="https://$DOMAIN" +else + API_ENDPOINT="http://localhost:$PORT" +fi + +sudo mkdir -p "$STACK_DIR" +cd "$STACK_DIR" +if [ -f .env ]; then + if ! sudo grep -qE '^SECRET_KEY=.+' .env || ! sudo grep -qE '^DB_PASSWORD=.+' .env; then + echo 'Existing .env is incomplete; restore SECRET_KEY and DB_PASSWORD before redeploying.' >&2 + exit 1 + fi +else + # Set restrictive permissions before writing credentials. + sudo touch .env + sudo chmod 600 .env + cat </dev/null +SECRET_KEY=$(openssl rand -base64 32) +DB_PASSWORD=$(openssl rand -hex 24) +ENV +fi +sudo chmod 600 .env + +cat </dev/null +services: + notifuse: + image: notifuse/notifuse:${IMAGE_TAG} + restart: unless-stopped + ports: + - "${BIND_ADDR}${PORT}:8080" + env_file: .env + environment: + SERVER_HOST: 0.0.0.0 + SERVER_PORT: "8080" + ENVIRONMENT: production + DB_HOST: postgres + DB_PORT: "5432" + DB_USER: postgres + DB_PASSWORD: \${DB_PASSWORD:?DB_PASSWORD required} + DB_PREFIX: notifuse + DB_NAME: notifuse_system + DB_SSLMODE: disable + SECRET_KEY: \${SECRET_KEY:?SECRET_KEY required} + API_ENDPOINT: "${API_ENDPOINT}" + depends_on: + postgres: + condition: service_healthy + volumes: + - notifuse-data:/app/data + healthcheck: + test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/healthz"] + interval: 5s + timeout: 5s + start_period: 30s + retries: 12 + deploy: + resources: + limits: + memory: 512M + postgres: + image: postgres:17-alpine + restart: unless-stopped + environment: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: \${DB_PASSWORD:?DB_PASSWORD required} + POSTGRES_DB: postgres + volumes: + - postgres-data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U postgres -d postgres"] + interval: 5s + timeout: 5s + retries: 12 + deploy: + resources: + limits: + memory: 256M +volumes: + postgres-data: + notifuse-data: +COMPOSE + +sudo docker compose up -d --wait --wait-timeout 180 +printf '%s\n' "$PORT" | sudo tee "$STACK_DIR/.stackpilot-port" >/dev/null +curl --fail --silent --show-error --max-time 10 "http://localhost:$PORT/healthz" >/dev/null +printf 'Notifuse is ready. Open %s/console to complete the setup wizard (admin email and SMTP).\n' "$API_ENDPOINT" +echo 'Keep .env and both data volumes in backups. Configure sending providers in the console.' diff --git a/apps/plunk/README.md b/apps/plunk/README.md new file mode 100644 index 0000000..faf300f --- /dev/null +++ b/apps/plunk/README.md @@ -0,0 +1,53 @@ +# Plunk + +Self-hosted email platform using the upstream `ghcr.io/useplunk/plunk` image, PostgreSQL, Redis, MinIO and ntfy. Nothing is built on the VPS. + +## Install + +Plunk requires AWS SES credentials at startup. Save these in `~/.config/stackpilot/plunk.env` **on the target server**, with mode `600`: + +```bash +AWS_SES_REGION=eu-west-1 +AWS_SES_ACCESS_KEY_ID=your-access-key +AWS_SES_SECRET_ACCESS_KEY=your-secret-key +SES_CONFIGURATION_SET=your-existing-configuration-set +``` + +Then use the normal StackPilot deployment flow: + +```bash +./local/deploy.sh plunk --ssh=vps --domain-type=cloudflare --domain=mail.example.com --yes +``` + +Caddy, Cloudflare DNS, TLS and Cytrus registration are handled by StackPilot. The installer only configures its containers. The default port is `3560`; proxy/local deployments bind to loopback and Cytrus binds to all interfaces. + +Without a domain, open an SSH tunnel: + +```bash +./local/deploy.sh plunk --ssh=vps --domain-type=local --yes +ssh -L 3560:localhost:3560 vps +``` + +New installations set `DISABLE_SIGNUPS=true`. To create the first account, deploy in local mode with the SSH tunnel above, temporarily set `DISABLE_SIGNUPS=false` in `/opt/stacks/plunk/.env` and redeploy in local mode. Open `http://localhost:3560/auth/signup` and create your account. Immediately set `DISABLE_SIGNUPS=true` and redeploy locally before assigning a public domain. Existing `.env` values are preserved, so upgrading an older installation does not change its signup policy. The upstream app does not automatically close signups after the first account. + +## Routing and storage + +The nginx gateway uses Docker DNS to refresh backend addresses, so API, dashboard and upload routes recover after container recreation. Reinstalling validates and reloads an already running gateway before waiting for readiness. This uses nginx's open-source `resolve` support (1.27.3+); the installer pulls the current `nginx:alpine` image. + +One domain serves the dashboard at `/`, API at `/api/` (e.g. `/api/health`), and uploaded assets at `/uploads/`. A bundled nginx gateway removes `/api/` before proxying to the API. Explicit upstream `API_URI` and `DASHBOARD_URI` values keep browser requests on the same origin. PostgreSQL, Redis and MinIO persist in named Docker volumes and are not published on host ports. + +Plunk's upstream SMTP relay ports are not published; use the HTTP API to send mail. The bundled marketing landing page and documentation server are not exposed. + +Secrets persist in `/opt/stacks/plunk/.env` (mode `600`); repeat installs refresh URLs without rotating database, JWT or storage credentials. Back up this file and the three named volumes. To change SES credentials after installation, edit this `.env`; the bootstrap configuration file only supplies the first installation. + +## Requirements + +Budget approximately 2 GB of available RAM and 6 GB of disk for the complete stack; actual usage depends on image version and workload. Container memory limits total about 1.7 GB. Use a larger VPS for sustained campaigns. + +AWS SES must have a verified sending domain and the configured configuration set. Sandbox recipient restrictions and production access remain AWS account settings. Installation/readiness checks do not send email and do not prove delivery. + +`IMAGE_TAG` can pin a published upstream image version when running the installer directly. Standard `deploy.sh` deploys the default upstream `latest` image. + +Upstream references: [Docker deployment](https://github.com/useplunk/plunk/blob/next/apps/wiki/content/docs/self-hosting/docker.mdx), [environment variables](https://github.com/useplunk/plunk/blob/next/apps/wiki/content/docs/self-hosting/environment-variables.mdx), [Compose](https://github.com/useplunk/plunk/blob/next/docker-compose.yml). StackPilot's single-origin gateway adapts upstream's default subdomain routing. + +Gateway regression test (local Docker): `bash tests/e2e/plunk-gateway.sh`. It replaces a backend with a different IP and checks all three URI routes without restarting the gateway. diff --git a/apps/plunk/install.sh b/apps/plunk/install.sh new file mode 100755 index 0000000..307203f --- /dev/null +++ b/apps/plunk/install.sh @@ -0,0 +1,204 @@ +#!/bin/bash +# StackPilot - Plunk +# Transactional and marketing email platform backed by AWS SES. +# IMAGE_SIZE_MB=4500 +# DB_BUNDLED=true +# AWS SES credentials are required; configure .env before deployment. +set -e +APP_NAME="plunk" +STACK_DIR="${STACK_DIR:-/opt/stacks/$APP_NAME}" +PORT=${PORT:-3560} +IMAGE_TAG="${IMAGE_TAG:-latest}" +CONFIG_FILE="${XDG_CONFIG_HOME:-$HOME/.config}/stackpilot/plunk.env" +if [ -f "$CONFIG_FILE" ]; then + set -a + # shellcheck disable=SC1090 + source "$CONFIG_FILE" + set +a +fi +BIND_ADDR="127.0.0.1:" +[ "${DOMAIN_TYPE:-}" != cytrus ] || BIND_ADDR="" +APP_URL="http://localhost:$PORT" +if [ -n "${DOMAIN:-}" ] && [ "$DOMAIN" != - ]; then + [[ "$DOMAIN" =~ ^[a-zA-Z0-9.-]+$ ]] || { echo 'Invalid domain'; exit 1; } + APP_URL="https://$DOMAIN" +fi +sudo mkdir -p "$STACK_DIR" +cd "$STACK_DIR" +if ! sudo test -f .env; then + umask 077 + sudo touch .env + sudo chmod 600 .env + cat </dev/null +DB_PASSWORD=$(openssl rand -hex 24) +JWT_SECRET=$(openssl rand -hex 32) +MINIO_ROOT_PASSWORD=$(openssl rand -hex 24) +AWS_SES_REGION=${AWS_SES_REGION:-} +AWS_SES_ACCESS_KEY_ID=${AWS_SES_ACCESS_KEY_ID:-} +AWS_SES_SECRET_ACCESS_KEY=${AWS_SES_SECRET_ACCESS_KEY:-} +SES_CONFIGURATION_SET=${SES_CONFIGURATION_SET:-plunk-tracking} +DISABLE_SIGNUPS=true +ENV +fi +sudo chmod 600 .env +for key in DB_PASSWORD JWT_SECRET MINIO_ROOT_PASSWORD AWS_SES_REGION AWS_SES_ACCESS_KEY_ID AWS_SES_SECRET_ACCESS_KEY; do + if ! sudo grep -qE "^${key}=.+" .env; then + echo "Configure $key in $STACK_DIR/.env, then run deploy.sh plunk again." + exit 1 + fi +done +# Refresh public URLs while keeping all persisted credentials. +ENV_TMP=$(mktemp) +trap 'rm -f "$ENV_TMP"' EXIT +sudo cat .env | awk '!/^(API_URI|DASHBOARD_URI|LANDING_URI|WIKI_URI|S3_PUBLIC_URL)=/' > "$ENV_TMP" +cat >> "$ENV_TMP" </dev/null +sudo chmod 600 .env +cat <<'NGINX' | sudo tee nginx.conf >/dev/null +resolver 127.0.0.11 valid=5s ipv6=off; +upstream plunk_api { zone plunk_api 64k; server plunk:8080 resolve; } +upstream plunk_web { zone plunk_web 64k; server plunk:3000 resolve; } +upstream plunk_uploads { zone plunk_uploads 64k; server minio:9000 resolve; } +server { + listen 80; + server_name _; + client_max_body_size 40M; + 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 $http_x_forwarded_proto; + location /api/ { proxy_pass http://plunk_api/; } + location /uploads/ { proxy_pass http://plunk_uploads/uploads/; } + location / { proxy_pass http://plunk_web; } +} +NGINX +cat </dev/null +services: + gateway: + image: nginx:alpine + restart: unless-stopped + ports: + - "${BIND_ADDR}${PORT}:80" + volumes: + - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro + depends_on: + plunk: + condition: service_healthy + healthcheck: + test: ["CMD-SHELL", "wget -qO- http://127.0.0.1/api/health >/dev/null && wget -qO- http://127.0.0.1/auth/login >/dev/null"] + interval: 10s + timeout: 5s + retries: 12 + deploy: + resources: + limits: + memory: 32M + plunk: + image: ghcr.io/useplunk/plunk:${IMAGE_TAG} + restart: unless-stopped + env_file: .env + environment: + SERVICE: all + NODE_ENV: production + DATABASE_URL: postgresql://plunk:\${DB_PASSWORD}@postgres:5432/plunk + DIRECT_DATABASE_URL: postgresql://plunk:\${DB_PASSWORD}@postgres:5432/plunk + REDIS_URL: redis://redis:6379 + S3_ENDPOINT: http://minio:9000 + S3_ACCESS_KEY_ID: plunk + S3_ACCESS_KEY_SECRET: \${MINIO_ROOT_PASSWORD} + S3_BUCKET: uploads + S3_FORCE_PATH_STYLE: "true" + NTFY_URL: http://ntfy/plunk-notifications + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + minio: + condition: service_started + healthcheck: + test: ["CMD", "curl", "-f", "http://127.0.0.1:8080/health"] + interval: 10s + timeout: 5s + start_period: 120s + retries: 18 + deploy: + resources: + limits: + memory: 1024M + postgres: + image: postgres:16-alpine + restart: unless-stopped + environment: + POSTGRES_USER: plunk + POSTGRES_DB: plunk + POSTGRES_PASSWORD: \${DB_PASSWORD} + volumes: + - postgres_data:/var/lib/postgresql/data + healthcheck: + test: ["CMD", "pg_isready", "-U", "plunk"] + interval: 5s + timeout: 5s + retries: 12 + deploy: + resources: + limits: + memory: 192M + redis: + image: redis:7-alpine + restart: unless-stopped + command: redis-server --appendonly yes --maxmemory 48mb --maxmemory-policy noeviction + volumes: + - redis_data:/data + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 5s + retries: 12 + deploy: + resources: + limits: + memory: 96M + minio: + image: pgsty/minio:RELEASE.2026-08-04T00-00-00Z + restart: unless-stopped + command: server /data + environment: + MINIO_ROOT_USER: plunk + MINIO_ROOT_PASSWORD: \${MINIO_ROOT_PASSWORD} + volumes: + - minio_data:/data + deploy: + resources: + limits: + memory: 256M + ntfy: + image: binwiederhier/ntfy:latest + restart: unless-stopped + command: serve + deploy: + resources: + limits: + memory: 64M +volumes: + postgres_data: + redis_data: + minio_data: +COMPOSE +sudo docker compose pull +if [ -n "$(sudo docker compose ps --status running -q gateway)" ]; then + sudo docker compose exec -T gateway nginx -t + sudo docker compose exec -T gateway nginx -s reload +fi +sudo docker compose up -d --wait --wait-timeout 360 +printf '%s\n' "$PORT" | sudo tee "$STACK_DIR/.stackpilot-port" >/dev/null +echo "Plunk ready: $APP_URL/auth/login" +echo 'Signups are closed. Bootstrap the first account in local SSH-tunnel mode; see apps/plunk/README.md.' +echo 'Configure a verified AWS SES sending domain and configuration set before sending email.' diff --git a/lib/db-setup.sh b/lib/db-setup.sh index b519e65..691d3be 100644 --- a/lib/db-setup.sh +++ b/lib/db-setup.sh @@ -220,8 +220,16 @@ setup_bundled_db() { BUNDLED_DB_TYPE="$DB_TYPE" - # Generate random credentials - DB_PASS=$(openssl rand -base64 24 | tr -dc 'A-Za-z0-9' | head -c 24) + # Re-install: the existing db-data volume keeps its original password, so reuse it. + local existing_pass="" + if [ -n "${APP_NAME:-}" ]; then + existing_pass=$(server_exec "grep -m1 -E '^ *(POSTGRES|MYSQL)_PASSWORD:' '/opt/stacks/$APP_NAME/docker-compose.yaml' 2>/dev/null | sed 's/^[^:]*: *//'" 2>/dev/null | tr -d '[:space:]') || existing_pass="" + fi + if [[ "$existing_pass" =~ ^[A-Za-z0-9]{8,}$ ]]; then + DB_PASS="$existing_pass" + else + DB_PASS=$(openssl rand -base64 24 | tr -dc 'A-Za-z0-9' | head -c 24) + fi DB_USER="app" DB_NAME="appdb" diff --git a/lib/port-utils.sh b/lib/port-utils.sh index 56804b3..14ad04d 100644 --- a/lib/port-utils.sh +++ b/lib/port-utils.sh @@ -53,6 +53,15 @@ find_free_port_remote() { echo "$port" } +# Read the published host port saved by an installer, with legacy env fallback. +read_existing_app_port() { + local marker="$1" legacy_env="$2" port + port=$(server_exec_timeout 5 "if [ -f '$marker' ]; then cat '$marker'; else grep -m1 '^PORT=' '$legacy_env' 2>/dev/null | cut -d= -f2; fi" 2>/dev/null) || return 1 + [[ "$port" =~ ^[1-9][0-9]{0,4}$ ]] && [ "$port" -le 65535 ] || return 1 + printf '%s\n' "$port" +} + # Export functions export -f find_free_port export -f find_free_port_remote +export -f read_existing_app_port diff --git a/lib/server-exec.sh b/lib/server-exec.sh index 1564373..ca38135 100644 --- a/lib/server-exec.sh +++ b/lib/server-exec.sh @@ -15,7 +15,8 @@ # i18n _SE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -if [ -z "${TOOLBOX_LANG+x}" ]; then +# Child processes inherit TOOLBOX_LANG, but locale messages are shell-local. +if [ -z "${MSG_SE_INSTALLING_TOOLBOX+x}" ]; then source "$_SE_DIR/i18n.sh" fi diff --git a/local/deploy.sh b/local/deploy.sh index 0849dcd..5018a71 100755 --- a/local/deploy.sh +++ b/local/deploy.sh @@ -71,7 +71,7 @@ Modes: --dry-run Show what would be executed without running --update Update existing application (instead of installing) --restart Restart without updating (e.g. after .env change) - used with --update - --build-file=PATH Use local tar.gz file (for --update, when repo is private) + --build-file=PATH Local Sellf build or MailCheap Docker image archive --help, -h Show this help Examples: @@ -106,6 +106,9 @@ Examples: # Update from local file (when repo is private) ./local/deploy.sh sellf --ssh=vps --update --build-file=~/Downloads/sellf-build.tar.gz + # Install MailCheap from a locally built Docker image + ./local/deploy.sh mailcheap --ssh=vps --build-file=/tmp/mailcheap-image.tar --domain-type=local --yes + # Restart without updating (e.g. after .env change) ./local/deploy.sh sellf --ssh=vps --update --restart @@ -601,8 +604,8 @@ fi DEFAULT_PORT=$(grep -E "^PORT=" "$SCRIPT_PATH" 2>/dev/null | head -1 | sed -E 's/.*[=:-]([0-9]+).*/\1/') PORT_OVERRIDE="" -if [ -n "$DEFAULT_PORT" ]; then - # For re-deploys: if an existing .env.local already has a PORT, reuse it. +if [ -n "$DEFAULT_PORT" ] && ! grep -qx '# PORT_MANAGED=true' "$SCRIPT_PATH"; then + # Reuse the installer host-port marker, with Sellf .env.local fallback. # This avoids picking a different port when the old process still holds the # original port (it will be stopped by install.sh before Docker/PM2 starts). # Derive INSTALL_DIR using the same logic as install.sh (domain → instance name). @@ -612,7 +615,7 @@ if [ -n "$DEFAULT_PORT" ]; then else _EXISTING_ENV="/opt/stacks/${APP_NAME}/admin-panel/.env.local" fi - _EXISTING_PORT=$(server_exec_timeout 5 "grep -m1 '^PORT=' '$_EXISTING_ENV' 2>/dev/null | cut -d= -f2" 2>/dev/null | tr -d '[:space:]') + _EXISTING_PORT=$(read_existing_app_port "/opt/stacks/$APP_NAME/.stackpilot-port" "$_EXISTING_ENV") || _EXISTING_PORT="" if [ -n "$_EXISTING_PORT" ] && [ "$_EXISTING_PORT" != "$DEFAULT_PORT" ]; then # Re-deploy with a previously assigned non-default port — preserve it @@ -646,7 +649,7 @@ DB_ENV_VARS="" DB_TYPE="" NEEDS_DB=false NEEDS_DOMAIN=false -APP_PORT="" +APP_PORT="$DEFAULT_PORT" # Check if application requires a database # WordPress with WP_DB_MODE=sqlite does not need MySQL @@ -1004,7 +1007,11 @@ if [ "$DRY_RUN" = true ]; then fi # Auto-install Docker if missing (skip for sellf pm2 mode — doesn't need Docker) -if [ "$APP_NAME" != "sellf" ] || [ "${RUNTIME:-pm2}" = "docker" ]; then +DOCKER_REQUIRED=true +if grep -qx '# DOCKER_REQUIRED=false' "$SCRIPT_PATH"; then + DOCKER_REQUIRED=false +fi +if [ "$DOCKER_REQUIRED" = true ] && { [ "$APP_NAME" != "sellf" ] || [ "${RUNTIME:-pm2}" = "docker" ]; }; then if ! server_exec "command -v docker >/dev/null 2>&1"; then echo "" msg "$MSG_DOCKER_MISSING" @@ -1277,8 +1284,9 @@ if [ -n "$POST_RAM_TOTAL" ] && [ "$POST_RAM_TOTAL" -gt 0 ] 2>/dev/null && \ printf "║ %s\n" "$MSG_HEALTH_HEADER" echo "╚════════════════════════════════════════════════════════════════╝" echo "" - msg "$MSG_HEALTH_RAM" "$POST_RAM_AVAIL" "$POST_RAM_TOTAL" "$RAM_USED_PCT" "$RAM_LABEL" - msg "$MSG_HEALTH_DISK" "$DISK_AVAIL_GB" "$DISK_TOTAL_GB" "$DISK_USED_PCT" "$DISK_LABEL" + # Labels carry \033 colour codes; %s arguments are not escape-interpreted. + msg "$MSG_HEALTH_RAM" "$POST_RAM_AVAIL" "$POST_RAM_TOTAL" "$RAM_USED_PCT" "$(printf '%b' "$RAM_LABEL")" + msg "$MSG_HEALTH_DISK" "$DISK_AVAIL_GB" "$DISK_TOTAL_GB" "$DISK_USED_PCT" "$(printf '%b' "$DISK_LABEL")" echo "" if [ "$HEALTH_LEVEL" -eq 0 ]; then diff --git a/locale/en.sh b/locale/en.sh index 4769a55..7c96660 100644 --- a/locale/en.sh +++ b/locale/en.sh @@ -1398,14 +1398,14 @@ MSG_CADDY_DONE_USAGE=" Usage: sp-expose app.domain.com 5000" # ── system/docker-setup.sh ─────────────────────────────────── MSG_DOCKER_MISSING="🐳 Docker not found — installing automatically..." MSG_DOCKER_INSTALL_FAILED="❌ Docker installation failed. Install Docker manually: curl -fsSL https://get.docker.com | sh" -MSG_DOCKER_STEP1="--- 1. Running official NOOBS Docker installation ---" +MSG_DOCKER_STEP1="--- 1. Installing Docker engine ---" MSG_DOCKER_STEP2="--- 2. Applying VPS-specific optimizations (Log Rotation) ---" MSG_DOCKER_STEP3="--- 3. Restarting Docker to apply changes ---" MSG_DOCKER_STEP4="--- 4. Verifying settings ---" MSG_DOCKER_CONFIG_HDR="Docker configuration (/etc/docker/daemon.json):" MSG_DOCKER_LOG_DRV="Logging Driver: %s" MSG_DOCKER_LIVE_RESTORE="Live Restore: %s" -MSG_DOCKER_DONE="✅ Docker is installed (via NOOBS) and optimized for your VPS!" +MSG_DOCKER_DONE="✅ Docker is installed and optimized for your VPS!" MSG_DOCKER_STORAGE_RETRY="⚙️ Docker storage error detected — restarting daemon and retrying..." # ── system/pm2-setup.sh ─────────────────────────────────────── diff --git a/locale/pl.sh b/locale/pl.sh index d89b1b4..9b28a78 100644 --- a/locale/pl.sh +++ b/locale/pl.sh @@ -1397,14 +1397,14 @@ MSG_CADDY_DONE_USAGE=" Użycie: sp-expose app.domena.pl 5000" # ── system/docker-setup.sh ─────────────────────────────────── MSG_DOCKER_MISSING="🐳 Docker nie znaleziony — instaluję automatycznie..." MSG_DOCKER_INSTALL_FAILED="❌ Instalacja Dockera nie powiodła się. Zainstaluj ręcznie: curl -fsSL https://get.docker.com | sh" -MSG_DOCKER_STEP1="--- 1. Uruchamianie oficjalnej instalacji Docker (NOOBS) ---" +MSG_DOCKER_STEP1="--- 1. Instalowanie silnika Docker ---" MSG_DOCKER_STEP2="--- 2. Stosowanie optymalizacji VPS (rotacja logów) ---" MSG_DOCKER_STEP3="--- 3. Restartowanie Dockera w celu zastosowania zmian ---" MSG_DOCKER_STEP4="--- 4. Weryfikacja ustawień ---" MSG_DOCKER_CONFIG_HDR="Konfiguracja Docker (/etc/docker/daemon.json):" MSG_DOCKER_LOG_DRV="Sterownik logowania: %s" MSG_DOCKER_LIVE_RESTORE="Live Restore: %s" -MSG_DOCKER_DONE="✅ Docker zainstalowany (przez NOOBS) i zoptymalizowany dla Twojego VPS!" +MSG_DOCKER_DONE="✅ Docker zainstalowany i zoptymalizowany dla Twojego VPS!" MSG_DOCKER_STORAGE_RETRY="⚙️ Wykryto błąd storage Dockera — restartuję daemon i powtarzam..." # ── system/pm2-setup.sh ─────────────────────────────────────── diff --git a/system/docker-setup.sh b/system/docker-setup.sh index 843f368..0c8ec95 100755 --- a/system/docker-setup.sh +++ b/system/docker-setup.sh @@ -1,10 +1,10 @@ #!/bin/bash -# StackPilot - Docker Setup (Based on NOOBS) -# This script uses the official 'noobs' script approved by the hosting provider -# and adds a layer of log rotation optimization. +# StackPilot - Docker Setup +# Uses the vendor installer on Debian and the provider installer on Ubuntu. set -e +set -o pipefail _DOCKER_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" 2>/dev/null && pwd)" if [ -z "${TOOLBOX_LANG+x}" ]; then @@ -18,15 +18,34 @@ if [ -z "${TOOLBOX_LANG+x}" ]; then fi fi -msg "$MSG_DOCKER_STEP1" -curl -s https://raw.githubusercontent.com/unkn0w/noobs/main/scripts/chce_dockera.sh | bash +install_docker_for_distribution() { + local distribution="$1" + if [ "$distribution" = debian ]; then + local installer status=0 + installer=$(mktemp) + if ! curl -fsSL https://get.docker.com -o "$installer"; then + rm "$installer" + return 1 + fi + bash "$installer" || status=$? + rm "$installer" + return "$status" + fi + curl -fsSL https://raw.githubusercontent.com/unkn0w/noobs/main/scripts/chce_dockera.sh | bash +} + +docker_setup_main() { + msg "$MSG_DOCKER_STEP1" + local distribution + distribution="$(. /etc/os-release; printf '%s' "$ID")" + install_docker_for_distribution "$distribution" -msg "$MSG_DOCKER_STEP2" -# Creating/Updating daemon.json to prevent disk exhaustion -# max-size=10m and max-file=3 ensures Docker logs never exceed 30MB per container. + msg "$MSG_DOCKER_STEP2" + # Creating/Updating daemon.json to prevent disk exhaustion + # max-size=10m and max-file=3 ensures Docker logs never exceed 30MB per container. -sudo mkdir -p /etc/docker -cat <&2; exit 2 ;; + esac +done +case "$DOMAIN_TYPE" in local|cloudflare) ;; *) echo 'Domain type must be local or cloudflare' >&2; exit 2 ;; esac +if [ -n "$DOMAIN_SUFFIX" ]; then + [[ "$DOMAIN_SUFFIX" =~ ^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$ ]] && [ "${#DOMAIN_SUFFIX}" -lt 240 ] || { echo 'Invalid domain suffix' >&2; exit 2; } +fi +if [ "$DOMAIN_TYPE" = cloudflare ]; then + [ -n "$DOMAIN_SUFFIX" ] || { echo 'Cloudflare requires --domain-suffix' >&2; exit 2; } + command -v dig >/dev/null || { echo 'dig required for domain preflight' >&2; exit 2; } +fi +case "$APP_FILTER" in ''|notifuse|mailcheap|plunk) ;; *) echo 'Unknown email app' >&2; exit 2 ;; esac +case "$CLEANUP" in always|never) ;; *) echo 'Cleanup must be always or never' >&2; exit 2 ;; esac +[ -n "$SSH_HOST" ] && [[ "$SSH_HOST" != -* ]] || { echo '--ssh=HOST required' >&2; exit 2; } +RESULTS_DIR="${E2E_RESULTS_DIR:-$E2E_DIR/results}" +mkdir -p "$RESULTS_DIR" +printf 'TAP version 13\n' > "$RESULTS_DIR/results.tap" +RUN_TOKEN=$(openssl rand -hex 16) +OWNED_APP="" +OWNED_DOMAIN="" +cleanup_owned() { + [ -n "$OWNED_APP" ] || return 0 + if [ "$CLEANUP" = never ]; then + echo "Keeping owned stack: $OWNED_APP ($RUN_TOKEN)" + return 0 + fi + ssh "$SSH_HOST" "set -e; cd '/opt/stacks/$OWNED_APP'; sudo grep -qx '$RUN_TOKEN' .stackpilot-e2e-owner; if [ -f docker-compose.yaml ]; then sudo docker compose down -v; fi" || return 1 + if [ -n "$OWNED_DOMAIN" ]; then + (source "$E2E_DIR/lib/assertions.sh"; E2E_SSH="$SSH_HOST"; cf_dns_delete "$OWNED_DOMAIN" && caddy_cleanup "$OWNED_DOMAIN") || return 1 + fi + ssh "$SSH_HOST" "set -e; cd '/opt/stacks/$OWNED_APP'; sudo grep -qx '$RUN_TOKEN' .stackpilot-e2e-owner; cd /; sudo rm -rf '/opt/stacks/$OWNED_APP'" || return 1 + OWNED_APP="" + OWNED_DOMAIN="" +} +EXIT_CODE=0 +trap 'EXIT_CODE=$?; cleanup_owned || EXIT_CODE=1; exit "$EXIT_CODE"' EXIT +trap 'exit 1' INT TERM + +run_app() { + local app="$1" service inner health console expected port first_hash + case "$app" in + notifuse) service=notifuse; inner=8080; health=/healthz; console=/console; expected='Notifuse' ;; + mailcheap) service=mailcheap; inner=3000; health=/api/health; console=/signin; expected='MailCheap' ;; + plunk) service=gateway; inner=80; health=/api/health; console=/auth/login; expected='Plunk' ;; + esac + local domain="" domain_args=("--domain-type=$DOMAIN_TYPE") existing_dns + if [ "$DOMAIN_TYPE" = cloudflare ]; then + domain="$app-$DOMAIN_SUFFIX" + existing_dns=$(dig @1.1.1.1 +short "$domain" A && dig @1.1.1.1 +short "$domain" AAAA && dig @1.1.1.1 +short "$domain" CNAME) || return 1 + [ -z "$existing_dns" ] || { echo "Domain already resolves: $domain" >&2; return 1; } + domain_args+=("--domain=$domain") + fi + # Atomic reservation; existing containers or volumes also stop this run. + if ! ssh "$SSH_HOST" "set -e; test ! -e '/opt/stacks/$app'; if [ -n '$domain' ]; then test ! -e '/etc/caddy/conf.d/$domain.caddy'; fi; if command -v docker >/dev/null 2>&1; then test -z \"\$(sudo docker ps -aq --filter label=com.docker.compose.project=$app)\"; test -z \"\$(sudo docker volume ls -q --filter label=com.docker.compose.project=$app)\"; fi; sudo mkdir -p /opt/stacks; sudo mkdir '/opt/stacks/$app'; echo '$RUN_TOKEN' | sudo tee '/opt/stacks/$app/.stackpilot-e2e-owner' >/dev/null"; then + echo "Refusing to use an existing stack or unavailable server: $app" >&2 + return 1 + fi + OWNED_APP="$app" + OWNED_DOMAIN="$domain" + if [ "$app" = plunk ]; then + ssh "$SSH_HOST" 'test -s ~/.config/stackpilot/plunk.env' || { echo 'Plunk requires remote ~/.config/stackpilot/plunk.env' >&2; return 1; } + fi + "$REPO_ROOT/local/deploy.sh" "$app" --ssh="$SSH_HOST" "${domain_args[@]}" --yes || return 1 + port=$(ssh "$SSH_HOST" "cd '/opt/stacks/$app'; sudo docker compose port '$service' '$inner'" | tail -1 | sed 's/.*://') || return 1 + [[ "$port" =~ ^[0-9]+$ ]] || return 1 + ssh "$SSH_HOST" "set -o pipefail; curl -fsS --max-time 15 'http://127.0.0.1:$port$health' >/dev/null && curl -fsSL --max-time 15 'http://127.0.0.1:$port$console' | grep -i '$expected' >/dev/null" || return 1 + check_public "$domain" "$health" "$console" "$expected" || return 1 + first_hash=$(ssh "$SSH_HOST" "sudo sha256sum '/opt/stacks/$app/.env'" | cut -d' ' -f1) || return 1 + case "$app" in + notifuse|plunk) + local dbuser=postgres dbname=postgres dbservice=postgres + [ "$app" != plunk ] || { dbuser=plunk; dbname=plunk; } + ssh "$SSH_HOST" "cd '/opt/stacks/$app'; sudo docker compose exec -T '$dbservice' psql -U '$dbuser' -d '$dbname' -v ON_ERROR_STOP=1 -c \"CREATE TABLE stackpilot_e2e_probe (value text); INSERT INTO stackpilot_e2e_probe VALUES ('$RUN_TOKEN');\"" >/dev/null || return 1 + ;; + mailcheap) + ssh "$SSH_HOST" "cd '/opt/stacks/$app'; sudo docker compose exec -T mongo sh -c 'mongosh --quiet \"mongodb://127.0.0.1:27017/mailcheap?serverSelectionTimeoutMS=20000&connectTimeoutMS=20000\" -u root -p \"\$MONGO_INITDB_ROOT_PASSWORD\" --authenticationDatabase admin --eval '\"'\"'db.stackpilot_e2e_probe.insertOne({value: \"$RUN_TOKEN\"})'\"'\"''" >/dev/null || return 1 + ;; + esac + ssh "$SSH_HOST" "cd '/opt/stacks/$app'; sudo docker compose restart && sudo docker compose up -d --wait --wait-timeout 360" || return 1 + [ "$first_hash" = "$(ssh "$SSH_HOST" "sudo sha256sum '/opt/stacks/$app/.env'" | cut -d' ' -f1)" ] || return 1 + case "$app" in + notifuse|plunk) + ssh "$SSH_HOST" "cd '/opt/stacks/$app'; sudo docker compose exec -T '$dbservice' psql -U '$dbuser' -d '$dbname' -tAc 'SELECT value FROM stackpilot_e2e_probe'" | grep -qx "$RUN_TOKEN" || return 1 + ;; + mailcheap) + ssh "$SSH_HOST" "cd '/opt/stacks/$app'; sudo docker compose exec -T mongo sh -c 'mongosh --quiet \"mongodb://127.0.0.1:27017/mailcheap?serverSelectionTimeoutMS=20000&connectTimeoutMS=20000\" -u root -p \"\$MONGO_INITDB_ROOT_PASSWORD\" --authenticationDatabase admin --eval '\"'\"'print(db.stackpilot_e2e_probe.findOne().value)'\"'\"''" | grep -qx "$RUN_TOKEN" || return 1 + ;; + esac + ssh "$SSH_HOST" "set -o pipefail; curl -fsS --max-time 15 'http://127.0.0.1:$port$health' >/dev/null" || return 1 + check_public "$domain" "$health" "$console" "$expected" || return 1 + cleanup_owned || return 1 +} + +check_public() { + [ -n "$1" ] || return 0 + curl -fsS --max-time 15 --retry 12 --retry-delay 5 --retry-max-time 90 --retry-all-errors "https://$1$2" >/dev/null || return 1 + curl -fsSL --max-time 15 "https://$1$3" | grep -i "$4" >/dev/null +} + +APPS=(notifuse mailcheap plunk) +[ -z "$APP_FILTER" ] || APPS=("$APP_FILTER") +FAILED=0 +INDEX=0 +for app in "${APPS[@]}"; do + INDEX=$((INDEX + 1)) + if run_app "$app"; then + echo "ok $INDEX - $app: deploy, HTTP and database persistence" | tee -a "$RESULTS_DIR/results.tap" + else + echo "not ok $INDEX - $app: deployment or persistence failed" | tee -a "$RESULTS_DIR/results.tap" + FAILED=1 + if [ -n "$OWNED_APP" ]; then + ssh "$SSH_HOST" "cd '/opt/stacks/$OWNED_APP' && sudo grep -qx '$RUN_TOKEN' .stackpilot-e2e-owner && sudo docker compose ps && sudo docker compose logs --tail 30" || true + fi + cleanup_owned || exit 1 + fi + OWNED_APP="" +done +printf '1..%s\n' "$INDEX" >> "$RESULTS_DIR/results.tap" +exit "$FAILED" diff --git a/tests/e2e/plunk-gateway.sh b/tests/e2e/plunk-gateway.sh new file mode 100755 index 0000000..7b82926 --- /dev/null +++ b/tests/e2e/plunk-gateway.sh @@ -0,0 +1,56 @@ +#!/bin/bash +# Local Docker integration: gateway routing survives backend address changes. +set -euo pipefail +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +DOCKER=$(command -v docker) +TEST_DIR=$(mktemp -d) +PREFIX="stackpilot-plunk-gateway-test-$$" +cleanup() { + "$DOCKER" rm -f "$PREFIX-gateway" "$PREFIX-backend" "$PREFIX-blocker" >/dev/null 2>&1 || true + "$DOCKER" network rm "$PREFIX" >/dev/null 2>&1 || true + rm -rf "$TEST_DIR" +} +trap cleanup EXIT +mkdir -p "$TEST_DIR/bin" +printf '#!/bin/bash\nexec "$@"\n' > "$TEST_DIR/bin/sudo" +printf '#!/bin/bash\nexit 0\n' > "$TEST_DIR/bin/docker" +chmod +x "$TEST_DIR/bin/"* +PATH="$TEST_DIR/bin:$PATH" STACK_DIR="$TEST_DIR/stack" XDG_CONFIG_HOME="$TEST_DIR/config" \ + AWS_SES_REGION=eu-west-1 AWS_SES_ACCESS_KEY_ID=test-key AWS_SES_SECRET_ACCESS_KEY=test-secret \ + bash "$REPO_ROOT/apps/plunk/install.sh" >/dev/null +cat > "$TEST_DIR/backend.conf" <<'NGINX' +server { listen 8080; return 200 "$server_port:$request_uri"; } +server { listen 3000; return 200 "$server_port:$request_uri"; } +server { listen 9000; return 200 "$server_port:$request_uri"; } +NGINX +"$DOCKER" image inspect nginx:alpine >/dev/null 2>&1 || "$DOCKER" pull nginx:alpine >/dev/null +"$DOCKER" network create "$PREFIX" >/dev/null +start_backend() { + "$DOCKER" run -d --name "$PREFIX-backend" --network "$PREFIX" --network-alias plunk --network-alias minio \ + -v "$TEST_DIR/backend.conf:/etc/nginx/conf.d/default.conf:ro" nginx:alpine >/dev/null +} +check_routes() { + "$DOCKER" exec "$PREFIX-gateway" sh -c ' + for attempt in $(seq 1 30); do + api=$(wget -qO- http://127.0.0.1/api/health 2>/dev/null) || api="" + web=$(wget -qO- http://127.0.0.1/auth/login 2>/dev/null) || web="" + asset=$(wget -qO- http://127.0.0.1/uploads/example.png 2>/dev/null) || asset="" + if [ "$api" = "8080:/health" ] && [ "$web" = "3000:/auth/login" ] && [ "$asset" = "9000:/uploads/example.png" ]; then exit 0; fi + sleep 1 + done + echo "Unexpected responses: api=$api web=$web asset=$asset" >&2 + exit 1 + ' +} +start_backend +"$DOCKER" run -d --name "$PREFIX-gateway" --network "$PREFIX" \ + -v "$TEST_DIR/stack/nginx.conf:/etc/nginx/conf.d/default.conf:ro" nginx:alpine >/dev/null +check_routes +OLD_IP=$("$DOCKER" inspect "$PREFIX-backend" --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}') +"$DOCKER" rm -f "$PREFIX-backend" >/dev/null +"$DOCKER" run -d --name "$PREFIX-blocker" --network "$PREFIX" --ip "$OLD_IP" nginx:alpine >/dev/null +start_backend +NEW_IP=$("$DOCKER" inspect "$PREFIX-backend" --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}') +[ "$OLD_IP" != "$NEW_IP" ] || { echo 'Backend address did not change' >&2; exit 1; } +check_routes +printf 'Gateway routes recovered after backend IP change %s -> %s without gateway restart.\n' "$OLD_IP" "$NEW_IP" diff --git a/tests/e2e/test-runner-e2e.sh b/tests/e2e/test-runner-e2e.sh index 0c84e2d..6b250bb 100644 --- a/tests/e2e/test-runner-e2e.sh +++ b/tests/e2e/test-runner-e2e.sh @@ -13,6 +13,13 @@ set -o pipefail E2E_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# This suite reserves its own stacks and handles its own cleanup. +for arg in "$@"; do + if [ "$arg" = --suite=email-apps ]; then + exec bash "$E2E_DIR/email-apps.sh" "$@" + fi +done + # Load config and libs source "$E2E_DIR/config.sh" source "$E2E_DIR/lib/assertions.sh" diff --git a/tests/run.sh b/tests/run.sh index 4f0995e..068b017 100755 --- a/tests/run.sh +++ b/tests/run.sh @@ -33,6 +33,7 @@ SSH_ALIAS="" E2E_SUITE="" E2E_APP="" QUICK=false +E2E_EXTRA_ARGS=() for arg in "$@"; do case "$arg" in @@ -42,6 +43,7 @@ for arg in "$@"; do --suite=*) E2E_SUITE="${arg#--suite=}" ;; --app=*) E2E_APP="${arg#--app=}" ;; --quick) QUICK=true ;; + --domain-type=*|--domain-suffix=*|--cleanup=*) E2E_EXTRA_ARGS+=("$arg") ;; -*) ;; # ignore unknown flags *) # First non-flag argument is the suite @@ -101,6 +103,7 @@ run_test_file() { if [ "$exit_code" -ne 0 ]; then FAILED_FILES+=("$name") + [ "$failed" -gt 0 ] || TOTAL_FAIL=$((TOTAL_FAIL + 1)) fi } @@ -175,29 +178,32 @@ run_e2e() { return 0 fi - # Build args for E2E runner - local e2e_args="--ssh=$SSH_ALIAS" - [ -n "$E2E_SUITE" ] && e2e_args="$e2e_args --suite=$E2E_SUITE" - [ -n "$E2E_APP" ] && e2e_args="$e2e_args --app=$E2E_APP" - [ "$QUICK" = true ] && e2e_args="$e2e_args --quick" - - # Delegate to E2E runner (it has its own summary) - bash "$TESTS_DIR/e2e/test-runner-e2e.sh" $e2e_args - local e2e_exit=$? - - # Count pass/fail from TAP output - local tap_file="$TESTS_DIR/e2e/results/results.tap" - if [ -f "$tap_file" ]; then - local tap_pass tap_fail - tap_pass=$(grep "^ok " "$tap_file" | grep -cv SKIP 2>/dev/null || true) - tap_fail=$(grep -c "^not ok " "$tap_file" 2>/dev/null || true) - tap_pass=${tap_pass:-0} - tap_fail=${tap_fail:-0} - TOTAL_PASS=$((TOTAL_PASS + tap_pass)) - TOTAL_FAIL=$((TOTAL_FAIL + tap_fail)) + local e2e_args=("--ssh=$SSH_ALIAS") + [ -z "$E2E_SUITE" ] || e2e_args+=("--suite=$E2E_SUITE") + [ -z "$E2E_APP" ] || e2e_args+=("--app=$E2E_APP") + [ "$QUICK" != true ] || e2e_args+=("--quick") + e2e_args+=("${E2E_EXTRA_ARGS[@]}") + + export E2E_RESULTS_DIR="${E2E_RESULTS_DIR:-$TESTS_DIR/e2e/results}" + local tap_file="$E2E_RESULTS_DIR/results.tap" e2e_exit=0 + mkdir -p "$E2E_RESULTS_DIR" + : > "$tap_file" + bash "$TESTS_DIR/e2e/test-runner-e2e.sh" "${e2e_args[@]}" || e2e_exit=$? + + local tap_pass tap_fail tap_skip tap_total tap_plan + tap_pass=$(grep '^ok ' "$tap_file" | grep -cv SKIP || true) + tap_fail=$(grep -c '^not ok ' "$tap_file" || true) + tap_skip=$(grep '^ok ' "$tap_file" | grep -c SKIP || true) + tap_total=$((tap_pass + tap_fail + tap_skip)) + tap_plan=$(sed -n 's/^1\.\.\([0-9][0-9]*\).*/\1/p' "$tap_file" | tail -1) + TOTAL_PASS=$((TOTAL_PASS + tap_pass)) + TOTAL_FAIL=$((TOTAL_FAIL + tap_fail)) + TOTAL_SKIP=$((TOTAL_SKIP + tap_skip)) + if [ "$e2e_exit" -ne 0 ] || [ "$tap_total" -eq 0 ] || [ "$tap_plan" != "$tap_total" ]; then + FAILED_FILES+=("e2e (exit $e2e_exit; TAP $tap_total/${tap_plan:-missing})") + [ "$tap_fail" -gt 0 ] || TOTAL_FAIL=$((TOTAL_FAIL + 1)) fi - - return "$e2e_exit" + return 0 } # ============================================================================= @@ -266,6 +272,9 @@ case "$SUITE" in echo " --suite=NAME E2E suite name" echo " --app=NAME E2E single app" echo " --quick E2E quick mode (1 variant per app)" + echo " --domain-type=TYPE E2E email apps: local or cloudflare" + echo " --domain-suffix=DNS E2E email apps: test domain suffix" + echo " --cleanup=POLICY E2E cleanup policy" exit 1 ;; esac diff --git a/tests/static/test-compose-syntax.sh b/tests/static/test-compose-syntax.sh index 105ca92..604075b 100644 --- a/tests/static/test-compose-syntax.sh +++ b/tests/static/test-compose-syntax.sh @@ -34,10 +34,7 @@ SKIP_APPS="coolify sellf littlelink cookie-hub dockge" # Apps where heredoc extraction is known to produce incomplete YAML # (multi-part heredocs, env_file references, conditional composition). -# poststack defers ${POSTGRES_*} to compose-level interpolation via bash-escaped \$, -# which this no-bash extractor can't unescape — the real compose is validated in -# tests/unit/test-poststack-install.sh (docker compose config on the generated file). -BEST_EFFORT_APPS="typebot vaultwarden postiz routepix social-media-generator filebrowser stirling-pdf poststack ksef-gateway" +BEST_EFFORT_APPS="typebot vaultwarden postiz routepix social-media-generator filebrowser stirling-pdf ksef-gateway" echo "--- Compose Syntax Validation ---" echo "" @@ -119,15 +116,25 @@ for install_sh in "$REPO_ROOT"/apps/*/install.sh; do export MYSQL_ROOT_PASSWORD="rootpass123" export MYSQL_PASSWORD="mysqlpass123" export CAP_ALLOWED_ORIGINS="https://app.example.com" - - # Extract the first heredoc that writes to a yaml/yml file + export IMAGE_TAG="latest" + export IMAGE_REPO="ghcr.io/stackpilot/test" + export IMAGE="stackpilot/test:latest" + export APP_URL="https://app.example.com" + export API_ENDPOINT="https://app.example.com" + export DB_PASSWORD="testpass123" + export MONGO_ROOT_PASSWORD="testpass123" + export POSTGRES_USER="testuser" + export POSTGRES_PASSWORD="testpass123" + export POSTGRES_DB="testdb" + + # Extract the first heredoc that writes a Compose file # This is a best-effort extraction — some complex scripts may not work extracted=false # Strategy: find lines like "cat </dev/null; then - echo "$content" | envsubst > "$compose_file" + # Quoted heredocs reach Compose literally. In unquoted heredocs, + # escaped dollars survive shell expansion for Compose to handle. + if [[ "$line" =~ \<\<[\'\"] ]]; then + printf '%s' "$content" > "$compose_file" + elif command -v envsubst &>/dev/null; then + printf '%s' "$content" | sed 's/\\\$/__SP_COMPOSE_DOLLAR__/g' | + envsubst | sed 's/__SP_COMPOSE_DOLLAR__/\$/g' > "$compose_file" else - echo "$content" > "$compose_file" + echo 'envsubst is required for unquoted Compose heredocs' >&2 + exit 1 fi extracted=true break fi done < "$install_sh" - if [ "$extracted" = false ]; then - # Fallback: try a simpler extraction with sed - # Look for heredoc pattern: cat </dev/null | sed '1d;$d') - - if [ -n "$heredoc_content" ]; then - if command -v envsubst &>/dev/null; then - echo "$heredoc_content" | envsubst > "$compose_file" - else - echo "$heredoc_content" > "$compose_file" - fi - extracted=true - fi - fi - if [ "$extracted" = false ]; then SKIP=$((SKIP + 1)) continue diff --git a/tests/static/test-locale-coverage.sh b/tests/static/test-locale-coverage.sh index d1e0495..bb0f48c 100755 --- a/tests/static/test-locale-coverage.sh +++ b/tests/static/test-locale-coverage.sh @@ -9,6 +9,8 @@ # Exit code 0 = all keys match; exit code 1 = mismatches found. set -e +# Compare identifier names with the same byte ordering on every platform. +export LC_ALL=C SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" diff --git a/tests/unit/test-compose-extraction.sh b/tests/unit/test-compose-extraction.sh new file mode 100755 index 0000000..79de37c --- /dev/null +++ b/tests/unit/test-compose-extraction.sh @@ -0,0 +1,50 @@ +#!/bin/bash +set -e +TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$TESTS_DIR/../.." && pwd)" +source "$TESTS_DIR/test-runner.sh" +setup() { + TEST_TMPDIR=$(mktemp -d) + mkdir -p "$TEST_TMPDIR/tests/static" "$TEST_TMPDIR/apps/example" + cp "$REPO_ROOT/tests/static/test-compose-syntax.sh" "$TEST_TMPDIR/tests/static/" +} +teardown() { rm -rf "$TEST_TMPDIR"; } +validate_fixture() { bash "$TEST_TMPDIR/tests/static/test-compose-syntax.sh" > "$TEST_TMPDIR/output" 2>&1; } +write_fixture() { + cat > "$TEST_TMPDIR/apps/example/install.sh" <<'FIXTURE' +#!/bin/bash +exit 99 +cat <<'CONFIG' | tee application.yaml +not: [valid +CONFIG +cat < "$TEST_TMPDIR/quoted" + # Quoted shell heredocs need no backslash to defer a dollar to Compose. + sed 's/\\\$/\$/g' "$TEST_TMPDIR/quoted" > "$TEST_TMPDIR/apps/example/install.sh" + assert_true validate_fixture +} +test_invalid_compose_remains_a_failure() { + write_fixture + sed 's/image: example:/image: [example:/' "$TEST_TMPDIR/apps/example/install.sh" > "$TEST_TMPDIR/invalid" + cp "$TEST_TMPDIR/invalid" "$TEST_TMPDIR/apps/example/install.sh" + assert_false validate_fixture + assert_contains "$(cat "$TEST_TMPDIR/output")" 'Failed: 1' +} +run_tests "$0" diff --git a/tests/unit/test-db-setup.sh b/tests/unit/test-db-setup.sh index 2e1e8bd..fdbb41b 100644 --- a/tests/unit/test-db-setup.sh +++ b/tests/unit/test-db-setup.sh @@ -73,6 +73,29 @@ test_fetch_database_bundled_generates_creds() { assert_not_eq "" "$DB_NAME" "bundled generates DB_NAME" } +test_bundled_reinstall_keeps_existing_password() { + _reset_db + local stacks + stacks=$(mktemp -d) + mkdir -p "$stacks/myapp" + printf 'services:\n db:\n environment:\n POSTGRES_USER: app\n POSTGRES_PASSWORD: OldSecret123\n' \ + > "$stacks/myapp/docker-compose.yaml" + server_exec() { bash -c "${1//\/opt\/stacks/$STACKS}"; } + STACKS="$stacks" APP_NAME=myapp DB_SOURCE=bundled + fetch_database "postgres" > /dev/null 2>&1 + assert_eq "OldSecret123" "$DB_PASS" "re-install reuses the bundled DB password" + + _reset_db + APP_NAME=freshapp DB_SOURCE=bundled + fetch_database "postgres" > /dev/null 2>&1 + assert_not_eq "OldSecret123" "$DB_PASS" "fresh install generates a new password" + assert_not_eq "" "$DB_PASS" "fresh install password is not empty" + + server_exec() { bash -c "$1"; } + unset APP_NAME STACKS + rm -rf "$stacks" +} + test_fetch_database_unknown_source() { _reset_db DB_SOURCE="nonexistent" diff --git a/tests/unit/test-docker-setup.sh b/tests/unit/test-docker-setup.sh new file mode 100644 index 0000000..e3524d6 --- /dev/null +++ b/tests/unit/test-docker-setup.sh @@ -0,0 +1,38 @@ +#!/bin/bash +set -e +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +if ! grep -q '^install_docker_for_distribution()' "$ROOT/system/docker-setup.sh"; then + echo 'FAIL: distribution installer entry point is missing' + exit 1 +fi +source "$ROOT/system/docker-setup.sh" +DIR=$(mktemp -d) +trap 'rm -r "$DIR"' EXIT +curl() { + printf '%s\n' "$*" >> "$DIR/curl" + if [ "${DOWNLOAD_FAIL:-0}" = 1 ]; then return 22; fi + local destination='' previous='' + for argument in "$@"; do + [ "$previous" = -o ] && destination="$argument" + previous="$argument" + done + if [ -n "$destination" ]; then printf 'vendor installer\n' > "$destination"; else printf 'provider installer\n'; fi +} +bash() { + printf '%s\n' "$*" >> "$DIR/bash" + if [ -n "${1:-}" ]; then test -s "$1"; fi + return "${INSTALL_FAIL:-0}" +} +install_docker_for_distribution debian +grep -q 'https://get.docker.com' "$DIR/curl" +grep -q -- '-fsSL' "$DIR/curl" +test -s "$DIR/bash" +old_calls=$(wc -l < "$DIR/bash") +if DOWNLOAD_FAIL=1 install_docker_for_distribution debian; then echo 'FAIL: download error accepted'; exit 1; fi +test "$(wc -l < "$DIR/bash")" = "$old_calls" +if INSTALL_FAIL=23 install_docker_for_distribution debian; then echo 'FAIL: installation error accepted'; exit 1; fi +install_docker_for_distribution ubuntu +grep -q 'unkn0w/noobs/main/scripts/chce_dockera.sh' "$DIR/curl" +piped_output=$({ printf 'docker_setup_main() { printf called; }\n'; sed -n '/^if \[\[ /,$p' "$ROOT/system/docker-setup.sh"; } | command bash -s) +test "$piped_output" = called || { echo 'FAIL: piped setup did not run'; exit 1; } +echo 'PASS: Debian, Ubuntu, errors, and piped execution' diff --git a/tests/unit/test-email-apps-e2e.sh b/tests/unit/test-email-apps-e2e.sh new file mode 100755 index 0000000..7749f5b --- /dev/null +++ b/tests/unit/test-email-apps-e2e.sh @@ -0,0 +1,88 @@ +#!/bin/bash +set -e +TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$TESTS_DIR/../.." && pwd)" +source "$TESTS_DIR/test-runner.sh" +ORIGINAL_PATH="$PATH" +setup() { + TEST_TMPDIR=$(mktemp -d) + mkdir -p "$TEST_TMPDIR/bin" + cat > "$TEST_TMPDIR/bin/ssh" <<'MOCK' +#!/bin/bash +printf '%s\n' "$*" >> "$SSH_CALLS" +if [ "${SSH_RUN_RESERVATION:-}" = true ]; then + remote_command="${2//\/opt\/stacks/$SERVER_STACKS}" + PATH="$REMOTE_BIN:/usr/bin:/bin" /bin/bash -c "$remote_command" +else + exit 1 +fi +MOCK + chmod +x "$TEST_TMPDIR/bin/ssh" + export PATH="$TEST_TMPDIR/bin:$ORIGINAL_PATH" SSH_CALLS="$TEST_TMPDIR/ssh.calls" + export E2E_RESULTS_DIR="$TEST_TMPDIR/results" +} +teardown() { PATH="$ORIGINAL_PATH"; rm -rf "$TEST_TMPDIR"; unset SSH_CALLS E2E_RESULTS_DIR SSH_RUN_RESERVATION SERVER_STACKS REMOTE_BIN E2E_CLEANUP DIG_CALLS; } +test_existing_stack_is_left_alone() { + local code=0 + bash "$REPO_ROOT/tests/e2e/test-runner-e2e.sh" --suite=email-apps --ssh=test-host --app=notifuse > "$TEST_TMPDIR/output" 2>&1 || code=$? + assert_eq 1 "$code" + assert_contains "$(cat "$TEST_TMPDIR/output")" 'Refusing to use an existing stack' + assert_not_contains "$(cat "$SSH_CALLS")" 'prune' + assert_not_contains "$(cat "$SSH_CALLS")" 'compose down' + assert_not_contains "$(cat "$SSH_CALLS")" 'rm -rf' + assert_eq 1 "$(wc -l < "$SSH_CALLS" | tr -d ' ')" 'only the ownership reservation was attempted' +} +test_invalid_app_stops_before_ssh() { + local code=0 + bash "$REPO_ROOT/tests/e2e/email-apps.sh" --ssh=test-host --app=unknown > "$TEST_TMPDIR/output" 2>&1 || code=$? + assert_eq 2 "$code" + assert_false test -f "$SSH_CALLS" +} +fresh_deploy_fixture() { + mkdir -p "$TEST_TMPDIR/repo/tests/e2e" "$TEST_TMPDIR/repo/local" "$TEST_TMPDIR/remote-bin" + cp "$REPO_ROOT/tests/e2e/email-apps.sh" "$TEST_TMPDIR/repo/tests/e2e/" + cat > "$TEST_TMPDIR/repo/local/deploy.sh" <<'DEPLOY' +#!/bin/bash +printf 'deployment reached: %s\n' "$*" +exit 1 +DEPLOY + printf '#!/bin/bash\nexec "$@"\n' > "$TEST_TMPDIR/remote-bin/sudo" + chmod +x "$TEST_TMPDIR/repo/local/deploy.sh" "$TEST_TMPDIR/remote-bin/sudo" + export SSH_RUN_RESERVATION=true SERVER_STACKS="$TEST_TMPDIR/remote-stacks" REMOTE_BIN="$TEST_TMPDIR/remote-bin" E2E_CLEANUP=never + local code=0 + bash "$TEST_TMPDIR/repo/tests/e2e/email-apps.sh" --ssh=test-host --app=notifuse "$@" > "$TEST_TMPDIR/output" 2>&1 || code=$? + assert_eq 1 "$code" 'fake deploy deliberately stops before installing' + assert_contains "$(cat "$TEST_TMPDIR/output")" 'deployment reached' + assert_true test -f "$SERVER_STACKS/notifuse/.stackpilot-e2e-owner" + assert_not_contains "$(cat "$TEST_TMPDIR/output")" 'command not found' +} +test_fresh_server_without_docker_reaches_deploy() { fresh_deploy_fixture; } +test_cloudflare_domain_is_passed_to_existing_deployer() { + export DIG_CALLS="$TEST_TMPDIR/dig.calls" + cat > "$TEST_TMPDIR/bin/dig" <<'DNS' +#!/bin/bash +printf '%s\n' "$*" >> "$DIG_CALLS" +DNS + chmod +x "$TEST_TMPDIR/bin/dig" + fresh_deploy_fixture --domain-type=cloudflare --domain-suffix=test.example.com + assert_contains "$(cat "$TEST_TMPDIR/output")" 'notifuse --ssh=test-host --domain-type=cloudflare --domain=notifuse-test.example.com' + assert_eq 3 "$(grep -c '^@1\.1\.1\.1 +short notifuse-test.example.com ' "$DIG_CALLS")" 'preflight bypasses the client resolver for every record type' +} +test_invalid_domain_options_stop_before_ssh() { + local option code + for option in '--domain-type=caddy' '--domain-type=cloudflare' '--domain-suffix=bad/host'; do + code=0 + bash "$REPO_ROOT/tests/e2e/email-apps.sh" --ssh=test-host "$option" > "$TEST_TMPDIR/output" 2>&1 || code=$? + assert_eq 2 "$code" "invalid domain option: $option" + assert_false test -f "$SSH_CALLS" + done +} +test_valid_cloudflare_options_reach_reservation() { + printf '#!/bin/bash\nexit 0\n' > "$TEST_TMPDIR/bin/dig" + chmod +x "$TEST_TMPDIR/bin/dig" + local code=0 + bash "$REPO_ROOT/tests/e2e/email-apps.sh" --ssh=test-host --app=notifuse --domain-type=cloudflare --domain-suffix=test.example.com > "$TEST_TMPDIR/output" 2>&1 || code=$? + assert_eq 1 "$code" + assert_contains "$(cat "$TEST_TMPDIR/output")" 'Refusing to use an existing stack' +} +run_tests "$0" diff --git a/tests/unit/test-listmonk-install.sh b/tests/unit/test-listmonk-install.sh new file mode 100644 index 0000000..d82b1c0 --- /dev/null +++ b/tests/unit/test-listmonk-install.sh @@ -0,0 +1,72 @@ +#!/bin/bash + +# Unit tests for apps/listmonk/install.sh +# Docker, sudo and psql are mocked; STACK_DIR is redirected so no server is needed. + +set -e + +TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$TESTS_DIR/../.." && pwd)" +INSTALL_SH="$REPO_ROOT/apps/listmonk/install.sh" + +source "$TESTS_DIR/test-runner.sh" + +ORIGINAL_PATH="$PATH" + +setup() { + TEST_TMPDIR=$(mktemp -d) + local bin="$TEST_TMPDIR/bin" + mkdir -p "$bin" + cat > "$bin/sudo" << 'EOF' +#!/bin/bash +"$@" +EOF + cat > "$bin/docker" << EOF +#!/bin/bash +echo "docker \$*" >> "$TEST_TMPDIR/calls.log" +if [ "\$1" = "compose" ] && [ "\$2" = "ps" ]; then + printf '{"Name":"listmonk","State":"running"}\n' +fi +EOF + cat > "$bin/psql" << EOF +#!/bin/bash +echo "psql \$*" >> "$TEST_TMPDIR/calls.log" +EOF + cat > "$bin/sleep" << 'EOF' +#!/bin/bash +EOF + chmod +x "$bin"/* + export PATH="$bin:$ORIGINAL_PATH" +} + +teardown() { + export PATH="$ORIGINAL_PATH" + rm -rf "$TEST_TMPDIR" +} + +run_install() { + YES_MODE=true STACK_DIR="$TEST_TMPDIR/stack" DB_HOST=db.example DB_USER=lm DB_PASS=secret DB_NAME=listmonk \ + bash "$INSTALL_SH" > "$TEST_TMPDIR/out.log" 2>&1 || { cat "$TEST_TMPDIR/out.log" >&2; return 1; } +} + +test_enables_bounce_processing() { + run_install + local calls + calls=$(cat "$TEST_TMPDIR/calls.log") + assert_contains "$calls" "bounce.enabled" "settings SQL enables bounce processing" + assert_contains "$calls" "bounce.webhooks_enabled" "settings SQL enables bounce webhooks" + assert_contains "$calls" "bounce.ses_enabled" "settings SQL enables the SES webhook" + assert_contains "$calls" "maintenance.db" "settings SQL keeps the daily vacuum" +} + +test_restarts_after_settings_so_they_take_effect() { + run_install + local psql_line restart_line + psql_line=$(grep -n '^psql' "$TEST_TMPDIR/calls.log" | head -1 | cut -d: -f1) + restart_line=$(grep -n '^docker compose restart listmonk' "$TEST_TMPDIR/calls.log" | head -1 | cut -d: -f1) + local ordered=no + [ -n "$restart_line" ] && [ -n "$psql_line" ] && [ "$restart_line" -gt "$psql_line" ] && ordered=yes + assert_eq "yes" "$ordered" "listmonk restarts after settings are written (settings load only at startup)" +} + +run_tests "$0" diff --git a/tests/unit/test-mailcheap-install.sh b/tests/unit/test-mailcheap-install.sh new file mode 100644 index 0000000..ac2dabf --- /dev/null +++ b/tests/unit/test-mailcheap-install.sh @@ -0,0 +1,168 @@ +#!/bin/bash +set -e +TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$TESTS_DIR/../.." && pwd)" +# shellcheck source=tests/unit/test-runner.sh +source "$TESTS_DIR/test-runner.sh" +ORIGINAL_PATH="$PATH" +REAL_DOCKER=$(command -v docker || true) +REAL_TEE=$(command -v tee) +export REAL_TEE +setup() { + TEST_TMPDIR=$(mktemp -d) + mkdir -p "$TEST_TMPDIR/bin" + printf '#!/bin/bash\n"$@"\n' > "$TEST_TMPDIR/bin/sudo" + cat > "$TEST_TMPDIR/bin/docker" <<'MOCK' +#!/bin/bash +printf '%s\n' "$*" >> "$DOCKER_LOG" +if [ "$1 $2" = 'load -i' ]; then + exit "${LOAD_EXIT:-0}" +fi +[ "${IMAGE_MISSING:-}" != true ] +MOCK + cat > "$TEST_TMPDIR/bin/curl" <<'MOCK' +#!/bin/bash +[ "${HEALTH_FAIL:-}" != true ] || exit 1 +case "$*" in + */signin*) [ "${SIGNIN_FAIL:-}" != true ] || exit 1; printf '%s' "${SIGNIN_BODY-Sign in to MailCheap}" ;; +esac +MOCK + cat > "$TEST_TMPDIR/bin/tee" <<'MOCK' +#!/bin/bash +if [ "${CHECK_ENV_MODE:-}" = true ] && [ "$1" = .env ]; then + mode=$(stat -c '%a' .env 2>/dev/null || stat -f '%Lp' .env 2>/dev/null) + [ "$mode" = 600 ] || { echo '.env must exist with mode 600 before writing' >&2; exit 1; } +fi +exec "$REAL_TEE" "$@" +MOCK + printf '#!/bin/bash\nexit 0\n' > "$TEST_TMPDIR/bin/sleep" + chmod +x "$TEST_TMPDIR/bin/"* + export PATH="$TEST_TMPDIR/bin:$ORIGINAL_PATH" DOCKER_LOG="$TEST_TMPDIR/docker.log" +} +teardown() { PATH="$ORIGINAL_PATH"; rm -rf "$TEST_TMPDIR"; } +run_install() { STACK_DIR="$TEST_TMPDIR/stack" PORT=8142 DOMAIN="${TEST_DOMAIN-mail.example.com}" DOMAIN_TYPE="${TEST_DOMAIN_TYPE:-caddy}" bash "$REPO_ROOT/apps/mailcheap/install.sh"; } +test_generates_distinct_stable_secrets() { + run_install >/dev/null || return + local before auth suppression + before=$(cat "$TEST_TMPDIR/stack/.env") + auth=$(sed -n 's/^BETTER_AUTH_SECRET=//p' "$TEST_TMPDIR/stack/.env") + suppression=$(sed -n 's/^SUPPRESSION_HASH_KEY=//p' "$TEST_TMPDIR/stack/.env") + assert_true test "${#auth}" -ge 32 + assert_true test "${#suppression}" -ge 32 + assert_not_eq "$auth" "$suppression" + printf '\nADMIN_EMAILS=owner@example.com\n' >> "$TEST_TMPDIR/stack/.env" + run_install >/dev/null || return + assert_contains "$(cat "$TEST_TMPDIR/stack/.env")" "$before" + assert_contains "$(cat "$TEST_TMPDIR/stack/.env")" 'ADMIN_EMAILS=owner@example.com' + assert_eq 600 "$(stat -c '%a' "$TEST_TMPDIR/stack/.env" 2>/dev/null || stat -f '%Lp' "$TEST_TMPDIR/stack/.env" 2>/dev/null)" +} +test_binds_only_web_and_has_authenticated_persistent_mongo() { + run_install >/dev/null || return + local compose + compose=$(cat "$TEST_TMPDIR/stack/docker-compose.yaml") + assert_contains "$compose" '127.0.0.1:8142:3000' + assert_contains "$compose" 'mongo:7.0.45' + assert_contains "$compose" 'mongo-data:/data/db' + assert_contains "$compose" 'MONGO_INITDB_ROOT_PASSWORD:' + assert_contains "$compose" 'authSource=admin' + assert_eq 1 "$(grep -c 'ports:' "$TEST_TMPDIR/stack/docker-compose.yaml")" + assert_contains "$compose" 'APP_URL: "https://mail.example.com"' + assert_contains "$(cat "$TEST_TMPDIR/docker.log")" 'up -d --wait' +} +test_cytrus_binds_all_interfaces() { + TEST_DOMAIN_TYPE=cytrus run_install >/dev/null || return + assert_contains "$(cat "$TEST_TMPDIR/stack/docker-compose.yaml")" '"8142:3000"' +} +test_local_url_uses_forwarded_port() { + TEST_DOMAIN='' run_install >/dev/null || return + assert_contains "$(cat "$TEST_TMPDIR/stack/docker-compose.yaml")" 'APP_URL: "http://localhost:8142"' +} +test_generated_compose_is_accepted_by_docker() { + if [ -z "$REAL_DOCKER" ] || ! "$REAL_DOCKER" compose version >/dev/null 2>&1; then + skip_test "Docker Compose not installed" + return + fi + run_install >/dev/null || return + assert_true "$REAL_DOCKER" compose -f "$TEST_TMPDIR/stack/docker-compose.yaml" config --quiet +} +test_partial_configuration_is_preserved_and_fails_before_start() { + mkdir -p "$TEST_TMPDIR/stack" + printf 'BETTER_AUTH_SECRET=retain-this-existing-key-retain-this-existing-key\n' > "$TEST_TMPDIR/stack/.env" + local before output rc=0 + before=$(cat "$TEST_TMPDIR/stack/.env") + output=$(run_install 2>&1) || rc=$? + assert_eq 1 "$rc" + assert_contains "$output" 'MONGO_ROOT_PASSWORD' + assert_eq "$before" "$(cat "$TEST_TMPDIR/stack/.env")" + assert_not_contains "$(cat "$TEST_TMPDIR/docker.log")" 'up -d' +} +test_empty_and_short_secrets_fail_before_start() { + run_install >/dev/null || return + sed '/^SUPPRESSION_HASH_KEY=/s/=.*/=short/' "$TEST_TMPDIR/stack/.env" > "$TEST_TMPDIR/changed-env" + mv "$TEST_TMPDIR/changed-env" "$TEST_TMPDIR/stack/.env" + : > "$TEST_TMPDIR/docker.log" + local output rc=0 + output=$(run_install 2>&1) || rc=$? + assert_eq 1 "$rc" + assert_contains "$output" 'SUPPRESSION_HASH_KEY' + assert_not_contains "$(cat "$TEST_TMPDIR/docker.log")" 'up -d' +} +test_env_is_private_before_first_write() { + CHECK_ENV_MODE=true run_install >/dev/null || return + assert_true test -s "$TEST_TMPDIR/stack/.env" +} +test_build_file_is_loaded_before_image_inspection() { + : > "$TEST_TMPDIR/image.tar" + BUILD_FILE="$TEST_TMPDIR/image.tar" run_install >/dev/null || return + assert_eq "load -i $TEST_TMPDIR/image.tar" "$(head -1 "$TEST_TMPDIR/docker.log")" + assert_contains "$(sed -n '2p' "$TEST_TMPDIR/docker.log")" 'image inspect stackpilot/mailcheap:' +} +test_missing_build_file_stops_before_docker() { + local output rc=0 + output=$(BUILD_FILE="$TEST_TMPDIR/missing-image.tar" run_install 2>&1) || rc=$? + assert_eq 1 "$rc" + assert_contains "$output" 'BUILD_FILE' + assert_false test -f "$TEST_TMPDIR/docker.log" +} +test_failed_image_load_stops_before_inspection() { + : > "$TEST_TMPDIR/image.tar" + local rc=0 + BUILD_FILE="$TEST_TMPDIR/image.tar" LOAD_EXIT=1 run_install >/dev/null 2>&1 || rc=$? + assert_eq 1 "$rc" + assert_not_contains "$(cat "$TEST_TMPDIR/docker.log")" 'image inspect' +} +test_success_persists_selected_host_port() { + run_install >/dev/null || return + assert_eq 8142 "$(cat "$TEST_TMPDIR/stack/.stackpilot-port")" +} +test_missing_image_fails_with_preparation_command() { + local output rc=0 + output=$(IMAGE_MISSING=true run_install 2>&1) || rc=$? + assert_eq 1 "$rc" + assert_contains "$output" 'apps/mailcheap/build.sh' + assert_false test -f "$TEST_TMPDIR/stack/docker-compose.yaml" +} +test_configuration_health_without_signin_does_not_report_success() { + local output rc=0 + output=$(SIGNIN_FAIL=true run_install 2>&1) || rc=$? + assert_eq 1 "$rc" + assert_not_contains "$output" 'MailCheap installed' + assert_false test -f "$TEST_TMPDIR/stack/.stackpilot-port" +} +test_signin_response_must_contain_the_login_form() { + local rc=0 + SIGNIN_BODY='An error occurred' run_install >/dev/null 2>&1 || rc=$? + assert_eq 1 "$rc" +} +test_container_readiness_uses_signin_page() { + run_install >/dev/null || return + assert_contains "$(cat "$TEST_TMPDIR/stack/docker-compose.yaml")" "fetch('http://127.0.0.1:3000/signin')" + assert_contains "$(cat "$TEST_TMPDIR/stack/docker-compose.yaml")" "includes('Sign in to MailCheap')" +} +test_unhealthy_service_does_not_report_success() { + local output rc=0 + output=$(HEALTH_FAIL=true run_install 2>&1) || rc=$? + assert_eq 1 "$rc" + assert_not_contains "$output" 'MailCheap installed' +} +run_tests "$0" diff --git a/tests/unit/test-managed-port.sh b/tests/unit/test-managed-port.sh new file mode 100644 index 0000000..b27e2fd --- /dev/null +++ b/tests/unit/test-managed-port.sh @@ -0,0 +1,37 @@ +#!/bin/bash +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +WORK=$(mktemp -d) +trap 'python3 -c "import shutil,sys;shutil.rmtree(sys.argv[1])" "$WORK"' EXIT +sed -n '/^DEFAULT_PORT=/,/^# PHASE 1/p' "$ROOT/local/deploy.sh" > "$WORK/phase.sh" +for managed in true false; do + printf 'PORT=31878\n' > "$WORK/install.sh" + [ "$managed" = false ] || printf '# PORT_MANAGED=true\n' >> "$WORK/install.sh" + result=$(bash -s -- "$WORK" <<'CASE' +set -e +SCRIPT_PATH="$1/install.sh" +DOMAIN='' +APP_NAME='native' +SSH_ALIAS='test' +MSG_PORT_IN_USE='' +MSG_PORT_OVERRIDE='' +read_existing_app_port() { return 1; } +server_exec_timeout() { echo yes; } +find_free_port_remote() { echo 31879; } +msg() { :; } +source "$1/phase.sh" > /dev/null +[ "$DEFAULT_PORT" = 31878 ] +printf '%s' "$PORT_OVERRIDE" +CASE +) + if [ "$managed" = true ]; then + [ -z "$result" ] || { echo 'Installer-managed port was replaced'; exit 1; } + else + [ "$result" = 31879 ] || { echo 'Ordinary port discovery did not run'; exit 1; } + fi +done + +export DEFAULT_PORT=31878 +initializer=$(sed -n '/^APP_PORT=/p' "$ROOT/local/deploy.sh" | head -1) +eval "$initializer" +[ "$APP_PORT" = 31878 ] || { echo 'Local access port was lost after discovery'; exit 1; } diff --git a/tests/unit/test-native-runtime.sh b/tests/unit/test-native-runtime.sh new file mode 100644 index 0000000..3d2aeda --- /dev/null +++ b/tests/unit/test-native-runtime.sh @@ -0,0 +1,26 @@ +#!/bin/bash +set -e +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +DIR=$(mktemp -d) +trap 'rm -r "$DIR"' EXIT +server_exec() { printf '%s\n' "$1" >> "$DIR/calls"; } +msg() { :; } +block=$(sed -n '/^# Auto-install Docker/,/^# Upload script/{ /^# Upload script/d; p; }' "$ROOT/local/deploy.sh") +test -n "$block" +SCRIPT_PATH="$DIR/native.sh" +printf '# DOCKER_REQUIRED=false\n' > "$SCRIPT_PATH" +APP_NAME=example RUNTIME=pm2 +export APP_NAME RUNTIME +eval "$block" +if [ -s "$DIR/calls" ]; then echo 'FAIL: native app still checks Docker'; exit 1; fi +printf '# normal app\n' > "$SCRIPT_PATH" +eval "$block" +test -s "$DIR/calls" +: > "$DIR/calls" +APP_NAME=sellf RUNTIME=pm2 +eval "$block" +test ! -s "$DIR/calls" +RUNTIME=docker +eval "$block" +test -s "$DIR/calls" +echo 'PASS: native, default, Sellf PM2 and Docker runtimes' diff --git a/tests/unit/test-notifuse-install.sh b/tests/unit/test-notifuse-install.sh new file mode 100755 index 0000000..0c8f03d --- /dev/null +++ b/tests/unit/test-notifuse-install.sh @@ -0,0 +1,76 @@ +#!/bin/bash +set -e +TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$TESTS_DIR/../.." && pwd)" +source "$TESTS_DIR/test-runner.sh" +ORIGINAL_PATH="$PATH" +REAL_DOCKER="$(command -v docker || true)" +setup() { + TEST_TMPDIR=$(mktemp -d) + mkdir -p "$TEST_TMPDIR/bin" + printf '#!/bin/bash\nexec "$@"\n' > "$TEST_TMPDIR/bin/sudo" + cat > "$TEST_TMPDIR/bin/docker" <<'MOCK' +#!/bin/bash +printf '%s\n' "$*" >> "$STACK_DIR/docker.calls" +exit "${DOCKER_EXIT:-0}" +MOCK + cat > "$TEST_TMPDIR/bin/curl" <<'MOCK' +#!/bin/bash +exit "${CURL_EXIT:-0}" +MOCK + chmod +x "$TEST_TMPDIR/bin/"* + export PATH="$TEST_TMPDIR/bin:$ORIGINAL_PATH" + export STACK_DIR="$TEST_TMPDIR/notifuse" PORT=8087 DOMAIN=mail.example.com DOMAIN_TYPE=cloudflare +} +teardown() { PATH="$ORIGINAL_PATH"; rm -rf "$TEST_TMPDIR"; unset STACK_DIR PORT DOMAIN DOMAIN_TYPE DOCKER_EXIT CURL_EXIT; } +install_app() { bash "$REPO_ROOT/apps/notifuse/install.sh" > "$TEST_TMPDIR/output" 2>&1; } +test_new_install_uses_upstream_runtime_contract() { + install_app || { assert_eq 0 "$?" "installer succeeds"; return; } + local compose; compose=$(cat "$STACK_DIR/docker-compose.yaml") + assert_contains "$compose" 'notifuse/notifuse:' + assert_contains "$compose" 'postgres:17-alpine' + assert_contains "$compose" 'DB_HOST: postgres' + assert_contains "$compose" 'DB_SSLMODE: disable' + assert_contains "$compose" '/healthz' + assert_contains "$compose" '/var/lib/postgresql/data' + assert_contains "$compose" 'condition: service_healthy' + assert_contains "$compose" 'API_ENDPOINT: "https://mail.example.com"' + assert_contains "$compose" '127.0.0.1:8087:8080' + assert_eq 8087 "$(cat "$STACK_DIR/.stackpilot-port")" + assert_not_contains "$compose" ':5432:5432' + assert_not_contains "$compose" ':587:587' +} +test_secrets_are_generated_and_preserved() { + install_app || { assert_eq 0 "$?"; return; } + local first; first=$(cat "$STACK_DIR/.env") + assert_true grep -Eq '^SECRET_KEY=.{43,}$' "$STACK_DIR/.env" + assert_true grep -Eq '^DB_PASSWORD=[a-f0-9]{48}$' "$STACK_DIR/.env" + install_app || { assert_eq 0 "$?"; return; } + assert_eq "$first" "$(cat "$STACK_DIR/.env")" 'redeploy keeps database and encryption keys' + local mode; mode=$(stat -c '%a' "$STACK_DIR/.env" 2>/dev/null || stat -f '%Lp' "$STACK_DIR/.env" 2>/dev/null) + assert_eq 600 "$mode" '.env permissions' +} +test_cytrus_binding() { + DOMAIN_TYPE=cytrus install_app || { assert_eq 0 "$?"; return; } + assert_contains "$(cat "$STACK_DIR/docker-compose.yaml")" '"8087:8080"' +} +test_local_url_and_changed_domain() { + DOMAIN='' install_app || { assert_eq 0 "$?"; return; } + assert_contains "$(cat "$STACK_DIR/docker-compose.yaml")" 'API_ENDPOINT: "http://localhost:8087"' + install_app || { assert_eq 0 "$?"; return; } + assert_contains "$(cat "$STACK_DIR/docker-compose.yaml")" 'API_ENDPOINT: "https://mail.example.com"' +} +test_incomplete_existing_config_is_not_replaced() { + mkdir -p "$STACK_DIR" + printf 'SECRET_KEY=keep-this-key\n' > "$STACK_DIR/.env" + assert_false install_app + assert_eq 'SECRET_KEY=keep-this-key' "$(cat "$STACK_DIR/.env")" +} +test_failed_start_is_reported() { DOCKER_EXIT=1 assert_false install_app; } +test_failed_host_health_is_reported() { CURL_EXIT=1 assert_false install_app; } +test_real_compose_validation() { + install_app || { assert_eq 0 "$?"; return; } + if [ -z "$REAL_DOCKER" ] || ! "$REAL_DOCKER" compose version >/dev/null 2>&1; then skip_test 'docker compose unavailable'; return; fi + assert_true "$REAL_DOCKER" compose -f "$STACK_DIR/docker-compose.yaml" --env-file "$STACK_DIR/.env" config --quiet +} +run_tests "$0" diff --git a/tests/unit/test-plunk-install.sh b/tests/unit/test-plunk-install.sh new file mode 100644 index 0000000..7a0a467 --- /dev/null +++ b/tests/unit/test-plunk-install.sh @@ -0,0 +1,141 @@ +#!/bin/bash +set -e +TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$TESTS_DIR/../.." && pwd)" +source "$TESTS_DIR/test-runner.sh" +setup() { + TEST_TMPDIR=$(mktemp -d) + ORIGINAL_PATH="$PATH" + REAL_DOCKER=$(command -v docker || true) + mkdir -p "$TEST_TMPDIR/bin" + printf '#!/bin/bash\n"$@"\n' > "$TEST_TMPDIR/bin/sudo" + cat > "$TEST_TMPDIR/bin/docker" <<'MOCK' +#!/bin/bash +printf '%s\n' "$*" >> "$DOCKER_CALLS" +if [ "$*" = 'compose ps --status running -q gateway' ]; then + printf '%s' "${RUNNING_GATEWAY:-}" +fi +if [[ "$*" == *'nginx -t' ]]; then exit "${NGINX_TEST_EXIT:-0}"; fi +exit 0 +MOCK + chmod +x "$TEST_TMPDIR/bin/"* + export PATH="$TEST_TMPDIR/bin:$PATH" DOCKER_CALLS="$TEST_TMPDIR/docker-calls" + export XDG_CONFIG_HOME="$TEST_TMPDIR/config" + export STACK_DIR="$TEST_TMPDIR/plunk" DOMAIN=mail.example.com DOMAIN_TYPE=cloudflare PORT=3560 + export AWS_SES_REGION=eu-west-1 AWS_SES_ACCESS_KEY_ID=test-key AWS_SES_SECRET_ACCESS_KEY=test-secret +} +teardown() { export PATH="$ORIGINAL_PATH"; unset STACK_DIR DOMAIN DOMAIN_TYPE PORT AWS_SES_REGION AWS_SES_ACCESS_KEY_ID AWS_SES_SECRET_ACCESS_KEY DOCKER_CALLS XDG_CONFIG_HOME RUNNING_GATEWAY NGINX_TEST_EXIT; rm -rf "$TEST_TMPDIR"; } +install() { bash "$REPO_ROOT/apps/plunk/install.sh" > "$TEST_TMPDIR/output" 2>&1; } +test_same_origin_urls_and_proxy() { + install + assert_contains "$(cat "$STACK_DIR/.env")" 'API_URI=https://mail.example.com/api' + assert_contains "$(cat "$STACK_DIR/.env")" 'DASHBOARD_URI=https://mail.example.com' + assert_contains "$(cat "$STACK_DIR/nginx.conf")" 'proxy_pass http://plunk_api/;' + assert_contains "$(cat "$STACK_DIR/nginx.conf")" 'proxy_pass http://plunk_web;' + assert_contains "$(cat "$STACK_DIR/nginx.conf")" 'proxy_pass http://plunk_uploads/uploads/;' +} +test_proxy_and_local_bindings() { + install + assert_contains "$(cat "$STACK_DIR/docker-compose.yaml")" '127.0.0.1:3560:80' + assert_eq 3560 "$(cat "$STACK_DIR/.stackpilot-port")" + unset DOMAIN + install + assert_contains "$(cat "$STACK_DIR/.env")" 'API_URI=http://localhost:3560/api' +} +test_cytrus_binds_public_port() { + DOMAIN_TYPE=cytrus install + assert_contains "$(cat "$STACK_DIR/docker-compose.yaml")" '"3560:80"' + assert_not_contains "$(cat "$STACK_DIR/docker-compose.yaml")" '127.0.0.1:3560:80' +} +test_secrets_survive_reinstall_and_config_is_private() { + install + local first + first=$(grep -E '^(JWT_SECRET|DB_PASSWORD|MINIO_ROOT_PASSWORD)=' "$STACK_DIR/.env") + install + assert_eq "$first" "$(grep -E '^(JWT_SECRET|DB_PASSWORD|MINIO_ROOT_PASSWORD)=' "$STACK_DIR/.env")" + local mode + mode=$(stat -c '%a' "$STACK_DIR/.env" 2>/dev/null || stat -f '%Lp' "$STACK_DIR/.env" 2>/dev/null) + assert_eq 600 "$mode" +} +test_missing_ses_stops_before_docker() { + unset AWS_SES_ACCESS_KEY_ID + local rc=0 + install || rc=$? + assert_not_eq 0 "$rc" + assert_contains "$(cat "$TEST_TMPDIR/output")" 'AWS_SES_ACCESS_KEY_ID' + assert_true test ! -f "$DOCKER_CALLS" +} +test_persistent_services_and_ready_wait() { + install + local compose + compose=$(cat "$STACK_DIR/docker-compose.yaml") + assert_contains "$compose" 'ghcr.io/useplunk/plunk:' + assert_contains "$compose" 'postgres:16-alpine' + assert_contains "$compose" 'redis:7-alpine' + assert_contains "$compose" 'postgres_data:' + assert_contains "$compose" 'minio_data:' + assert_contains "$(cat "$DOCKER_CALLS")" 'compose up -d --wait' + assert_not_contains "$compose" ':465' + assert_not_contains "$compose" ':587' +} +test_compose_configuration() { + if [ -z "$REAL_DOCKER" ] || ! "$REAL_DOCKER" compose version >/dev/null 2>&1; then + skip_test 'docker compose unavailable' + return + fi + install + local rc=0 + (cd "$STACK_DIR" && "$REAL_DOCKER" compose config --quiet) || rc=$? + assert_eq 0 "$rc" 'generated Compose validates with the real CLI' +} +test_incomplete_existing_configuration_stops_without_rotating_secrets() { + local key first rc + for key in DB_PASSWORD JWT_SECRET MINIO_ROOT_PASSWORD; do + install + first=$(cat "$STACK_DIR/.env") + grep -v "^${key}=" "$STACK_DIR/.env" > "$TEST_TMPDIR/partial" + cp "$TEST_TMPDIR/partial" "$STACK_DIR/.env" + rm -f "$DOCKER_CALLS" + rc=0 + install || rc=$? + assert_not_eq 0 "$rc" "missing $key stops installation" + assert_eq "$(cat "$TEST_TMPDIR/partial")" "$(cat "$STACK_DIR/.env")" 'existing configuration stays unchanged' + assert_true test ! -f "$DOCKER_CALLS" + printf '%s\n' "$first" > "$STACK_DIR/.env" + done +} +test_empty_existing_secret_stops_before_docker() { + install + grep -v '^JWT_SECRET=' "$STACK_DIR/.env" > "$TEST_TMPDIR/partial" + printf 'JWT_SECRET=\n' >> "$TEST_TMPDIR/partial" + cp "$TEST_TMPDIR/partial" "$STACK_DIR/.env" + rm -f "$DOCKER_CALLS" + local rc=0 + install || rc=$? + assert_not_eq 0 "$rc" + assert_true test ! -f "$DOCKER_CALLS" +} +test_new_instances_keep_signup_closed() { + install + assert_contains "$(cat "$STACK_DIR/.env")" 'DISABLE_SIGNUPS=true' +} +test_existing_gateway_validates_and_reloads_before_wait() { + RUNNING_GATEWAY=existing install + local calls validate reload wait + calls=$(cat "$DOCKER_CALLS") + validate=$(printf '%s\n' "$calls" | grep -nF 'compose exec -T gateway nginx -t' | cut -d: -f1) + reload=$(printf '%s\n' "$calls" | grep -nF 'compose exec -T gateway nginx -s reload' | cut -d: -f1) + wait=$(printf '%s\n' "$calls" | grep -nF 'compose up -d --wait' | cut -d: -f1) + assert_true test -n "$validate" + assert_true test -n "$reload" + assert_true test "$validate" -lt "$reload" + assert_true test "$reload" -lt "$wait" +} +test_invalid_existing_gateway_configuration_stops_before_wait() { + local rc=0 + RUNNING_GATEWAY=existing NGINX_TEST_EXIT=1 install || rc=$? + assert_not_eq 0 "$rc" + assert_not_contains "$(cat "$DOCKER_CALLS")" 'compose up -d --wait' +} + +run_tests "$0" diff --git a/tests/unit/test-port-utils.sh b/tests/unit/test-port-utils.sh index 12eae9a..6115cee 100644 --- a/tests/unit/test-port-utils.sh +++ b/tests/unit/test-port-utils.sh @@ -67,4 +67,30 @@ test_find_free_port_single_used() { # Run # ============================================================================= +setup() { TEST_TMPDIR=$(mktemp -d); } +teardown() { rm -rf "$TEST_TMPDIR"; } +server_exec_timeout() { bash -c "$2"; } +test_existing_port_prefers_saved_host_port() { + printf '3561\n' > "$TEST_TMPDIR/.stackpilot-port" + printf 'PORT=3000\n' > "$TEST_TMPDIR/.env.local" + assert_eq 3561 "$(read_existing_app_port "$TEST_TMPDIR/.stackpilot-port" "$TEST_TMPDIR/.env.local")" +} +test_existing_port_accepts_default_as_existing() { + printf '3560\n' > "$TEST_TMPDIR/.stackpilot-port" + assert_eq 3560 "$(read_existing_app_port "$TEST_TMPDIR/.stackpilot-port" "$TEST_TMPDIR/missing")" +} +test_existing_port_keeps_legacy_env_support() { + printf 'PORT=3334\n' > "$TEST_TMPDIR/.env.local" + assert_eq 3334 "$(read_existing_app_port "$TEST_TMPDIR/missing" "$TEST_TMPDIR/.env.local")" +} +test_existing_port_rejects_invalid_values() { + local value port rc + for value in 0 65536 -1 abc 003560 '3560; echo extra'; do + printf '%s\n' "$value" > "$TEST_TMPDIR/.stackpilot-port" + rc=0 + port=$(read_existing_app_port "$TEST_TMPDIR/.stackpilot-port" "$TEST_TMPDIR/missing") || rc=$? + assert_eq '' "$port" + assert_not_eq 0 "$rc" + done +} run_tests "$0" diff --git a/tests/unit/test-runner.sh b/tests/unit/test-runner.sh index c85e0cd..b4d4486 100755 --- a/tests/unit/test-runner.sh +++ b/tests/unit/test-runner.sh @@ -81,7 +81,7 @@ assert_contains() { local message="${3:-assert_contains}" _TR_TOTAL=$((_TR_TOTAL + 1)) - if echo "$haystack" | grep -qF "$needle"; then + if echo "$haystack" | grep -qF -- "$needle"; then return 0 else echo -e " ${_TR_RED}FAIL${_TR_NC}: $message" @@ -98,7 +98,7 @@ assert_not_contains() { local message="${3:-assert_not_contains}" _TR_TOTAL=$((_TR_TOTAL + 1)) - if ! echo "$haystack" | grep -qF "$needle"; then + if ! echo "$haystack" | grep -qF -- "$needle"; then return 0 else echo -e " ${_TR_RED}FAIL${_TR_NC}: $message" diff --git a/tests/unit/test-server-exec-i18n.sh b/tests/unit/test-server-exec-i18n.sh new file mode 100755 index 0000000..65c7332 --- /dev/null +++ b/tests/unit/test-server-exec-i18n.sh @@ -0,0 +1,34 @@ +#!/bin/bash +set -e +TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$TESTS_DIR/../.." && pwd)" +source "$TESTS_DIR/test-runner.sh" + +child_message() { + TOOLBOX_LANG="$1" bash -c ' + source "$1/lib/i18n.sh" + bash -c '\''source "$1/lib/server-exec.sh"; msg "$MSG_DNS_CF_MODE"'\'' bash "$1" + ' bash "$REPO_ROOT" +} +test_english_child_loads_message_variables() { + assert_eq 'Cloudflare mode' "$(child_message en)" 'exported language and msg function do not carry locale variables' +} +test_polish_child_keeps_requested_language() { + assert_eq 'Tryb Cloudflare' "$(child_message pl)" +} +test_explicit_language_in_fresh_shell_loads_messages() { + local actual + actual=$(TOOLBOX_LANG=pl bash -c 'source "$1/lib/server-exec.sh"; msg "$MSG_DNS_CF_MODE"' bash "$REPO_ROOT") + assert_eq 'Tryb Cloudflare' "$actual" +} +test_same_process_keeps_loaded_messages() { + local actual + actual=$(TOOLBOX_LANG=pl bash -c ' + source "$1/lib/i18n.sh" + MSG_DNS_CF_MODE="Already loaded" + source "$1/lib/server-exec.sh" + msg "$MSG_DNS_CF_MODE" + ' bash "$REPO_ROOT") + assert_eq 'Already loaded' "$actual" 'sourcing the library again keeps in-process configuration' +} +run_tests "$0" diff --git a/tests/unit/test-sgtm-install.sh b/tests/unit/test-sgtm-install.sh index 3469f0e..a443568 100644 --- a/tests/unit/test-sgtm-install.sh +++ b/tests/unit/test-sgtm-install.sh @@ -17,6 +17,7 @@ source "$TESTS_DIR/test-runner.sh" # ============================================================================= MOCK_BIN="" +ORIGINAL_PATH="$PATH" setup() { TEST_TMPDIR=$(mktemp -d) @@ -50,11 +51,18 @@ exit 0 EOF chmod +x "$MOCK_BIN/sleep" - export PATH="$MOCK_BIN:$PATH" + cat > "$MOCK_BIN/curl" <<'EOF' +#!/bin/bash +printf '%s' "${CURL_STATUS:-200}" +EOF + chmod +x "$MOCK_BIN/curl" + printf 'source "%s/lib/health-check.sh"\n' "$REPO_ROOT" > "$TEST_TMPDIR/bash-env" + export PATH="$MOCK_BIN:$ORIGINAL_PATH" } teardown() { - unset CONTAINER_CONFIG DOMAIN PORT STACK_DIR + PATH="$ORIGINAL_PATH" + unset CONTAINER_CONFIG DOMAIN PORT STACK_DIR CURL_STATUS if [ -n "$TEST_TMPDIR" ] && [ -d "$TEST_TMPDIR" ]; then rm -rf "$TEST_TMPDIR" fi @@ -65,7 +73,7 @@ run_install() { local extra_env="${1:-}" local stack_dir="$TEST_TMPDIR/stacks/sgtm" mkdir -p "$stack_dir" - eval "$extra_env STACK_DIR='$stack_dir' bash '$INSTALL_SH'" 2>&1 + eval "$extra_env BASH_ENV='$TEST_TMPDIR/bash-env' STACK_DIR='$stack_dir' bash '$INSTALL_SH'" 2>&1 } compose_file() { @@ -108,6 +116,7 @@ test_succeeds_with_container_config() { rc=$? set -e assert_eq "0" "$rc" "exits 0 when CONTAINER_CONFIG is provided (output: ${output:0:200})" + assert_contains "$output" 'HTTP 200' 'shared HTTP readiness helper is exercised' } test_compose_file_created() { @@ -166,6 +175,12 @@ test_success_warns_when_no_domain() { assert_contains "$output" "domain" "warns when no domain is configured" } +test_unresponsive_http_does_not_report_success() { + local code=0 + CURL_STATUS=000 run_install "CONTAINER_CONFIG='example-config'" > /dev/null 2>&1 || code=$? + assert_eq 1 "$code" 'running containers without HTTP readiness are not successful' +} + # ============================================================================= # Run # ============================================================================= diff --git a/tests/unit/test-unified-runner.sh b/tests/unit/test-unified-runner.sh new file mode 100644 index 0000000..21bdcab --- /dev/null +++ b/tests/unit/test-unified-runner.sh @@ -0,0 +1,68 @@ +#!/bin/bash +set -e +TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$TESTS_DIR/../.." && pwd)" +source "$TESTS_DIR/test-runner.sh" +setup() { + TEST_TMPDIR=$(mktemp -d) + mkdir -p "$TEST_TMPDIR/tests/e2e/results" "$TEST_TMPDIR/tests/unit" + cp "$REPO_ROOT/tests/run.sh" "$TEST_TMPDIR/tests/" + printf 'ok 1 - stale result\n' > "$TEST_TMPDIR/tests/e2e/results/results.tap" + cat > "$TEST_TMPDIR/tests/e2e/test-runner-e2e.sh" <<'E2E' +#!/bin/bash +printf '%s\n' "$@" > "$ARG_LOG" +if [ -n "${FAKE_TAP:-}" ]; then + mkdir -p "$E2E_RESULTS_DIR" + printf '%s\n' "$FAKE_TAP" > "$E2E_RESULTS_DIR/results.tap" +fi +exit "${FAKE_EXIT:-0}" +E2E + export E2E_RESULTS_DIR="$TEST_TMPDIR/custom-results" ARG_LOG="$TEST_TMPDIR/arguments" +} +teardown() { rm -rf "$TEST_TMPDIR"; unset E2E_RESULTS_DIR ARG_LOG FAKE_TAP FAKE_EXIT; } +run_fixture() { + RESULT=0 + bash "$TEST_TMPDIR/tests/run.sh" e2e --ssh=fake-host "$@" > "$TEST_TMPDIR/output" 2>&1 || RESULT=$? +} +test_e2e_failure_without_tap_is_not_hidden_by_stale_results() { + FAKE_EXIT=2 run_fixture + assert_eq 1 "$RESULT" + assert_contains "$(cat "$TEST_TMPDIR/output")" '1 failed' +} +test_tap_override_failure_changes_outer_exit() { + FAKE_TAP=$'TAP version 13\nnot ok 1 - expected failure\n1..1' run_fixture + assert_eq 1 "$RESULT" + assert_contains "$(cat "$TEST_TMPDIR/output")" '1 failed' +} +test_successful_tap_and_passthrough() { + FAKE_TAP=$'TAP version 13\nok 1 - expected success\n1..1' run_fixture --suite=email-apps --app=notifuse --domain-type=cloudflare --domain-suffix=test.example.com --cleanup=never + assert_eq 0 "$RESULT" + assert_contains "$(cat "$TEST_TMPDIR/output")" '1 passed' + assert_true grep -qx -- '--domain-type=cloudflare' "$ARG_LOG" + assert_true grep -qx -- '--domain-suffix=test.example.com' "$ARG_LOG" + assert_true grep -qx -- '--cleanup=never' "$ARG_LOG" +} +test_unit_process_failure_without_assertion_output_fails_outer_runner() { + printf '#!/bin/bash\nexit 2\n' > "$TEST_TMPDIR/tests/unit/test-process.sh" + local code=0 + bash "$TEST_TMPDIR/tests/run.sh" unit > "$TEST_TMPDIR/output" 2>&1 || code=$? + assert_eq 1 "$code" +} +test_hyphen_prefixed_assertion_pattern() { + assert_contains 'deploy --domain-type=cloudflare' '--domain-type=cloudflare' + assert_not_contains 'deploy --domain-type=cloudflare' '--cleanup=never' +} +test_nonzero_exit_with_passing_tap_still_fails() { + FAKE_EXIT=2 FAKE_TAP=$'TAP version 13\nok 1 - completed assertion\n1..1' run_fixture + assert_eq 1 "$RESULT" +} +test_incomplete_tap_fails_even_with_zero_exit() { + FAKE_TAP=$'TAP version 13\nok 1 - completed assertion' run_fixture + assert_eq 1 "$RESULT" +} +test_e2e_config_preserves_results_override() { + local actual + actual=$(bash -c 'source "$1"; printf "%s" "$E2E_RESULTS_DIR"' bash "$REPO_ROOT/tests/e2e/config.sh") + assert_eq "$E2E_RESULTS_DIR" "$actual" +} +run_tests "$0"