From 5bfb128e945f3a5cb434cdd291af0faf7d3e4dae Mon Sep 17 00:00:00 2001 From: rob Date: Tue, 10 Nov 2026 19:45:11 +0000 Subject: [PATCH] BS-007 Implement accepted Contact page and independent enquiry service --- .github/workflows/ci-deploy.yml | 1 + .roborto/testtask-compose.yml | 8 +- .roborto/testtask-hook | 2 +- .roborto/testtask.conf | 2 +- AGENTS.md | 2 +- api/contact_app.py | 129 ++++++++++++ api/test_contact_independent.py | 103 ++++++++++ docs/CONTACT.md | 13 ++ docs/CURRENT_STATE.md | 26 ++- docs/DECISIONS.md | 10 + docs/HANDOFF.md | 26 +-- docs/PROJECT_OVERVIEW.md | 4 +- docs/TASKS.md | 37 +++- docs/TESTTASK.md | 3 +- .../BortStack Projects Showcase-2.png | Bin 0 -> 1638209 bytes docs/references/about-concept.png | Bin 0 -> 1659688 bytes docs/references/contact-concept.png | Bin 0 -> 1540456 bytes docs/references/home-approved-direction.png | Bin 0 -> 1647741 bytes docs/references/services-concept.png | Bin 0 -> 1618920 bytes docs/visual-qa/bs-007/AUDIT.md | 11 ++ docs/visual-qa/bs-007/about-regression.png | Bin 0 -> 353997 bytes docs/visual-qa/bs-007/after-1536-full.png | Bin 0 -> 414927 bytes docs/visual-qa/bs-007/before-1536.png | Bin 0 -> 36148 bytes docs/visual-qa/bs-007/desktop-1440-full.png | Bin 0 -> 395453 bytes docs/visual-qa/bs-007/homepage-regression.png | Bin 0 -> 356746 bytes docs/visual-qa/bs-007/light-1536-full.png | Bin 0 -> 382368 bytes docs/visual-qa/bs-007/measurements.json | 104 ++++++++++ docs/visual-qa/bs-007/mobile-390-full.png | Bin 0 -> 223366 bytes docs/visual-qa/bs-007/narrow-320-full.png | Bin 0 -> 198164 bytes .../service-open-chromium-dark-1536.png | Bin 0 -> 402680 bytes .../bs-007/service-open-chromium-dark-390.png | Bin 0 -> 226479 bytes .../service-open-chromium-light-1536.png | Bin 0 -> 370823 bytes docs/visual-qa/bs-007/services-regression.png | Bin 0 -> 386402 bytes docs/visual-qa/bs-007/tablet-768-full.png | Bin 0 -> 302905 bytes react/e2e/about.spec.js | 2 +- react/e2e/contact.spec.js | 150 ++++++++++++++ react/e2e/homepage.spec.js | 2 +- react/e2e/public-shell.spec.js | 4 +- react/e2e/services.spec.js | 2 +- react/e2e/themes.spec.js | 2 +- react/src/App.jsx | 3 +- react/src/views/Contact/Contact.jsx | 183 +++++++++++------- react/src/views/Contact/Contact.module.scss | 68 +++++-- react/src/views/Contact/ServiceSelect.jsx | 57 ++++++ react/src/views/MarketingRoutes.test.jsx | 14 +- react/src/views/PublicPages.test.jsx | 14 +- 46 files changed, 837 insertions(+), 145 deletions(-) create mode 100644 api/contact_app.py create mode 100644 api/test_contact_independent.py create mode 100644 docs/CONTACT.md create mode 100644 docs/references/BortStack Projects Showcase-2.png create mode 100644 docs/references/about-concept.png create mode 100644 docs/references/contact-concept.png create mode 100644 docs/references/home-approved-direction.png create mode 100644 docs/references/services-concept.png create mode 100644 docs/visual-qa/bs-007/AUDIT.md create mode 100644 docs/visual-qa/bs-007/about-regression.png create mode 100644 docs/visual-qa/bs-007/after-1536-full.png create mode 100644 docs/visual-qa/bs-007/before-1536.png create mode 100644 docs/visual-qa/bs-007/desktop-1440-full.png create mode 100644 docs/visual-qa/bs-007/homepage-regression.png create mode 100644 docs/visual-qa/bs-007/light-1536-full.png create mode 100644 docs/visual-qa/bs-007/measurements.json create mode 100644 docs/visual-qa/bs-007/mobile-390-full.png create mode 100644 docs/visual-qa/bs-007/narrow-320-full.png create mode 100644 docs/visual-qa/bs-007/service-open-chromium-dark-1536.png create mode 100644 docs/visual-qa/bs-007/service-open-chromium-dark-390.png create mode 100644 docs/visual-qa/bs-007/service-open-chromium-light-1536.png create mode 100644 docs/visual-qa/bs-007/services-regression.png create mode 100644 docs/visual-qa/bs-007/tablet-768-full.png create mode 100644 react/e2e/contact.spec.js create mode 100644 react/src/views/Contact/ServiceSelect.jsx diff --git a/.github/workflows/ci-deploy.yml b/.github/workflows/ci-deploy.yml index 35b76c6..3fb0f94 100644 --- a/.github/workflows/ci-deploy.yml +++ b/.github/workflows/ci-deploy.yml @@ -28,6 +28,7 @@ jobs: 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: diff --git a/.roborto/testtask-compose.yml b/.roborto/testtask-compose.yml index 5358068..8ffc80d 100644 --- a/.roborto/testtask-compose.yml +++ b/.roborto/testtask-compose.yml @@ -1,4 +1,4 @@ -# Isolated manual-test runtime only. No SWAG, production env, external networks or mail. +# Isolated database-free Contact runtime. No SWAG, production env or outbound mail. services: api: build: @@ -8,11 +8,9 @@ services: DEBUG: 'false' APP_URL: http://127.0.0.1:18081 CORS_ORIGINS: http://127.0.0.1:18081 - SQLALCHEMY_DATABASE_URI: sqlite:////tmp/testtask.sqlite EMAIL_DELIVERY_ENABLED: 'false' - REGISTRATION_MODE: closed - SECRET_KEY: disposable-local-testtask-key-not-for-production - command: [sh, -c, 'flask --app api.py db upgrade && exec gunicorn --bind 0.0.0.0:5000 --workers 1 api:app'] + CONTACT_TRUST_PROXY: 'true' + command: [gunicorn, --bind, '0.0.0.0:5000', --workers, '1', --timeout, '20', contact_app:app] tmpfs: - /tmp:mode=1777 ports: diff --git a/.roborto/testtask-hook b/.roborto/testtask-hook index eda14f4..c8d8e9b 100755 --- a/.roborto/testtask-hook +++ b/.roborto/testtask-hook @@ -56,7 +56,7 @@ import urllib.request for url in ['http://127.0.0.1:15001/api/health/ready', 'http://127.0.0.1:18081/', 'http://127.0.0.1:18081/api/health/ready']: with urllib.request.urlopen(url, timeout=10) as response: assert response.status == 200, url -print('Ready: http://127.0.0.1:18081/ — inherited starter; registration closed, email disabled; no login required.') +print('Ready: http://127.0.0.1:18081/ — BortStack marketing; database-free Contact runtime, delivery disabled; no login required.') PY ;; cleanup) diff --git a/.roborto/testtask.conf b/.roborto/testtask.conf index d94113c..d09ba95 100644 --- a/.roborto/testtask.conf +++ b/.roborto/testtask.conf @@ -4,6 +4,6 @@ ROBORTO_TASK_ID_PATTERN='^[0-9]{3}$' ROBORTO_WORKTREE="${ROBORTO_PROJECT_ROOT}/.test-worktrees/task-${ROBORTO_TASK_ID}" ROBORTO_HOOK="${ROBORTO_PROJECT_ROOT}/.roborto/testtask-hook" # Loopback-only manual testing; fixed ports prevent concurrent conflicting sessions. -ROBORTO_BROWSER_URL="http://127.0.0.1:18081/about" +ROBORTO_BROWSER_URL="http://127.0.0.1:18081/contact" ROBORTO_READY_PORTS=(15001 18081) ROBORTO_READY_LABELS=(API Web) diff --git a/AGENTS.md b/AGENTS.md index ad7d9b8..800c510 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -91,7 +91,7 @@ Report files and behaviour changed; tests added or updated; commands run; test, - Captain's newest explicit instructions govern intended changes. Code/configuration prove observed behavior; report conflicts with plans rather than treating inherited behavior as approved product scope. - Integration branch: `codex`. Task IDs: `BS-###`; branches: `bs-###`; isolated implementation worktrees: `.task-worktrees/bs-###` under the integration checkout. One accepted, scoped task per branch/worktree. Report path, branch, status and existing changes before edits. - No commit, push, merge, rebase, release or production deployment without explicit authorization. Green checks mean implementation-ready, not Complete. Captain review/manual acceptance and the authorized integration process are required for Complete. -- Current accepted tasks and Captain authorizations are recorded in docs/TASKS.md and the latest handoff. On 2026-11-10 Captain accepted Services and authorized integration of its dependency stack (BS-002/003/004/011/012). BS-013 About was manually accepted by Captain on 2026-11-10 with explicit commit/merge authorization. Future commits/merges and production deployment require the applicable explicit authorization. Original CODEX_HANDOFF.md is historical input; its instruction to continue automatically is superseded. +- Current accepted tasks and Captain authorizations are recorded in docs/TASKS.md and the latest handoff. On 2026-11-10 Captain accepted Services and authorized integration of its dependency stack (BS-002/003/004/011/012). BS-013 About was manually accepted by Captain on 2026-11-10 with explicit commit/merge authorization. BS-007 Contact was manually accepted by Captain on 2026-11-10, followed by explicit commit-all/merge authorization. Production remains unauthorized. Future commits/merges and production deployment require the applicable explicit authorization. Original CODEX_HANDOFF.md is historical input; its instruction to continue automatically is superseded. - Canonical maintained context lives in `docs/{PROJECT_OVERVIEW,CURRENT_STATE,DECISIONS,TASKS,HANDOFF}.md`; root counterparts are navigation pointers. Read all at entry and refresh after meaningful work. Original handoff text is preserved in `docs/source-handoff/`. - Design authority: `brand/BORTSTACK_BRAND_DECISION.md`, authentic master artwork when supplied, `assets/references/home-approved-direction.png`, `DESIGN_SPEC.md` and approved brand tokens. Reference images are concepts, never authentic logos or project screenshots. Never invent replacement logo artwork. - Marketing website remains independent of API Admin. Inherited authentication, database, branding and deployment scaffolding are provisional; see `docs/TEMPLATE_RECONCILIATION.md`. Preserve existing behaviour outside the accepted task; do not resolve later tasks during bootstrap. diff --git a/api/contact_app.py b/api/contact_app.py new file mode 100644 index 0000000..627ccf4 --- /dev/null +++ b/api/contact_app.py @@ -0,0 +1,129 @@ +"""Independent, database-free BortStack enquiry service. No account imports.""" +import json +import os +import re +from email.utils import parseaddr +from html import escape +from urllib.request import Request, urlopen +from uuid import UUID + +from flask import Flask, request +from flask_limiter import Limiter +from flask_limiter.util import get_remote_address +from werkzeug.middleware.proxy_fix import ProxyFix + +SERVICES = ('Website Development', 'Custom Software & Web Applications', + 'API Development & Integration', 'Managed Hosting & Maintenance') + + +def valid_email(value): + return (isinstance(value, str) and len(value) <= 254 + and re.fullmatch(r"[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+", value) is not None) + + +def deliver(payload, key, config): + """Bounded provider call; only provider acceptance with an ID counts as success.""" + req = Request('https://api.resend.com/emails', data=json.dumps(payload).encode(), + headers={'Authorization': f"Bearer {config['RESEND_API_KEY']}", + 'Content-Type': 'application/json', 'Idempotency-Key': f'contact/{key}'}, + method='POST') + with urlopen(req, timeout=10) as response: + result = json.loads(response.read(16384)) + if not isinstance(result, dict) or not isinstance(result.get('id'), str) or not result['id']: + raise ValueError('Provider did not acknowledge acceptance') + + +def create_app(overrides=None): + app = Flask(__name__) + app.config.update(MAX_CONTENT_LENGTH=32768, + CONTACT_EMAIL=os.environ.get('CONTACT_EMAIL', ''), + EMAIL_FROM=os.environ.get('EMAIL_FROM', ''), + RESEND_API_KEY=os.environ.get('RESEND_API_KEY', ''), + EMAIL_DELIVERY_ENABLED=os.environ.get('EMAIL_DELIVERY_ENABLED', 'false').lower() == 'true', + CONTACT_TRUST_PROXY=os.environ.get('CONTACT_TRUST_PROXY', 'false').lower() == 'true') + if overrides: + app.config.update(overrides) + # Enable only behind a single trusted proxy that overwrites client headers. + if app.config['CONTACT_TRUST_PROXY']: + app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1) + limiter = Limiter(get_remote_address, app=app, storage_uri='memory://') + app.extensions['contact_limiter'] = limiter + + def configured(): + sender = app.config['EMAIL_FROM'] + return bool(app.config['EMAIL_DELIVERY_ENABLED'] + and valid_email(app.config['CONTACT_EMAIL']) + and isinstance(sender, str) and '\r' not in sender and '\n' not in sender + and valid_email(parseaddr(sender)[1]) and app.config['RESEND_API_KEY']) + + @app.get('/api/health') + @app.get('/api/health/live') + @app.get('/api/health/ready') + def health(): + # Process readiness is separate from externally configured mail availability. + return {'status': 'ready'} + + @app.get('/api/contact/config') + def contact_config(): + email = app.config['CONTACT_EMAIL'] + response = app.json.response({'email': email if valid_email(email) else None, + 'available': configured()}) + response.headers['Cache-Control'] = 'no-store' + return response + + @app.errorhandler(413) + def too_large(_error): + return {'message': 'Message is too large.'}, 413 + + @app.errorhandler(429) + def limited(_error): + return {'message': 'Too many attempts. Please try again later.'}, 429, {'Retry-After': '3600'} + + @app.post('/api/contact') + @limiter.limit('5 per hour;20 per day') + def contact(): + data = request.get_json(silent=True) + if not isinstance(data, dict): + return {'message': 'Send a valid enquiry.'}, 400 + allowed = {'name', 'email', 'service', 'description', 'website'} + if set(data) - allowed or any(not isinstance(v, str) for v in data.values()): + return {'message': 'Send a valid enquiry.'}, 400 + if data.get('website', ''): + return {'message': 'Unable to accept this enquiry.'}, 400 + values = {k: data.get(k, '').strip() for k in allowed} + errors = {} + if not 1 <= len(values['name']) <= 100 or any(ord(c) < 32 for c in values['name']): + errors['name'] = 'Enter your name (up to 100 characters).' + if not valid_email(values['email']): + errors['email'] = 'Enter a valid email address.' + if values['service'] and values['service'] not in SERVICES: + errors['service'] = 'Choose one of the listed services or leave it blank.' + if not 10 <= len(values['description']) <= 5000 or '\x00' in values['description']: + errors['description'] = 'Describe your project in 10 to 5,000 characters.' + if errors: + return {'message': 'Please check the highlighted fields.', 'errors': errors}, 400 + key = request.headers.get('Idempotency-Key', '') + try: + if str(UUID(key)) != key: + raise ValueError() + except (ValueError, AttributeError): + return {'message': 'Refresh the page and try again.'}, 400 + if not configured(): + return {'message': 'Enquiries are temporarily unavailable. Your message has not been sent.'}, 503 + service = values['service'] or 'General enquiry' + text = f"Name: {values['name']}\nEmail: {values['email']}\nService: {service}\n\n{values['description']}" + payload = {'from': app.config['EMAIL_FROM'], 'to': [app.config['CONTACT_EMAIL']], + 'reply_to': values['email'], 'subject': f'BortStack enquiry: {service}', + 'text': text, 'html': '
' + escape(text) + '
'} + try: + deliver(payload, key, app.config) + except Exception: + # No provider exception/body or visitor data in logs/responses. + app.logger.warning('Contact provider acceptance could not be confirmed') + return {'message': 'Sending could not be confirmed. Your draft is kept; please retry. A retry of the same draft avoids duplicate processing.'}, 503 + return {'success': True, 'message': 'Your enquiry has been accepted for delivery. Thank you.'} + + return app + + +app = create_app() diff --git a/api/test_contact_independent.py b/api/test_contact_independent.py new file mode 100644 index 0000000..d3cfe8c --- /dev/null +++ b/api/test_contact_independent.py @@ -0,0 +1,103 @@ +"""Standalone tests: no tests/conftest.py or account/database fixture required.""" +import json +from uuid import uuid4 +from unittest.mock import patch + +import pytest +from contact_app import create_app, deliver + +VALID = dict(name='Example Person', email='person@example.com', service='', + description='A useful software project enquiry.', website='') +KEY = str(uuid4()) + +@pytest.fixture +def app(): + return create_app(dict(TESTING=True, EMAIL_DELIVERY_ENABLED=True, + EMAIL_FROM='BortStack ', + CONTACT_EMAIL='business@example.com', RESEND_API_KEY='test-only')) + + +def post(app, data=VALID, key=KEY): + return app.test_client().post('/api/contact', json=data, headers={'Idempotency-Key': key}) + + +def test_independent_no_database_or_account_routes(app): + assert 'sqlalchemy' not in app.extensions + assert app.test_client().get('/api/health/ready').status_code == 200 + assert app.test_client().get('/api/users').status_code == 404 + assert app.test_client().get('/api/contact/config').json == {'email': 'business@example.com', 'available': True} + + +def test_success_safe_sender_replyto_and_escaping(app): + with patch('contact_app.deliver') as send: + r = post(app, {**VALID, 'name': ''}) + assert r.status_code == 200 and r.json['success'] is True + payload, key, _ = send.call_args.args + assert payload['from'] == 'BortStack ' + assert payload['reply_to'] == VALID['email'] + assert payload['to'] == ['business@example.com'] + assert '