From 5c02d888432c9470bd3de09e083e7573a9245d07 Mon Sep 17 00:00:00 2001 From: rob Date: Thu, 12 Nov 2026 10:08:54 +0000 Subject: [PATCH] Prepare database-free BortStack deployment --- .env.example | 32 +---- .github/workflows/ci-deploy.yml | 48 +------- api/Dockerfile | 2 +- api/gunicorn.conf.py | 6 +- docker-compose.yml | 27 +---- docs/CONTACT.md | 8 +- docs/CURRENT_STATE.md | 49 ++++---- docs/DECISIONS.md | 10 ++ docs/DEPLOYMENT.md | 180 ++++++++++++----------------- docs/HANDOFF.md | 38 ++++-- docs/PROJECT_OVERVIEW.md | 4 +- docs/TASKS.md | 34 +++++- ops/swag/README.md | 9 +- scripts/check-deployment-config.py | 36 ++++++ 14 files changed, 230 insertions(+), 253 deletions(-) create mode 100644 scripts/check-deployment-config.py diff --git a/.env.example b/.env.example index 0d8bd72..d78342f 100644 --- a/.env.example +++ b/.env.example @@ -1,30 +1,8 @@ -APP_ENV=production -APP_URL=https://app.example.com -APP_SLUG=bortstack -REGISTRATION_MODE=open -SECRET_KEY=replace-with-a-long-random-value - -MYSQL_DATABASE=bortstack -MYSQL_USER=bortstack -MYSQL_PASSWORD=replace-with-a-strong-password -MYSQL_ROOT_PASSWORD=replace-with-a-different-strong-password -SQLALCHEMY_DATABASE_URI=mysql+pymysql://bortstack:replace-with-a-strong-password@mysql:3306/bortstack -SQLALCHEMY_ECHO=false -SQLALCHEMY_TRACK_MODIFICATIONS=false - -SESSION_COOKIE_SECURE=true -SESSION_COOKIE_HTTPONLY=true -SESSION_COOKIE_SAMESITE=Lax -CORS_ORIGINS=https://app.example.com - -RESEND_API_KEY=re_replace-with-a-resend-api-key -EMAIL_FROM="BortStack " -CONTACT_EMAIL=bortstack@roborto.net -EMAIL_DELIVERY_ENABLED=true -RATELIMIT_ENABLED=true -LOG_LEVEL=INFO -MAX_CONTENT_LENGTH=1048576 -GUNICORN_WORKERS=2 +CONTACT_EMAIL= +EMAIL_FROM= +RESEND_API_KEY= +EMAIL_DELIVERY_ENABLED=false +GUNICORN_WORKERS=1 GUNICORN_TIMEOUT=30 GUNICORN_GRACEFUL_TIMEOUT=30 GUNICORN_KEEPALIVE=5 diff --git a/.github/workflows/ci-deploy.yml b/.github/workflows/ci-deploy.yml index 3fb0f94..979dd8e 100644 --- a/.github/workflows/ci-deploy.yml +++ b/.github/workflows/ci-deploy.yml @@ -16,55 +16,15 @@ jobs: run: working-directory: api env: - APP_ENV: testing - SQLALCHEMY_DATABASE_URI: sqlite:///:memory: - SECRET_KEY: ci-test-key - REGISTRATION_MODE: open EMAIL_DELIVERY_ENABLED: "false" - RATELIMIT_ENABLED: "false" steps: - uses: actions/checkout@v5 - uses: actions/setup-python@v6 with: python-version: "3.12" - run: python -m pip install -r config/requirements-dev.txt - - run: pytest test_contact_independent.py - - run: pytest --cov --cov-report=term-missing - - backend-mysql: - runs-on: ubuntu-latest - defaults: - run: - working-directory: api - services: - mysql: - image: mysql:8.4 - env: - MYSQL_DATABASE: app_test - MYSQL_USER: app_test - MYSQL_PASSWORD: test-password - MYSQL_ROOT_PASSWORD: root-test-password - ports: ["3306:3306"] - options: >- - --health-cmd="mysqladmin ping -h localhost -uroot -proot-test-password --silent" - --health-interval=10s - --health-timeout=5s - --health-retries=10 - env: - APP_ENV: testing - SQLALCHEMY_DATABASE_URI: mysql+pymysql://app_test:test-password@127.0.0.1:3306/app_test - SECRET_KEY: ci-test-key - REGISTRATION_MODE: open - EMAIL_DELIVERY_ENABLED: "false" - RATELIMIT_ENABLED: "false" - steps: - - uses: actions/checkout@v5 - - uses: actions/setup-python@v6 - with: - python-version: "3.12" - - run: python -m pip install -r config/requirements-dev.txt - - run: flask --app api.py db upgrade - - run: pytest + - run: pytest --cov --cov-report=term-missing test_contact_independent.py + - run: python ../scripts/check-deployment-config.py frontend: runs-on: ubuntu-latest @@ -87,7 +47,7 @@ jobs: publish-images: if: github.ref == 'refs/heads/production' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') - needs: [backend, backend-mysql, frontend] + needs: [backend, frontend] runs-on: ubuntu-latest permissions: contents: read @@ -226,8 +186,6 @@ jobs: compose=(docker compose --env-file "$env_path") "${compose[@]}" config --quiet "${compose[@]}" pull api nginx - "${compose[@]}" up -d mysql - "${compose[@]}" run --rm --no-deps api flask --app api.py db upgrade "${compose[@]}" up -d --no-build api nginx "${compose[@]}" ps diff --git a/api/Dockerfile b/api/Dockerfile index b1e6aa1..ea74794 100644 --- a/api/Dockerfile +++ b/api/Dockerfile @@ -12,4 +12,4 @@ ENV HOME=/home/app \ PYTHONUNBUFFERED=1 USER app:app EXPOSE 5000 -CMD ["gunicorn", "--config", "gunicorn.conf.py", "api:app"] +CMD ["gunicorn", "--config", "gunicorn.conf.py", "contact_app:app"] diff --git a/api/gunicorn.conf.py b/api/gunicorn.conf.py index 6729537..b7b9082 100644 --- a/api/gunicorn.conf.py +++ b/api/gunicorn.conf.py @@ -1,12 +1,12 @@ -"""Environment-tunable Gunicorn defaults for the generic container.""" +"""Environment-tunable Gunicorn defaults for the Contact container.""" import os bind = "0.0.0.0:5000" -workers = int(os.environ.get("GUNICORN_WORKERS", "2")) +workers = int(os.environ.get("GUNICORN_WORKERS", "1")) timeout = int(os.environ.get("GUNICORN_TIMEOUT", "30")) graceful_timeout = int(os.environ.get("GUNICORN_GRACEFUL_TIMEOUT", "30")) keepalive = int(os.environ.get("GUNICORN_KEEPALIVE", "5")) errorlog = "-" -accesslog = None # Query strings may contain verification/reset tokens. +accesslog = None # Avoid logging visitor data or query strings. capture_output = False diff --git a/docker-compose.yml b/docker-compose.yml index f626ef7..4f73914 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,23 +1,4 @@ services: - mysql: - image: mysql:8.4 - restart: unless-stopped - environment: - MYSQL_DATABASE: ${MYSQL_DATABASE:?MYSQL_DATABASE must be set} - MYSQL_USER: ${MYSQL_USER:?MYSQL_USER must be set} - MYSQL_PASSWORD: ${MYSQL_PASSWORD:?MYSQL_PASSWORD must be set} - MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:?MYSQL_ROOT_PASSWORD must be set} - volumes: - - db:/var/lib/mysql - healthcheck: - test: ["CMD-SHELL", "mysqladmin ping -h localhost -uroot -p$$MYSQL_ROOT_PASSWORD --silent"] - interval: 10s - timeout: 5s - retries: 10 - start_period: 30s - networks: - - internal - api: image: ${API_IMAGE:-bortstack-api:local} build: @@ -34,9 +15,8 @@ services: - ALL env_file: - ${APP_ENV_FILE:-.env} - depends_on: - mysql: - condition: service_healthy + environment: + CONTACT_TRUST_PROXY: 'true' healthcheck: test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:5000/api/health/ready')"] interval: 15s @@ -79,6 +59,3 @@ networks: swag: external: true name: ${SWAG_NETWORK:-swagnet} - -volumes: - db: diff --git a/docs/CONTACT.md b/docs/CONTACT.md index ca6489a..484646b 100644 --- a/docs/CONTACT.md +++ b/docs/CONTACT.md @@ -1,13 +1,13 @@ # Contact service -BS-007 uses `api/contact_app.py:create_app`, exposed as `contact_app:app`. Start from api/ with existing requirements installed: `gunicorn --bind 127.0.0.1:5000 --workers 1 --timeout 20 contact_app:app`. Vite proxies /api to localhost:5000. The task Compose command selects this entry point explicitly. Existing api:app/account infrastructure and production Compose are unchanged provisional scaffolding; production adaptation remains BS-009, not ready for launch. +BS-007 uses `api/contact_app.py:create_app`, exposed as `contact_app:app`. Start from api/ with existing requirements installed: `gunicorn --bind 127.0.0.1:5000 --workers 1 --timeout 20 contact_app:app`. Vite proxies /api to localhost:5000. The task Compose command and BS-009 production image select this entry point. The account app remains in source but is outside the public runtime. Production is not commissioned. No SQLAlchemy, migrations, account routes or enquiry persistence. GET /api/contact/config returns only public email/null and delivery availability with no-store. Health/ready indicates service readiness, separate from mail configuration. POST /api/contact accepts JSON name (1–100), email (up to254), service (blank or one of four approved values), description (10–5000), and hidden website honeypot. Other keys/types rejected. 32KiB body limit. Errors are JSON: 400 fields/body, 413 oversized, 429 attempts, 503 disabled/unconfigured/provider failure; 200 success only after provider acknowledgement with ID. No enquiry content/provider error details logged. -Mail configuration is server-only: CONTACT_EMAIL = Captain-verified public inbox and recipient; EMAIL_FROM = verified Resend-domain sender; RESEND_API_KEY = secret; EMAIL_DELIVERY_ENABLED=true only when authorized/configured. Defaults are blank/disabled; no example mailbox is published. No live credentials or real sends used for this task. Configuration cannot independently prove sender/domain verification; Resend must accept the send. Do not put secrets in VITE variables. The separate inherited .env.example contains template values, not approved contact identity. +Mail configuration is server-only: CONTACT_EMAIL = Captain-verified public inbox and recipient; EMAIL_FROM = verified Resend-domain sender; RESEND_API_KEY = secret; EMAIL_DELIVERY_ENABLED=true only when authorized/configured. Defaults are blank/disabled; no example mailbox is published. No live credentials or real sends used for this task. Configuration cannot independently prove sender/domain verification; Resend must accept the send. Do not put secrets in VITE variables. The BS-009 `.env.example` has blank identities and delivery disabled. Direct Resend HTTPS call uses Python standard library, timeout10s, visitor email only as reply_to, fixed configured From/To, escaped HTML/plain text and service-derived subject. No new dependencies. Provider acknowledgement means accepted for delivery, not a guarantee of receipt. No automatic retries: draft and request key retained in the current page after failure; unchanged-draft retry uses the same UUID Idempotency-Key, edits create a fresh key. Browser timeout15s. Refresh/navigation loses unsent draft/key; no local-storage enquiry retention. Retry promptly without editing after uncertain outcome; provider idempotency expires after24h. Provider reference: https://resend.com/docs/dashboard/emails/idempotency-keys . -Limits: 5 attempts/hour and20/day per direct remote IP, including failures, held in memory per process; no rate-limit bypass from untrusted forwarding headers by default. CONTACT_TRUST_PROXY=true only behind one trusted proxy that sets/appends the real client IP and blocks direct external backend access. Task Compose enables it for local nginx; direct diagnostic port is loopback/test-only. Multiworker/multireplica global limits, production proxy/edge policy, provider data handling/privacy review and deployment authorization remain launch work. No claim of comprehensive spam prevention. +Limits: 5 attempts/hour and20/day per perceived remote IP, including failures, held in memory per process; no rate-limit bypass from untrusted forwarding headers by default. CONTACT_TRUST_PROXY=true only behind one trusted proxy that sets/appends the real client IP and blocks direct external backend access. Task and production Compose enable it for local nginx; direct diagnostic port is loopback/test-only. The actual SWAG-to-nginx client-IP chain must be verified before public submissions; shared proxy IPs can share a limit. Gunicorn defaults to one worker. Multiworker/multireplica global limits, production proxy/edge policy, provider data handling/privacy review and deployment authorization remain launch work. No claim of comprehensive spam prevention. -Validation: `python -m pytest test_contact_independent.py` in api/ exercises this app without account fixtures, plus existing `python -m pytest tests`. CI backend runs both. Browser success/failure are controlled responses; actual local Docker integration has delivery disabled. Manual review from project root: `./scripts/testtask.sh TASK-007`. Validate four fields, dark/light/mobile layout, empty-form errors and honest not-sent response with retained draft. Do not enter sensitive real enquiries into local test fixtures. +Validation: `python -m pytest test_contact_independent.py` in api/ exercises this app without account fixtures. CI gates this test plus the deployment topology check; inherited account tests are outside the public deployment gate. Browser success/failure are controlled responses; actual local Docker integration has delivery disabled. Manual review from project root: `./scripts/testtask.sh TASK-007`. Validate four fields, dark/light/mobile layout, empty-form errors and honest not-sent response with retained draft. Do not enter sensitive real enquiries into local test fixtures. diff --git a/docs/CURRENT_STATE.md b/docs/CURRENT_STATE.md index 038d94b..4832a14 100644 --- a/docs/CURRENT_STATE.md +++ b/docs/CURRENT_STATE.md @@ -1,31 +1,26 @@ # BortStack current state -BS-008 was accepted by Captain and integrated into `codex` at `ebfb10d` on 2026-11-12. Its privacy route describes confirmed Contact and theme flows and names Robert O'Reilly/support@bortstack.com for enquiry-data requests. The incomplete notice stays noindex pending lawful-basis, mail-backup, actual Resend account/DPA and legal review. The frontend prerenders nine public routes with static metadata and a noindex 404; matching pages hydrate. All 38 unit tests, lint, build and 27 offline browser/axe cases passed before acceptance; scoped pre-integration review found no blocker. Full server-backed nginx result was not supplied to Engineering. Canonical origin is unconfirmed, with no sitemap/canonical URLs approved. No push or deployment authorized. +Updated 2026-11-12. Integration `codex` is at `7ad054b` with BS-008 accepted +and merged. Captain accepted BS-009 on 2026-11-12. It is an uncommitted candidate in `.task-worktrees/bs-009` on +`bs-009`; it prepares database-free Contact/nginx production configuration, +workflow and operations documentation. It has not been integrated or deployed. +No new work was applied to the integration checkout. -Updated 2026-11-11 for BS-006. Integration codex at2660577 contains Captain-accepted public routing/themes, homepage composition, Services, About, Contact and responsive showcase footer (BS-001/002/003/004/007/011/012/013/014). All old task worktrees were removed after authorized cleanup; task branches/history remain. BS-006 is now engaged in .task-worktrees/bs-006 on bs-006 from2660577. No commit/merge/push/deployment authorized. +The public React/Vite frontend contains the approved marketing routes, theme, +homepage, Services, About, Contact, Projects and draft Privacy page. BS-008 +prerenders nine public routes and a noindex 404. The privacy notice remains +noindex pending legal and operational facts; canonical origin and sitemap are +unconfirmed. Contact is an independent Flask app with no database, bounded +Resend call, truthful disabled/unconfigured response and process-local limits. +The inherited account app remains in source but outside the public frontend +and BS-009 production entry point. API Admin remains a separate project. -## BS-006 candidate - -Projects gallery features RouletteBuddy, gives substantive PitchInvader coverage marked In development, and presents API Admin as a small showcase. Three reusable case-study routes include problem/solution/features/engineering/work-to-date sections. Curated copy grounded in read-only source inspection of ~/projects/{roulettebuddy,pitchinvader,api-admin}; API Admin uses SQLite, overriding concept-image MySQL. Genuine screenshots remain absent and explicitly pending, not replaced by concept imagery. Unknown slugs are unavailable/noindex. Homepage/shared header/footer/Contact/backend unchanged. See BS-006-DESIGN.md. - -## Existing Contact and launch boundaries - -Independent database-free Flask contact_app:app provides config/health/contact, four visible fields, hidden honeypot, server validation, bounded Resend provider acceptance, escaped email, verified sender/visitor Reply-To and idempotent same-draft retries. Process-local rate limits and disabled/unconfigured delivery returns503 remain intentional; no live mail tested. Accepted custom Service combobox replaces system popup. See CONTACT.md for configuration/privacy/production limits. - -Inherited account/database/production scaffolding is provisional; marketing remains independent of API Admin. Authentic logo/light artwork and project screenshots, verified email/sender/domain/API Admin destination, legal/SEO and production runtime remain launch gates. Existing lockfile alerts:10 (5moderate/3high/2critical); no dependency upgrades. No claim of production readiness or full WCAG compliance. - -## BS-006 diagnostics - -Lint, all38 unit tests (including5 new Projects tests), production build, whitespace and shell syntax checks passed. Existing unit TimeoutNaNWarning remains. Browser evidence and final manual-test snapshot recorded in HANDOFF.md and visual-qa/bs-006/. Captain controls dev-server and testtask startup; no runtime started by Engineering. Full server-backed Playwright and backend suite not run for this frontend-only task; no type-check script exists. Manual acceptance remains required. - -BS-006 live link refinement (2026-11-11): Captain authorized adding Visit RouletteBuddy to its featured entry and case-study header after https://roulettebuddy.app/ returned HTTP200 over validated HTTPS and RouletteBuddy title/canonical content. Standard same-tab external anchors preserve browser Back; case study remains first action. No external link invented for other projects. Earlier screenshots predate this refinement; refresh manual-test snapshot after validation. No server/commit/merge/deploy authorized. - -Live-link validation: final build/lint and5focused Projects tests passed. Offline Chromium at1440/320 in both themes confirmed exact URL/same-tab anchors on gallery and RouletteBuddy case study;20Projects-route axe/overflow checks plus20existing-route overflow checks/navigation passed with zero page errors. Mobile dark gallery and desktop light case-study screenshots inspected. Scoped review found no blocking defect. Full unit/server-backed browser suites not rerun for this link-only refinement. See visual-qa/bs-006/link-results.json and link-*.png; earlier screenshot matrix predates the link. Snapshot refreshed after documentation; restart TASK-006 if already testing. No server/commit/merge/deploy performed. - -## BS-006 Captain acceptance — 2026-11-11 - -Captain confirmed “task complete”, accepting the Projects gallery, three case studies and verified RouletteBuddy links with disclosed pending genuine screenshots. Manual acceptance gate satisfied. Integrated into codex through bc980e4 and dcda09; no push or deployment authorized. Previous pending-review statements are superseded. Existing screenshot/publication gates remain. - -## Worktree cleanup — 2026-11-11 - -Captain-authorized cleanup removed the nine earlier task worktrees after verifying their commits were ancestors of codex/2660577. Task branches/history remain retained; no active test processes or containers were found. This cleanup record predates and is preserved alongside the merged BS-006 mission. +BS-009 topology, Compose config, workflow YAML/job parsing, Python syntax and +whitespace validation passed locally with the safe sample environment. +The local Python environment lacks Flask, so the Contact unit suite has not +been run in this worktree. Captain controls dev-server and testtask startup; +no task runtime has been started by Engineering, and no runtime observations +were supplied with acceptance. Production SWAG/client-IP +behavior, mail settings and real inbox delivery are unverified. No commit, +merge, push or deployment is authorized. Authentic artwork, project media, +privacy review and other launch gates remain open. diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 720d715..f60b578 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -90,6 +90,16 @@ Within Captain-engaged BS-007, Contact uses a separate database-free Flask entry Captain instructed Engineering not to start the dev server itself. Prepare incomplete tasks for Captain to launch using the supported testtask command; do not independently start dev servers or test sessions unless Captain explicitly requests it. +## BS-ADR-007 — Database-free marketing deployment path (2026-11-12) + +Captain engaged BS-009 after confirming there is no business database. Production +Compose and image startup should run only the independent Contact app and the +marketing nginx frontend, behind the existing SWAG network. No MySQL or account +migration is part of the marketing deployment. Keep inherited account code in +source outside this task; CI production gates should target Contact and the +public frontend. Example mail delivery stays disabled with blank identities. +This is a configuration decision, not permission for production cutover. + ## BS-014 footer direction refinement (2026-11-11) Captain requested implementation of the proposed two-row footer: BortStack introduction and Services/Projects/About/Contact links above a separate copyright/Privacy row, using existing theme surfaces and restrained dividers. Text identity only until authentic artwork is available; API Admin link remains pending verified destination. diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 5784c2b..5b81966 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -1,118 +1,88 @@ -# Production Deployment +# Deployment plan — not commissioned -## Architecture +BS-009 prepares a database-free marketing deployment. No server, DNS, mail +provider or production GitHub environment has been changed by this task. Launch +still requires the Captain's explicit authorization and the gates below. -The supported production pattern is a Hetzner-hosted Docker Compose project: +## Topology -1. LinuxServer SWAG runs as the existing shared TLS reverse proxy on an external - Docker network (default `swagnet`). -2. The template's nginx container joins that network, serves the built React SPA, - and proxies `/api/` to the private API container. -3. Gunicorn serves Flask in the non-root API container. -4. MySQL persists to a named volume and is reachable only on the internal network. -5. Resend provides outbound transactional account/contact email from the generated project's `@roborto.net` product identity when explicitly enabled. -6. Cloudflare Email Routing receives mail sent to that product address and forwards it to the captain's private mail server; this inbound path is provisioned outside the repository. -7. GitHub Actions validates pull requests; pushes to `production` publish images - tagged with the tested commit SHA and deploy that exact commit and image set. +Docker Compose runs two services. `nginx` serves the prerendered React build and +proxies `/api/` to the private `api` service. The API image starts +`contact_app:app` under Gunicorn; it has no account routes, SQLAlchemy startup, +database, migration or persistent enquiry store. The existing LinuxServer SWAG +instance should terminate public TLS and reach `nginx:80` over the external +network named by `SWAG_NETWORK` (default `swagnet`). The API is on the internal +network only. Port 8081 (web) and 5001 (API) bind to host loopback for local +diagnostics. No public hostname has been confirmed. -## Server prerequisites +`/api/health/ready` confirms that the Contact process can serve requests; it +does **not** confirm email configuration, provider delivery or inbox receipt. +`/api/contact/config` reports whether the configured mail settings are present; +that is not a provider or inbox test. The sample environment disables mail and +leaves sender, recipient and API key blank. Contact responds with 503 when +delivery is disabled or unconfigured. -- Docker Engine with the Compose plugin. -- A running SWAG stack and external Docker network matching `SWAG_NETWORK`. -- A clean clone on branch `production` at the path stored in the GitHub variable - `PRODUCTION_DEPLOY_PATH`. -- A mode-`600` production environment file outside the repository at the path in - `PRODUCTION_ENV_PATH`. -- A deployment user able to run Docker without an interactive prompt and pull - the repository's GHCR packages. -- A verified SSH host key and dedicated deployment key. +## Server and GitHub prerequisites -Use `.env.example` only as a variable-name reference. Generate unique secrets and -never commit the production file. +- Docker Engine with Compose and an existing SWAG stack on the configured + external network; validate the final SWAG proxy configuration and TLS. +- A clean `production` branch checkout at `PRODUCTION_DEPLOY_PATH`, a readable + external mode-600 environment file at `PRODUCTION_ENV_PATH`, and a deployment + user with Docker and GHCR pull access. +- GitHub Actions secrets `PRODUCTION_SSH_HOST`, `PRODUCTION_SSH_USER`, + `PRODUCTION_SSH_PRIVATE_KEY`, `PRODUCTION_SSH_KNOWN_HOSTS`; variables + `PRODUCTION_DEPLOY_PATH`, `PRODUCTION_ENV_PATH`, `PRODUCTION_PUBLIC_URL`. + Confirm the public URL before enabling this path. -## Product email commissioning +The current workflow runs on `production` pushes and manual dispatch, publishes +commit-tagged API/nginx images, fast-forwards a clean server checkout, pulls and +starts the two services, then probes the loopback web endpoint and public Contact +readiness. Protect the branch and `production` environment before using that +trigger. The workflow is **configured**, not evidence of a successful release. +It does not perform automatic rollback. -The generator derives a product mailbox from the project slug. For example, a project named `Example Product` receives `example-product@roborto.net` as both the example Resend sender address and contact destination. The visible sender name remains independently configurable in `EMAIL_FROM`. +## Commissioning sequence -Before setting `EMAIL_DELIVERY_ENABLED=true` in production: +1. Confirm the public hostname, SWAG network/proxy configuration, host capacity, + firewall, GHCR access, TLS and external environment file. Use `.env.example` + only as a variable reference; keep real settings and secrets outside Git. +2. With mail disabled, validate + `APP_ENV_FILE=/path/to/env docker compose --env-file /path/to/env config --quiet` + and `python3 scripts/check-deployment-config.py` in a checkout containing + the candidate. The script validates the safe example topology, not the + server's secrets or connectivity. +3. On a separately authorized deployment, start `api` and `nginx` using the + tested images. Probe `/`, a known static route, an unknown route, local + `/api/health/ready`, public `/api/health/ready`, and + `/api/contact/config`. Confirm an unconfigured submission cannot report + success. Check container health and logs without recording visitor data. +4. Before enabling delivery, verify a BortStack sender/domain with Resend, + verify the intended recipient mailbox and incoming routing, configure + credentials outside Git, then make a controlled enquiry and confirm inbox + receipt and visitor Reply-To. Provider acceptance alone is insufficient. +5. Complete privacy/legal, authentic media, domain/SEO, backup/retention and + production readiness review. Record the deployed commit/image tags and + operator observations. Captain acceptance and launch authority remain + separate from CI checks. -1. Confirm the generated address and reserve it for the product. -2. Verify the required `roborto.net` sending identity and DNS records with Resend using the captain's existing domain-management process. -3. Create the matching Cloudflare Email Routing rule and point it to the intended mailbox on the captain's private mail system. -4. Confirm inbound delivery from an unrelated external account; a successful Resend API call does not prove inbound routing works. -5. Send verification and password-reset messages to test users and confirm links use the production `APP_URL`. -6. Submit the public contact form, confirm delivery to the product mailbox, and verify that replying targets the visitor address supplied through `Reply-To`. -7. Record the sender identity, routing owner, destination owner, and test date without storing API keys, mailbox credentials, or DNS secrets in the repository. +Do not copy inherited account/MySQL keys from an old deployment file. Existing +MySQL containers or volumes from an earlier stack require a separate inventory +and explicit disposal plan; changing Compose does not authorize deleting them. -Resend handles application-originated outbound mail; Cloudflare Email Routing handles inbound mail. The application does not host an SMTP receiver, read the destination mailbox, or provision either provider. Keep `RESEND_API_KEY` and all private-mail-server credentials outside Git. +## Operations and rollback -## GitHub configuration +Gunicorn defaults to one worker because Contact's attempt limits are held in +process memory (5/hour and 20/day per perceived IP). Multiple workers or +replicas require a shared limiter before scaling. Nginx forwards one proxy hop +to Contact; verify the real client IP through the actual SWAG chain before +enabling public submissions. A shared proxy IP can cause unrelated visitors to +share the limit. Do not trust arbitrary incoming forwarding headers. The +sample SWAG config is a starting point, not a verified host configuration. -Configure these Actions secrets: - -- `PRODUCTION_SSH_HOST` -- `PRODUCTION_SSH_USER` -- `PRODUCTION_SSH_PRIVATE_KEY` -- `PRODUCTION_SSH_KNOWN_HOSTS` - -Configure these repository or `production` environment variables: - -- `PRODUCTION_DEPLOY_PATH`, for example `/home/deploy/example-app` -- `PRODUCTION_ENV_PATH`, for example `/opt/example-app/.env` -- `PRODUCTION_PUBLIC_URL`, for example `https://app.example.com` - -The workflow refuses a dirty remote checkout or a branch other than `production`, -fast-forwards to the tested commit, runs migrations from the immutable API image, -and checks the local frontend plus the public health endpoint. Protect the -`production` environment/branch where the GitHub plan permits it. - -## SWAG - -Adapt `ops/swag/app.subdomain.conf.sample` to the desired SWAG hostname convention. -SWAG should proxy to the Compose `nginx` service on port 80 over the shared network. -Do not expose MySQL. Loopback-bound ports 8081 and 5001 are provided only for -server-local diagnostics. - -## Manual first deployment - -1. Copy `.env.example` to the external production path and replace every example. -2. Create the configured MySQL database volume and external SWAG network through - the normal Compose/SWAG lifecycle. -3. Run `docker compose --env-file /path/to/.env config --quiet`. -4. Start MySQL, run `flask --app api.py db upgrade` from the API image, then start - the API and nginx services. -5. Confirm `/api/health/live` and `/api/health/ready` locally and through the public URL. - -## Health and logs - -- `/api/health` and `/api/health/live` prove that Flask can serve a request; they do not query external dependencies. -- `/api/health/ready` executes a minimal database query and returns `503` without database details when persistence is unavailable. Compose and deployment verification use this readiness endpoint. -- Application events use one-line JSON on standard error with timestamp, severity, logger, and generic message. Account tokens, request bodies, contact contents, email addresses, credentials, and provider/database exception details must not be added to logs. -- Container logs remain the default collection boundary. Add a host-level retention/forwarding policy before production; this template does not select an external observability vendor. - -Use liveness for process restarts and readiness for routing/deployment gates. A healthy probe does not prove registration, email delivery, authentication, or every migration is correct. - -## Deployment failure and rollback - -The workflow stops on failed configuration, pull, migration, service update, or health verification. Because database migrations may be forward-only, application rollback and schema rollback are separate decisions. - -Before each production deployment: - -1. Confirm a recent recoverable database backup and record the current commit and immutable image tags. -2. Review the pending migration upgrade and downgrade operations against disposable data. -3. Confirm the previous API/nginx image tags remain pullable. - -For an application-only rollback, set `API_IMAGE` and `NGINX_IMAGE` to the previously verified commit tags in the external environment/deployment invocation, restore the corresponding clean Git commit, run `docker compose config --quiet`, and update the API/nginx services. Do not run a database downgrade automatically. - -If the previous application is incompatible with the migrated schema, keep the new application stopped or in maintenance mode while following a migration-specific recovery plan. Restore into disposable infrastructure first; never overwrite the production volume merely because a deployment health check failed. - -## Security and proxy boundaries - -- SWAG is the sole public TLS boundary. MySQL is internal-only; diagnostic API/nginx ports bind to loopback. -- Nginx preserves the trusted upstream `X-Forwarded-Proto` value from SWAG and replaces client forwarding headers at the application boundary. Flask trusts exactly one nginx proxy hop. -- Production startup rejects wildcard CORS, short secret keys, SQLAlchemy query logging, and insecure `SameSite=None` cookie configuration. -- Nginx applies frame, MIME-sniffing, referrer, and browser-permission headers. Add a project-specific Content Security Policy only after inventorying required scripts, styles, fonts, frames, and external origins. -- Review host firewalling, Docker daemon access, SSH key scope, GHCR package access, log retention, disk alerts, resource limits, and security updates before launch. - -Production provisioning, Resend identity verification, and DNS/Cloudflare changes remain deliberate operator -actions; this repository does not create or mutate external infrastructure. +Logs are container output; define host retention, monitoring and recovery +procedures before launch. There is no application database to back up, but +mailbox records, server configuration and external service recovery still need +an operator plan. For rollback, retain the previous verified commit and image +tags, restore their clean checkout and external image overrides, validate +Compose, restart the two services and repeat probes. Do not delete resources +or assume that a successful health probe proves mail delivery. diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index e16bc12..7d6ae1b 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -1,13 +1,31 @@ -# BortStack handoff — BS-008 integrated +# BortStack handoff — BS-009 candidate -Updated 2026-11-12. Integration root `/home/rob/projects/bortstack` is on `codex`. Captain accepted BS-008 and explicitly ordered commit and merge. Scoped pre-integration Code Review found no blocking defect. Task commit `ebfb10d` was fast-forwarded into `codex`; this context refresh follows it. No push, release or production deployment authorized. Retain `bs-008` and its worktree; no cleanup order was given. BS-006 history remains in Git and its retained task worktree. +Updated 2026-11-12. Integration root is clean on `codex` at `7ad054b` after +Captain-authorized BS-008 integration. BS-009 is engaged in isolated +`.task-worktrees/bs-009` on `bs-009`, based on that commit. The worktree was +clean before BS-009 edits. Captain accepted the candidate with “task complete” +on 2026-11-12 without supplying runtime observations. No commit, merge, push, +release or production deployment. BS-006 and BS-008 worktrees remain retained. -BS-008 covers the approved marketing site and independent Contact service, excluding inherited account scaffolding. `/privacy` is a factual draft naming Robert O'Reilly and `support@bortstack.com`, describing enquiry/theme flows, a 12-month review for non-client enquiries, Hetzner mail in Helsinki, and Resend's published US storage/transfer arrangement. It is `noindex` and explicitly incomplete. Captain's private address is not published. Full legal review, lawful basis, mail backup retention, configured Resend plan/DPA, verified email delivery, and production hosting remain publication gates. Captain may publish the website before planned January 2027 sole-trader operations and accept enquiries to plan work; production remains unauthorized. +BS-009 adapts production Compose from inherited MySQL/account startup to the +independent `contact_app:app` and marketing nginx. It removes MySQL service, +volume, migration command and MySQL CI gate; keeps the external SWAG network +and loopback diagnostics. The sample environment has blank mail identities and +delivery disabled. CI runs Contact tests and a database-free topology check; +the public frontend job remains. `docs/DEPLOYMENT.md` now describes the +planned topology, commissioning sequence, limits and rollback. Inherited +account source remains untouched. No external infrastructure has been changed. -The frontend build now emits static HTML with route metadata for nine public routes plus a noindex 404 page. Matching pages hydrate; unknown paths receive 404 from the changed nginx configuration and client-render recovery. No new dependency. Canonical origin is unconfirmed, so canonical URLs and sitemap are deferred. Do not claim live nginx behavior until the Captain-controlled runtime is checked. - -Pre-acceptance validation: 38 unit tests, lint, build, 27 offline Chromium route/viewport/axe checks, Compose configuration and whitespace checks passed. Browser checks included 1440/390/320 widths, light privacy contrast, static metadata, hydration and simulated 404 status. Contact config was mocked unavailable. `scripts/check-privacy-build.cjs` is the repeatable offline check. Full server-backed Playwright/nginx and real email delivery were not run by Engineering; the Captain did not supply actual testtask observations. No checks were rerun for the acceptance/integration-only turn. - -The exact BS-008 manual-test snapshot was refreshed before integration (342 verified files). Task runtime is Captain-controlled: `./scripts/testtask.sh TASK-008` from the integration root opens `/privacy`; it must be restarted after any future source change. The snapshot is test-only, not an editing source. No server or testtask runtime was started by Engineering. - -Next proposed missions remain BS-009 deployment topology/regression and BS-010 final visual/launch prep; neither is engaged here. Authentic logo/project media, legal/domain/email choices and production readiness remain separate gates. See `docs/TASKS.md`, `docs/DECISIONS.md`, `docs/CONTACT.md` and `docs/TEMPLATE_RECONCILIATION.md` for durable scope and limitations. +At this handoff, local `python3 scripts/check-deployment-config.py`, Compose +config, workflow YAML/job parsing, Python syntax and `git diff --check` passed. +The Contact unit suite could not collect because local Python lacks Flask; +CI has not run. The candidate is Captain-accepted, awaiting separately +authorized commit/integration. The exact test-only snapshot was +prepared with 343 verified files at `.test-worktrees/task-009`. The acceptance +context edits postdate the snapshot; its refresh is currently refused because +another test session owns the snapshot lock. Refresh it after that session ends. +No testtask or dev server was started by Engineering; +Captain controls startup under BS-ADR-006. Real SWAG client-IP forwarding, +host access, sender/domain, inbox delivery, privacy review and launch authority +remain open. Health checks alone do not prove delivery. See `docs/TASKS.md`, +`docs/CONTACT.md` and `docs/DEPLOYMENT.md`. diff --git a/docs/PROJECT_OVERVIEW.md b/docs/PROJECT_OVERVIEW.md index e06f93e..d529ee8 100644 --- a/docs/PROJECT_OVERVIEW.md +++ b/docs/PROJECT_OVERVIEW.md @@ -10,13 +10,13 @@ Public routes: `/`, `/services`, `/projects`, `/projects/:slug`, `/about`, `/con Homepage follows the approved spacious dark reference: split hero, concise services, one genuine featured project, short Why BortStack section and contact CTA. Dark default, optional persistent light mode applied before first paint. Exact Concept 2 identity and approved palette are authoritative; master assets are missing. -Contact has exactly four visible fields: required name/email/description and optional service. Flask validates server-side, uses honeypot/rate limiting and Resend with verified sender and visitor Reply-To. Business email remains configurable and unverified. BS-007 candidate supplies database-free contact_app:app, bounded provider acceptance and same-draft idempotent retries; production adaptation remains separate. See CONTACT.md. +Contact has exactly four visible fields: required name/email/description and optional service. Flask validates server-side, uses honeypot/rate limiting and Resend with verified sender and visitor Reply-To. Business email remains configurable and unverified. BS-007 supplies database-free contact_app:app, bounded provider acceptance and same-draft idempotent retries. BS-009 prepares its production Compose path without commissioning it. See CONTACT.md. ## Foundation and boundaries Generated from maintained `flask-react-auth-base` using its supported generator. React/Vite/React-Bootstrap/SCSS under `react/`; Flask under `api/`; Docker Compose/nginx/SWAG scaffolding. Inherited backend code still includes SQLAlchemy, MySQL, accounts, tests and CI/deployment scaffolding; these are not approved marketing functionality. The accepted integrated frontend removes public account routes/session coupling and implements the marketing shell/themes/corrected homepage, Services and About, with explicit missing-asset placeholders. See TEMPLATE_RECONCILIATION.md for precise gaps and later task ownership. -Public pages should be static/prerendered for SEO; technique remains unresolved. Target deployment pattern is Compose behind SWAG with Cloudflare DNS, subject to explicit authorization and verified hosting. Domain, email identity, legal content and portfolio permissions are unresolved. +Public pages are prerendered for route-specific metadata and hydrate on known routes. Target deployment pattern is database-free Compose behind SWAG with Cloudflare DNS, subject to explicit authorization and verified hosting. Domain, email identity, legal content and portfolio permissions are unresolved. API Admin remains a separate repository/application/deployment with no authentication, database or uptime coupling. No CMS, blog engine, customer portal, billing, marketplace, public account system or consent-dependent analytics in V1. diff --git a/docs/TASKS.md b/docs/TASKS.md index cb2df3f..58c48c1 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -45,11 +45,43 @@ Deviation/asset gate: reference photograph replaced by restrained decorative CSS | BS-006 | Projects gallery and case studies — engaged 2026-11-11; see detailed task below | Captain review; genuine imagery pending | | BS-007 | Contact UI and Flask service — engaged; see detailed task below | Captain manual review; verified mail configuration before real delivery | | BS-008 | Privacy/legal, SEO and accessibility — Captain accepted 2026-11-12; see mission note below | Complete in `codex`; publication gates remain | -| BS-009 | Docker/SWAG plan and regression tests | Adapt production database-free topology/readiness; no live cutover. Existing manual-test runtime already operational | +| BS-009 | Docker/SWAG plan and regression tests — Captain accepted 2026-11-12; see mission note below | Accepted, awaiting authorized commit/integration; no live cutover | | BS-010 | Final visual reconciliation and launch prep | Authentic brand/media, verified contact/domain and final review | ## Lifecycle and constraints +## BS-009 mission — database-free deployment path + +Status: Captain accepted the BS-009 candidate with “task complete” on 2026-11-12. +Awaiting separate commit/integration authority on `bs-009` in `.task-worktrees/bs-009`, based on clean +`codex` at `7ad054b`. Captain engaged the task on 2026-11-12. No commit, merge, +push, release or production deployment authorized. + +Objective: make the production deployment path match the independent Contact +service and marketing frontend. Scope: production Compose and API image entry +point, safe environment example, CI/deployment commands, SWAG/operations plan +and topology regression check. Non-goals: removing inherited account source, +changing Contact contract or public pages, choosing a hostname or email +identity, provisioning SWAG/DNS, live email, migration of old resources or +production cutover. + +Acceptance: Compose resolves to only `api` and `nginx`, with private Contact +API and external SWAG link; API starts `contact_app:app` with database-free +readiness; CI requires no MySQL service or account migration; deployment starts +and checks only those two services; sample mail remains disabled; docs distinguish +process health from delivery and list unverified commissioning gates. Validate +Compose config/topology script, Contact unit tests where dependencies are +available, workflow/static diff checks, and Captain-controlled manual runtime +as requested. Local results: topology script, Compose config, workflow YAML/job +parse, Python syntax and `git diff --check` passed. Contact pytest could not +collect because local Python lacks Flask; CI has not run. No frontend code or +runtime was changed/started. Risks/dependencies: actual SWAG forwarding/client IP, verified +domain/inbox/Resend settings, host/GHCR access and production authorization. +Captain acceptance did not include runtime observations or authorization to +commit, merge, push or deploy. The `/api/health`, `/api/health/live` and +`/api/health/ready` aliases return the same process status; manual review can +focus on page loading and honest disabled-mail behavior. + ## BS-008 mission — privacy, SEO and accessibility Status: Complete in `codex` through Captain-authorized commit/fast-forward merge on 2026-11-12 (`ebfb10d`). Captain accepted the BS-008 candidate with “task complete” and then explicitly ordered commit and merge. Task branch/worktree `bs-008` at `.task-worktrees/bs-008` remains for history; no cleanup, push or deployment authorized. Captain engaged the task on 2026-11-11. Scope confirmed as the approved public marketing site and independent Contact service, excluding inherited account scaffolding. Captain will not publish a private address. Canonical origin remains unconfirmed. Resend's published GDPR information says message content and delivery records are stored in the US under its DPA/SCCs; verify the actual account plan and DPA before publication: https://resend.com/security/gdpr/ . diff --git a/ops/swag/README.md b/ops/swag/README.md index ebff7b3..23007ad 100644 --- a/ops/swag/README.md +++ b/ops/swag/README.md @@ -10,6 +10,9 @@ replace the placeholder domain settings using normal SWAG conventions, and restart or reload SWAG. The exact SWAG filesystem location is a server concern and is intentionally not encoded in this repository. -Do not expose MySQL publicly. The loopback API and frontend port mappings exist -for server-local health diagnostics; SWAG should reach the frontend by Docker -service name over the external network. +The API is private on the Compose internal network. Loopback API and frontend +ports exist for server-local diagnostics; SWAG should reach the frontend by +Docker service name over the external network. Confirm the real client IP and +forwarded scheme at the Contact API before enabling submissions. The sample +hostname is illustrative; the public hostname is not confirmed. See +`docs/DEPLOYMENT.md` for commissioning gates. diff --git a/scripts/check-deployment-config.py b/scripts/check-deployment-config.py new file mode 100644 index 0000000..74d66a5 --- /dev/null +++ b/scripts/check-deployment-config.py @@ -0,0 +1,36 @@ +"""Check the public deployment topology without starting containers.""" + +import json +import os +import subprocess +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +env = os.environ.copy() +env["APP_ENV_FILE"] = str(ROOT / ".env.example") +result = subprocess.run( + ["docker", "compose", "--env-file", str(ROOT / ".env.example"), + "config", "--format", "json"], + cwd=ROOT, env=env, check=True, capture_output=True, text=True, +) +config = json.loads(result.stdout) +services = config["services"] +assert set(services) == {"api", "nginx"}, sorted(services) +assert not config.get("volumes"), "Production topology must not require a database volume" +api = services["api"] +web = services["nginx"] +assert api.get("environment", {}).get("EMAIL_DELIVERY_ENABLED") == "false" +assert api["environment"]["CONTACT_TRUST_PROXY"] == "true" +assert not api.get("depends_on"), "Contact must have no database dependency" +assert web["depends_on"]["api"]["condition"] == "service_healthy" +assert "api/health/ready" in " ".join(api["healthcheck"]["test"]) +assert config["networks"]["swag"]["external"] is True +assert "swag" in web["networks"] +assert "swag" not in api["networks"] +assert config["networks"]["internal"]["internal"] is True +assert "internal" in api["networks"] and "internal" in web["networks"] +assert all(port["host_ip"] == "127.0.0.1" for service in (api, web) + for port in service["ports"]), "Diagnostic ports must bind to loopback" +assert "contact_app:app" in (ROOT / "api" / "Dockerfile").read_text() +print("Database-free Contact deployment topology: OK")