diff --git a/.gitea/workflows/continuous_integration.yaml b/.gitea/workflows/continuous_integration.yaml
index d12b106..def921b 100644
--- a/.gitea/workflows/continuous_integration.yaml
+++ b/.gitea/workflows/continuous_integration.yaml
@@ -3,12 +3,12 @@ name: Continuous Integration
on:
workflow_dispatch:
inputs:
- deploy_test:
- description: 'Deploy to Test'
+ deploy_sls_test:
+ description: 'Deploy SLS test (SlpSoftware)'
type: boolean
default: false
- deploy_production:
- description: 'Deploy to Production'
+ deploy_sls_production:
+ description: 'Deploy SLS production (SlpSoftware)'
type: boolean
default: false
deploy_asf_test:
@@ -22,7 +22,7 @@ on:
# A new push to the same PR does not cancel an already-running CI attempt by default (each
# `synchronize` event starts an independent run) — this opts in to cancelling the superseded one,
-# but ONLY for pull_request events. `deploy-test`/`deploy-production` never run on a pull_request
+# but ONLY for pull_request events. `deploy-sls-test`/`deploy-sls-production` never run on a pull_request
# (they require a push to master or a workflow_dispatch, see those jobs' `if:` conditions), so
# scoping cancel-in-progress to pull_request here can never abort a live deploy mid-flight.
concurrency:
@@ -31,17 +31,17 @@ concurrency:
# Reusable settings for this workflow. Change these in one place if the .NET/Node/pnpm version,
# artifact names, or deploy destinations change. The env context is NOT available inside a called
-# reusable workflow's `with:` inputs (see the `config` job below, which works around this by passing
-# these values through as job outputs to the `deploy-test` / `deploy-production` jobs).
+# reusable workflow's `with:` inputs (see the `config-sls` job below, which works around this by passing
+# these values through as job outputs to the `deploy-sls-test` / `deploy-sls-production` jobs).
env:
DOTNET_VERSION: '10.0.x'
NODE_VERSION: '20'
PNPM_VERSION: '9'
PUBLISH_RID: linux-arm64
- ARTIFACT_NAME_TEST: app-test
- ARTIFACT_NAME_PRODUCTION: app-production
- DEPLOY_ENVIRONMENT_TEST: test
- DEPLOY_ENVIRONMENT_PRODUCTION: production
+ ARTIFACT_NAME_SLS_TEST: app-sls-test
+ ARTIFACT_NAME_SLS_PRODUCTION: app-sls-production
+ DEPLOY_ENVIRONMENT_SLS_TEST: test
+ DEPLOY_ENVIRONMENT_SLS_PRODUCTION: production
DEPLOY_PATH_TEST: ${{ vars.DEPLOY_PATH_TEST }}
DEPLOY_PATH_PRODUCTION: ${{ vars.DEPLOY_PATH_PRODUCTION }}
SERVICE_NAME_TEST: ${{ vars.SERVICE_NAME_TEST }}
@@ -51,40 +51,56 @@ env:
jobs:
# Passes the env: values above through as job outputs, since the env context is unavailable in
- # the `with:` block of a job that calls a reusable workflow (see deploy-test / deploy-production).
- config:
- runs-on: ubuntu-latest
+ # the `with:` block of a job that calls a reusable workflow (see deploy-sls-test / deploy-sls-production).
+ config-sls:
+ runs-on: linux
outputs:
- artifact_name_test: ${{ steps.set.outputs.artifact_name_test }}
- artifact_name_production: ${{ steps.set.outputs.artifact_name_production }}
- deploy_environment_test: ${{ steps.set.outputs.deploy_environment_test }}
- deploy_environment_production: ${{ steps.set.outputs.deploy_environment_production }}
- deploy_path_test: ${{ steps.set.outputs.deploy_path_test }}
- deploy_path_production: ${{ steps.set.outputs.deploy_path_production }}
- service_name_test: ${{ steps.set.outputs.service_name_test }}
- service_name_production: ${{ steps.set.outputs.service_name_production }}
- health_check_url_test: ${{ steps.set.outputs.health_check_url_test }}
- health_check_url_production: ${{ steps.set.outputs.health_check_url_production }}
+ artifact_name_sls_test: ${{ steps.set.outputs.artifact_name_sls_test }}
+ artifact_name_sls_production: ${{ steps.set.outputs.artifact_name_sls_production }}
+ deploy_environment_sls_test: ${{ steps.set.outputs.deploy_environment_sls_test }}
+ deploy_environment_sls_production: ${{ steps.set.outputs.deploy_environment_sls_production }}
+ deploy_path_sls_test: ${{ steps.set.outputs.deploy_path_sls_test }}
+ deploy_path_sls_production: ${{ steps.set.outputs.deploy_path_sls_production }}
+ service_name_sls_test: ${{ steps.set.outputs.service_name_sls_test }}
+ service_name_sls_production: ${{ steps.set.outputs.service_name_sls_production }}
+ health_check_url_sls_test: ${{ steps.set.outputs.health_check_url_sls_test }}
+ health_check_url_sls_production: ${{ steps.set.outputs.health_check_url_sls_production }}
steps:
# Gitea has no reliable way to see a past run's workflow_dispatch input values from the UI, so
# this logs them explicitly — the only durable record of what was actually checked for a run.
- name: Log dispatch inputs
if: github.event_name == 'workflow_dispatch'
run: |
- echo "Deploy to Test: ${{ github.event.inputs.deploy_test }}"
- echo "Deploy to Production: ${{ github.event.inputs.deploy_production }}"
+ echo "Deploy SLS test: ${{ github.event.inputs.deploy_sls_test }}"
+ echo "Deploy SLS production: ${{ github.event.inputs.deploy_sls_production }}"
+ # The Gitea variables are read at STEP level (like config-asf), not through the workflow-level env block: on the PC
+ # runner the workflow-level `${{ vars.* }}` values came through empty (deploy path "" -> mkdir /releases), while
+ # step-level env works on both runners. The test trio must be set, otherwise fail here instead of in the deploy.
- id: set
+ env:
+ DEPLOY_PATH_TEST: ${{ vars.DEPLOY_PATH_TEST }}
+ DEPLOY_PATH_PRODUCTION: ${{ vars.DEPLOY_PATH_PRODUCTION }}
+ SERVICE_NAME_TEST: ${{ vars.SERVICE_NAME_TEST }}
+ SERVICE_NAME_PRODUCTION: ${{ vars.SERVICE_NAME_PRODUCTION }}
+ HEALTH_CHECK_URL_TEST: ${{ vars.HEALTH_CHECK_URL_TEST }}
+ HEALTH_CHECK_URL_PRODUCTION: ${{ vars.HEALTH_CHECK_URL_PRODUCTION }}
run: |
- echo "artifact_name_test=${{ env.ARTIFACT_NAME_TEST }}" >> "$GITHUB_OUTPUT"
- echo "artifact_name_production=${{ env.ARTIFACT_NAME_PRODUCTION }}" >> "$GITHUB_OUTPUT"
- echo "deploy_environment_test=${{ env.DEPLOY_ENVIRONMENT_TEST }}" >> "$GITHUB_OUTPUT"
- echo "deploy_environment_production=${{ env.DEPLOY_ENVIRONMENT_PRODUCTION }}" >> "$GITHUB_OUTPUT"
- echo "deploy_path_test=${{ env.DEPLOY_PATH_TEST }}" >> "$GITHUB_OUTPUT"
- echo "deploy_path_production=${{ env.DEPLOY_PATH_PRODUCTION }}" >> "$GITHUB_OUTPUT"
- echo "service_name_test=${{ env.SERVICE_NAME_TEST }}" >> "$GITHUB_OUTPUT"
- echo "service_name_production=${{ env.SERVICE_NAME_PRODUCTION }}" >> "$GITHUB_OUTPUT"
- echo "health_check_url_test=${{ env.HEALTH_CHECK_URL_TEST }}" >> "$GITHUB_OUTPUT"
- echo "health_check_url_production=${{ env.HEALTH_CHECK_URL_PRODUCTION }}" >> "$GITHUB_OUTPUT"
+ for v in DEPLOY_PATH_TEST SERVICE_NAME_TEST HEALTH_CHECK_URL_TEST; do
+ if [ -z "${!v}" ]; then
+ echo "The Gitea variable $v is empty or not set on this runner; the deploy would use an empty path."
+ exit 1
+ fi
+ done
+ echo "artifact_name_sls_test=${{ env.ARTIFACT_NAME_SLS_TEST }}" >> "$GITHUB_OUTPUT"
+ echo "artifact_name_sls_production=${{ env.ARTIFACT_NAME_SLS_PRODUCTION }}" >> "$GITHUB_OUTPUT"
+ echo "deploy_environment_sls_test=${{ env.DEPLOY_ENVIRONMENT_SLS_TEST }}" >> "$GITHUB_OUTPUT"
+ echo "deploy_environment_sls_production=${{ env.DEPLOY_ENVIRONMENT_SLS_PRODUCTION }}" >> "$GITHUB_OUTPUT"
+ echo "deploy_path_sls_test=$DEPLOY_PATH_TEST" >> "$GITHUB_OUTPUT"
+ echo "deploy_path_sls_production=$DEPLOY_PATH_PRODUCTION" >> "$GITHUB_OUTPUT"
+ echo "service_name_sls_test=$SERVICE_NAME_TEST" >> "$GITHUB_OUTPUT"
+ echo "service_name_sls_production=$SERVICE_NAME_PRODUCTION" >> "$GITHUB_OUTPUT"
+ echo "health_check_url_sls_test=$HEALTH_CHECK_URL_TEST" >> "$GITHUB_OUTPUT"
+ echo "health_check_url_sls_production=$HEALTH_CHECK_URL_PRODUCTION" >> "$GITHUB_OUTPUT"
# Path-based skip: keeps the pipeline short when a change only touches one side of the repo.
# fetch-depth: 0 gives paths-filter full local git history to diff against, rather than relying
@@ -94,7 +110,7 @@ jobs:
# workflow_dispatch run has no `before` commit to diff against and is always an explicit request
# to run everything, so it force-reports both sides as changed rather than trusting the filter.
changes:
- runs-on: ubuntu-latest
+ runs-on: linux
outputs:
backend: ${{ github.event_name == 'workflow_dispatch' || steps.filter.outputs.backend == 'true' }}
frontend: ${{ github.event_name == 'workflow_dispatch' || steps.filter.outputs.frontend == 'true' }}
@@ -118,6 +134,7 @@ jobs:
- 'src/**'
- 'tests/**'
- '*.sln'
+ - '*.slnf'
- '**/*.csproj'
frontend:
- *workflow
@@ -127,20 +144,44 @@ jobs:
backend-build:
needs: changes
if: needs.changes.outputs.backend == 'true'
- runs-on: ubuntu-latest
+ runs-on: linux
steps:
- uses: actions/checkout@v4
- uses: actions/setup-dotnet@v4
with:
dotnet-version: ${{ env.DOTNET_VERSION }}
+ # The CI builds and tests the master CMS only (SlpModularCms.Api with every module, Core and all test
+ # projects), listed in SlpModularCms.Ci.slnf. The site projects (Api.SlpSoftware, Api.AndreaSlopFotografie,
+ # Api.Slave) are thin compositions: they are compiled by compile-sites below and built/published only when a
+ # deploy needs them. Their behaviour is covered by the tests on the master host (see SiteContractTests).
- name: Restore and build (Release)
- run: dotnet build SlpModularCms.sln -c Release
+ run: dotnet build SlpModularCms.Ci.slnf -c Release
+
+ # --- Not required: the thin site projects still compile ---
+ # Compile only (no tests, a few seconds): catches a broken reference or a renamed type in a site project on the
+ # pull request instead of at deploy time. Deliberately not a required check; the smoke tests after the test
+ # deploys catch composition errors that compile fine.
+ compile-sites:
+ needs: changes
+ if: needs.changes.outputs.backend == 'true'
+ runs-on: linux
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: ${{ env.DOTNET_VERSION }}
+ - name: Compile the site projects (Release)
+ run: |
+ for project in SlpSoftware AndreaSlopFotografie Slave; do
+ echo "== SlpModularCms.Api.$project"
+ dotnet build "src/SlpModularCms.Api.$project/SlpModularCms.Api.$project.csproj" -c Release
+ done
# --- Gate 2: backend tests ---
backend-test:
needs: [changes, backend-build]
if: needs.changes.outputs.backend == 'true'
- runs-on: ubuntu-latest
+ runs-on: linux
# Added for SlpModularCms.Api.Tests (slpsoftware-api feature, NFR-CS-01): its pipeline
# regression tests boot the real Api host via WebApplicationFactory, which unconditionally
# runs CmsHost.ConfigurePipeline's startup migration (MigrateCoreDatabase) -- unlike every
@@ -148,56 +189,54 @@ jobs:
# database. Without a real, reachable MariaDB, those tests fail on the connection itself
# before any assertion runs.
#
- # A `services:` block was tried first and rejected: this runner uses host networking for
- # job AND service containers ("--network and --net in the options will be ignored" in the
- # job log), so the `ports:` mapping was silently ignored, and the mariadb:11 service ended
- # up sharing the host's network namespace directly on port 3306 -- which something else on
- # this runner already answers on (root auth was rejected by a server that was clearly NOT
- # the freshly-initialized container: "Access denied ... using password: YES" against a
- # password nothing but this job ever set). An explicitly `docker run` container below,
- # published on host port 3307 instead of 3306, avoids that collision entirely.
+ # The database is a job-level `services:` container, so the job needs no container-engine socket (the PC
+ # runner has no /var/run/docker.sock in its job containers; a manual `docker run` failed there). The server
+ # listens on 3308 (MYSQL_TCP_PORT) instead of 3306: on the Pi runner job and service containers share the
+ # host's network namespace (host networking), where the host's own database already answers on 3306 -- the
+ # reason the first `services:` attempt there failed. On a runner with a separate job network the service is
+ # reached by its name `mariadb`; with host networking it is reached on 127.0.0.1 (resolved in the test step).
+ services:
+ mariadb:
+ image: mariadb:11
+ env:
+ MARIADB_ROOT_PASSWORD: ci_test_password
+ MARIADB_DATABASE: SlpModularCms
+ MYSQL_TCP_PORT: '3308'
+ options: >-
+ --health-cmd="mariadb-admin ping -uroot -pci_test_password --silent"
+ --health-interval=3s --health-timeout=3s --health-retries=40
steps:
- uses: actions/checkout@v4
- uses: actions/setup-dotnet@v4
with:
dotnet-version: ${{ env.DOTNET_VERSION }}
- - name: Start MariaDB for SlpModularCms.Api.Tests
+ - name: Test (Release)
+ shell: bash
+ # ConnectionStrings__DefaultConnection overrides the placeholder in appsettings.Development.json for this CI
+ # run only (environment variables are applied after appsettings.*.json), so it reaches
+ # SlpModularCms.Api.Tests' WebApplicationFactory without touching a committed appsettings file.
run: |
- docker run -d --name ci-mariadb \
- -e MARIADB_ROOT_PASSWORD=ci_test_password \
- -e MARIADB_DATABASE=SlpModularCms \
- -p 3307:3306 \
- mariadb:11
- for i in $(seq 1 30); do
- # mariadb:11 does not provide a `mysqladmin` alias -- verified locally against this
- # exact image; the correct binary here is `mariadb-admin`.
- if docker exec ci-mariadb mariadb-admin ping -uroot -pci_test_password --silent 2>/dev/null; then
- echo "MariaDB is ready."
- break
- fi
- echo "Waiting for MariaDB... ($i/30)"
+ HOST=127.0.0.1
+ if getent hosts mariadb >/dev/null 2>&1; then HOST=mariadb; fi
+ echo "Waiting for MariaDB on $HOST:3308"
+ for i in $(seq 1 60); do
+ if (echo > "/dev/tcp/$HOST/3308") 2>/dev/null; then echo "MariaDB is accepting connections."; break; fi
sleep 2
done
- - name: Test (Release)
- env:
- # Overrides the placeholder in SlpModularCms.Api/appsettings.Development.json for this
- # CI run only -- ASP.NET Core's configuration layering applies environment variables
- # after appsettings.*.json, so this reaches SlpModularCms.Api.Tests' WebApplicationFactory
- # without touching any committed appsettings file. Port 3307, not 3306 -- see above.
- ConnectionStrings__DefaultConnection: "Server=127.0.0.1;Port=3307;Database=SlpModularCms;Uid=root;Pwd=ci_test_password"
- run: dotnet test SlpModularCms.sln -c Release
- - name: Stop MariaDB for SlpModularCms.Api.Tests
- if: always()
- run: docker rm -f ci-mariadb || true
+ export ConnectionStrings__DefaultConnection="Server=$HOST;Port=3308;Database=SlpModularCms;Uid=root;Pwd=ci_test_password"
+ dotnet test SlpModularCms.Ci.slnf -c Release
# --- Gate 3: vulnerability scan ---
# `dotnet list package --vulnerable` always exits 0, even when it reports vulnerabilities, so the
# step greps its own output and fails deliberately (FR-22, D-12, OPEN-03 — closed by pinning
# Microsoft.OpenApi and System.Security.Cryptography.Xml in the relevant .csproj files).
- # Runner labels: `ubuntu-latest` exists only on the Pi (linux-arm64). The independent jobs below (vulnerability-scan,
- # frontend-*) use `linux`, which the Pi and the desktop runner (x64) both carry, so they can run in parallel. They need no
- # arm64 artefact and each does its own `pnpm install`. NOT moved: backend-test (docker mariadb), publish-* (linux-arm64
- # artefacts for the Pi) and deploy-* (reusable deploy workflow).
+ # Runner labels: a job runs on a runner that has ALL of its runs-on labels.
+ # Pi runner: linux-arm64, ubuntu-latest, global, linux, arm64, podman, raspberry-pi
+ # PC runner: global, linux, x64, podman, bryan-desktop
+ # Every job uses `linux` so that any runner (PC, Pi, future ones) can pick it up; no job assumes the host
+ # architecture or a specific user: publish-* cross-publishes with an explicit `-r linux-arm64`, deploy-scp.yaml only
+ # installs missing tools and only uses sudo when needed, backend-test uses a services: container (no engine socket needed).
+ # Use `raspberry-pi` only for a job that demonstrably cannot run elsewhere, and say why in a comment.
vulnerability-scan:
needs: changes
if: needs.changes.outputs.backend == 'true'
@@ -244,7 +283,7 @@ jobs:
# --- Gate 4: frontend build ---
# Validates the frontend compiles on its own, independent of any environment. The actual
# per-environment deployable artifact is produced later by each publish job's own "Build admin
- # frontend" step (publish-test / publish-production, below), which builds frontend/ again with
+ # frontend" step (publish-sls-test / publish-sls-production, below), which builds frontend/ again with
# that environment's Vite variables set and copies the result into wwwroot/admin before
# `dotnet publish` runs — see that step's comment for why this isn't an MSBuild target instead.
frontend-build:
@@ -342,7 +381,7 @@ jobs:
# kept in sync with the host's real SecurityHeaders__AllowedScriptOrigins__0 env var (D-16). This
# gate cannot see the actual runtime CSP configuration; it only catches drift between the frontend
# build and what this variable claims the CSP allows.
- publish-test:
+ publish-sls-test:
needs: [changes, backend-build, backend-test, vulnerability-scan, frontend-build, frontend-test, frontend-lint]
# always() bypasses the automatic skip-cascade from a gate job that was itself skipped (because
# its side of the repo didn't change). Gitea Actions only implements always() from the GitHub
@@ -350,9 +389,9 @@ jobs:
# gate's outcome is checked explicitly via needs..result instead: a skipped gate is fine,
# but a gate that actually ran and failed or was cancelled still blocks the publish. The
# changes.outputs check makes sure there's something to publish at all: a run that touched
- # neither backend nor frontend has nothing new to deploy. The final line skips this build on a
- # manual workflow_dispatch run that didn't check deploy_test — building and uploading a test
- # artifact nobody is going to deploy is wasted work; push/PR runs are unaffected.
+ # neither backend nor frontend has nothing new to deploy. The last two lines build this site only when a
+ # deploy will use it: never on a pull_request (the pull request builds and tests the master CMS only) and, on a
+ # manual workflow_dispatch run, only when deploy_sls_test is checked.
if: |
always() &&
needs.changes.result == 'success' &&
@@ -363,8 +402,9 @@ jobs:
needs.frontend-test.result != 'failure' && needs.frontend-test.result != 'cancelled' &&
needs.frontend-lint.result != 'failure' && needs.frontend-lint.result != 'cancelled' &&
(needs.changes.outputs.backend == 'true' || needs.changes.outputs.frontend == 'true') &&
- (github.event_name != 'workflow_dispatch' || github.event.inputs.deploy_test == 'true')
- runs-on: ubuntu-latest
+ github.event_name != 'pull_request' &&
+ (github.event_name != 'workflow_dispatch' || github.event.inputs.deploy_sls_test == 'true')
+ runs-on: linux
steps:
- uses: actions/checkout@v4
- uses: actions/setup-dotnet@v4
@@ -399,6 +439,8 @@ jobs:
working-directory: frontend
env:
VITE_APP_ENV: test
+ VITE_APP_TITLE: SLP Software
+ VITE_THEME: slpsoftware
VITE_UMAMI_SCRIPT_URL: ${{ vars.VITE_UMAMI_SCRIPT_URL }}
VITE_UMAMI_WEBSITE_ID: ${{ vars.VITE_UMAMI_WEBSITE_ID_TEST }}
VITE_SENTRY_DSN: ${{ vars.VITE_SENTRY_DSN }}
@@ -412,21 +454,21 @@ jobs:
working-directory: src/SlpModularCms.Api.SlpSoftware
run: >
dotnet publish -c Release -r ${{ env.PUBLISH_RID }} --self-contained false
- -o ${{ github.workspace }}/${{ env.ARTIFACT_NAME_TEST }}
+ -o ${{ github.workspace }}/${{ env.ARTIFACT_NAME_SLS_TEST }}
- name: Upload publish artifact
uses: actions/upload-artifact@v3
with:
- name: ${{ env.ARTIFACT_NAME_TEST }}
- path: ${{ env.ARTIFACT_NAME_TEST }}
+ name: ${{ env.ARTIFACT_NAME_SLS_TEST }}
+ path: ${{ env.ARTIFACT_NAME_SLS_TEST }}
retention-days: 1
- # Same as publish-test, but only for a manual workflow_dispatch run with deploy_production set —
- # a distinct job rather than a parameterized reuse of publish-test, because VITE_APP_ENV is a
+ # Same as publish-sls-test, but only for a manual workflow_dispatch run with deploy_sls_production set —
+ # a distinct job rather than a parameterized reuse of publish-sls-test, because VITE_APP_ENV is a
# Vite build-time value: one dist/ bundle cannot be tagged as both 'test' and 'production' (FR-05).
- publish-production:
+ publish-sls-production:
needs: [changes, backend-build, backend-test, vulnerability-scan, frontend-build, frontend-test, frontend-lint]
- # See publish-test's comment above on why this checks needs..result explicitly instead of
+ # See publish-sls-test's comment above on why this checks needs..result explicitly instead of
# failure()/cancelled(), which Gitea Actions doesn't support.
if: |
always() &&
@@ -437,9 +479,9 @@ jobs:
needs.frontend-build.result != 'failure' && needs.frontend-build.result != 'cancelled' &&
needs.frontend-test.result != 'failure' && needs.frontend-test.result != 'cancelled' &&
needs.frontend-lint.result != 'failure' && needs.frontend-lint.result != 'cancelled' &&
- github.event_name == 'workflow_dispatch' && github.event.inputs.deploy_production == 'true' &&
+ github.event_name == 'workflow_dispatch' && github.event.inputs.deploy_sls_production == 'true' &&
(needs.changes.outputs.backend == 'true' || needs.changes.outputs.frontend == 'true')
- runs-on: ubuntu-latest
+ runs-on: linux
steps:
- uses: actions/checkout@v4
- uses: actions/setup-dotnet@v4
@@ -462,12 +504,14 @@ jobs:
exit 1
fi
- # See publish-test's "Build admin frontend" step for why this runs as its own step ahead of
+ # See publish-sls-test's "Build admin frontend" step for why this runs as its own step ahead of
# dotnet publish rather than an MSBuild target.
- name: Build admin frontend
working-directory: frontend
env:
VITE_APP_ENV: production
+ VITE_APP_TITLE: SLP Software
+ VITE_THEME: slpsoftware
VITE_UMAMI_SCRIPT_URL: ${{ vars.VITE_UMAMI_SCRIPT_URL }}
VITE_UMAMI_WEBSITE_ID: ${{ vars.VITE_UMAMI_WEBSITE_ID_PRODUCTION }}
VITE_SENTRY_DSN: ${{ vars.VITE_SENTRY_DSN }}
@@ -481,46 +525,50 @@ jobs:
working-directory: src/SlpModularCms.Api.SlpSoftware
run: >
dotnet publish -c Release -r ${{ env.PUBLISH_RID }} --self-contained false
- -o ${{ github.workspace }}/${{ env.ARTIFACT_NAME_PRODUCTION }}
+ -o ${{ github.workspace }}/${{ env.ARTIFACT_NAME_SLS_PRODUCTION }}
- name: Upload publish artifact
uses: actions/upload-artifact@v3
with:
- name: ${{ env.ARTIFACT_NAME_PRODUCTION }}
- path: ${{ env.ARTIFACT_NAME_PRODUCTION }}
+ name: ${{ env.ARTIFACT_NAME_SLS_PRODUCTION }}
+ path: ${{ env.ARTIFACT_NAME_SLS_PRODUCTION }}
retention-days: 1
# Automatic test deploy on every push to master (unchanged — a merge should reach test without
- # extra steps). A manual workflow_dispatch run only deploys to test when deploy_test is checked,
+ # extra steps). A manual workflow_dispatch run only deploys to test when deploy_sls_test is checked,
# since a dispatch run is often just re-running CI/production, not a new test build (FR-03, D-01,
# D-09).
- deploy-test:
- needs: [publish-test, config]
- if: (github.event_name == 'workflow_dispatch' && github.event.inputs.deploy_test == 'true') || (github.event_name == 'push' && github.ref == 'refs/heads/master')
+ # deploy_path / service_name / health_check_url come straight from the Gitea variables, NOT from the `config-sls` job
+ # outputs: a job output whose value contains a secret value (here most likely the deploy account name inside the
+ # path) is dropped by the runner, so the reusable workflow received an empty deploy_path ("/releases"). The
+ # `config-sls` outputs are still used for the artifact and environment names.
+ deploy-sls-test:
+ needs: [publish-sls-test, config-sls]
+ if: (github.event_name == 'workflow_dispatch' && github.event.inputs.deploy_sls_test == 'true') || (github.event_name == 'push' && github.ref == 'refs/heads/master')
uses: ./.gitea/workflows/deploy-scp.yaml
secrets: inherit
with:
- artifact_name: ${{ needs.config.outputs.artifact_name_test }}
- environment: ${{ needs.config.outputs.deploy_environment_test }}
- deploy_path: ${{ needs.config.outputs.deploy_path_test }}
- service_name: ${{ needs.config.outputs.service_name_test }}
- health_check_url: ${{ needs.config.outputs.health_check_url_test }}
+ artifact_name: ${{ needs.config-sls.outputs.artifact_name_sls_test }}
+ environment: ${{ needs.config-sls.outputs.deploy_environment_sls_test }}
+ deploy_path: ${{ vars.DEPLOY_PATH_TEST }}
+ service_name: ${{ vars.SERVICE_NAME_TEST }}
+ health_check_url: ${{ vars.HEALTH_CHECK_URL_TEST }}
run_db_backup: false
- # Production deploy ONLY on an explicit workflow_dispatch run with deploy_production checked
+ # Production deploy ONLY on an explicit workflow_dispatch run with deploy_sls_production checked
# (FR-04, D-09) — never reachable from a plain push to master, so pushing cannot deploy production
# under any circumstance.
- deploy-production:
- needs: [publish-production, config]
- if: github.event_name == 'workflow_dispatch' && github.event.inputs.deploy_production == 'true'
+ deploy-sls-production:
+ needs: [publish-sls-production, config-sls]
+ if: github.event_name == 'workflow_dispatch' && github.event.inputs.deploy_sls_production == 'true'
uses: ./.gitea/workflows/deploy-scp.yaml
secrets: inherit
with:
- artifact_name: ${{ needs.config.outputs.artifact_name_production }}
- environment: ${{ needs.config.outputs.deploy_environment_production }}
- deploy_path: ${{ needs.config.outputs.deploy_path_production }}
- service_name: ${{ needs.config.outputs.service_name_production }}
- health_check_url: ${{ needs.config.outputs.health_check_url_production }}
+ artifact_name: ${{ needs.config-sls.outputs.artifact_name_sls_production }}
+ environment: ${{ needs.config-sls.outputs.deploy_environment_sls_production }}
+ deploy_path: ${{ vars.DEPLOY_PATH_PRODUCTION }}
+ service_name: ${{ vars.SERVICE_NAME_PRODUCTION }}
+ health_check_url: ${{ vars.HEALTH_CHECK_URL_PRODUCTION }}
run_db_backup: true
# ==========================================================================================
@@ -537,7 +585,7 @@ jobs:
# ==========================================================================================
config-asf:
if: ${{ vars.ASF_TEST_DEPLOY_ENABLED == 'true' }}
- runs-on: ubuntu-latest
+ runs-on: linux
outputs:
deploy_path: ${{ steps.set.outputs.deploy_path }}
service_name: ${{ steps.set.outputs.service_name }}
@@ -561,7 +609,7 @@ jobs:
publish-asf-test:
needs: [changes, backend-build, backend-test, vulnerability-scan, frontend-build, frontend-test, frontend-lint]
- # Same gate handling as publish-test (see there for why always() and explicit results), plus the
+ # Same gate handling as publish-sls-test (see there for why always() and explicit results), plus the
# ASF switch, and built only when it will actually be deployed.
if: |
always() &&
@@ -576,7 +624,7 @@ jobs:
(needs.changes.outputs.backend == 'true' || needs.changes.outputs.frontend == 'true') &&
((github.event_name == 'workflow_dispatch' && github.event.inputs.deploy_asf_test == 'true') ||
(github.event_name == 'push' && github.ref == 'refs/heads/master'))
- runs-on: ubuntu-latest
+ runs-on: linux
steps:
- uses: actions/checkout@v4
- uses: actions/setup-dotnet@v4
@@ -590,7 +638,7 @@ jobs:
version: ${{ env.PNPM_VERSION }}
# Admin SPA with the ASF theme and Dutch as the default language. Lands in wwwroot/admin
- # BEFORE dotnet publish, for the same reason as in publish-test. No Umami for the admin.
+ # BEFORE dotnet publish, for the same reason as in publish-sls-test. No Umami for the admin.
- name: Build admin frontend (ASF theme)
working-directory: frontend
env:
@@ -618,6 +666,8 @@ jobs:
path: app-asf-test
retention-days: 1
+ # Path/service/health straight from the Gitea variables, like deploy-sls-test (a job output containing a secret value,
+ # here the deploy account name in the path, arrives empty). config-asf still validates that they are set.
deploy-asf-test:
needs: [publish-asf-test, config-asf]
if: vars.ASF_TEST_DEPLOY_ENABLED == 'true' && ((github.event_name == 'workflow_dispatch' && github.event.inputs.deploy_asf_test == 'true') || (github.event_name == 'push' && github.ref == 'refs/heads/master'))
@@ -626,7 +676,32 @@ jobs:
with:
artifact_name: app-asf-test
environment: test
- deploy_path: ${{ needs.config-asf.outputs.deploy_path }}
- service_name: ${{ needs.config-asf.outputs.service_name }}
- health_check_url: ${{ needs.config-asf.outputs.health_check_url }}
+ deploy_path: ${{ vars.DEPLOY_PATH_ASF_TEST }}
+ service_name: ${{ vars.SERVICE_NAME_ASF_TEST }}
+ health_check_url: ${{ vars.HEALTH_CHECK_URL_ASF_TEST }}
run_db_backup: false
+
+ # --- Smoke tests of the deployed compositions (anonymous requests, see scripts/smoke-site.sh) ---
+ # The CI tests the master CMS; this is the check that the composition of each site that was just deployed to test
+ # is the intended one (modules, website mode, noindex, protected admin routes). A failing smoke test fails the run.
+ smoke-sls-test:
+ needs: [deploy-sls-test]
+ if: always() && needs.deploy-sls-test.result == 'success'
+ runs-on: linux
+ steps:
+ - uses: actions/checkout@v4
+ - name: Smoke test SLS test
+ env:
+ HEALTH_URL: ${{ vars.HEALTH_CHECK_URL_TEST }}
+ run: bash scripts/smoke-site.sh "$HEALTH_URL" sls-test
+
+ smoke-asf-test:
+ needs: [deploy-asf-test]
+ if: always() && needs.deploy-asf-test.result == 'success'
+ runs-on: linux
+ steps:
+ - uses: actions/checkout@v4
+ - name: Smoke test ASF test
+ env:
+ HEALTH_URL: ${{ vars.HEALTH_CHECK_URL_ASF_TEST }}
+ run: bash scripts/smoke-site.sh "$HEALTH_URL" asf-test
diff --git a/.gitea/workflows/deploy-scp.yaml b/.gitea/workflows/deploy-scp.yaml
index d46c5e0..2db2680 100644
--- a/.gitea/workflows/deploy-scp.yaml
+++ b/.gitea/workflows/deploy-scp.yaml
@@ -40,8 +40,75 @@ on:
jobs:
deploy:
- runs-on: ubuntu-latest
+ runs-on: linux
steps:
+ # Runner-independent: only installs what is missing, and only uses sudo when not already root and sudo exists
+ # (a container on the PC runner has neither sudo nor a need for it; the Pi runner may need it).
+ #
+ # Authentication: the Pi-Main host only allows password login from the Pi runner's address, so every runner other
+ # than that one needs a key. If the secret PI_MAIN_SSH_KEY (private key of the deploy account) is set and works,
+ # the wrappers `rssh` / `rscp` below use it (-i, IdentitiesOnly, BatchMode); otherwise they fall back to sshpass
+ # with the password, which keeps working from the Pi runner. The key lives in a temp directory that is removed
+ # at the end of the job; it is never printed.
+ - name: Ensure ssh tooling and authentication
+ env:
+ SSH_USER: ${{ secrets.PI_MAIN_USERNAME }}
+ SSH_PASS: ${{ secrets.PI_MAIN_PASSWORD }}
+ SSH_PORT: ${{ secrets.PI_MAIN_PORT }}
+ SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
+ SSH_KEY: ${{ secrets.PI_MAIN_SSH_KEY }}
+ IN_DEPLOY_PATH: ${{ inputs.deploy_path }}
+ IN_SERVICE_NAME: ${{ inputs.service_name }}
+ IN_HEALTH_URL: ${{ inputs.health_check_url }}
+ run: |
+ # Inputs are not secret: print them so an empty one is visible, and stop before anything touches the host.
+ echo "Inputs: deploy_path='$IN_DEPLOY_PATH' service_name='$IN_SERVICE_NAME' health_check_url='$IN_HEALTH_URL'"
+ for v in IN_DEPLOY_PATH IN_SERVICE_NAME IN_HEALTH_URL; do
+ if [ -z "${!v}" ]; then echo "Input $v is empty; refusing to deploy."; exit 1; fi
+ done
+ SUDO=""
+ if [ "$(id -u)" != "0" ] && command -v sudo >/dev/null 2>&1; then SUDO="sudo"; fi
+ if ! command -v sshpass >/dev/null 2>&1 || ! command -v ssh >/dev/null 2>&1 || ! command -v scp >/dev/null 2>&1; then
+ $SUDO apt-get update && $SUDO apt-get install -y sshpass openssh-client
+ fi
+
+ D=$(mktemp -d)
+ mkdir -p "$D/bin"
+ echo "DEPLOY_TMP=$D" >> "$GITHUB_ENV"
+ echo "$D/bin" >> "$GITHUB_PATH"
+
+ if [ -n "$SSH_KEY" ]; then
+ printf '%s\n' "$SSH_KEY" > "$D/key"
+ chmod 600 "$D/key"
+ if ssh -i "$D/key" -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=no -o ConnectTimeout=15 \
+ -p "$SSH_PORT" "$SSH_USER@$SSH_HOST" true; then
+ touch "$D/key_ok"
+ echo "Authentication: deploy key"
+ else
+ echo "Deploy key rejected or host unreachable with it; falling back to password"
+ fi
+ else
+ echo "No deploy key set; using password"
+ fi
+
+ cat > "$D/bin/rssh" <<'WRAP'
+ #!/bin/sh
+ D="$(dirname "$0")/.."
+ if [ -f "$D/key_ok" ]; then
+ exec ssh -i "$D/key" -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=no -p "$SSH_PORT" "$SSH_USER@$SSH_HOST" "$@"
+ fi
+ exec sshpass -p "$SSH_PASS" ssh -o StrictHostKeyChecking=no -p "$SSH_PORT" "$SSH_USER@$SSH_HOST" "$@"
+ WRAP
+ cat > "$D/bin/rscp" <<'WRAP'
+ #!/bin/sh
+ D="$(dirname "$0")/.."
+ if [ -f "$D/key_ok" ]; then
+ exec scp -i "$D/key" -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=no -P "$SSH_PORT" "$@"
+ fi
+ exec sshpass -p "$SSH_PASS" scp -o StrictHostKeyChecking=no -P "$SSH_PORT" "$@"
+ WRAP
+ chmod +x "$D/bin/rssh" "$D/bin/rscp"
+
- name: Compute release timestamp
id: release
run: echo "timestamp=$(date -u +%Y%m%d%H%M%S)" >> "$GITHUB_OUTPUT"
@@ -68,11 +135,7 @@ jobs:
SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
run: |
echo "Environment: ${{ inputs.environment }}"
- sudo apt-get update && sudo apt-get install -y sshpass
- sshpass -p "$SSH_PASS" ssh \
- -p "$SSH_PORT" \
- -o StrictHostKeyChecking=no \
- "$SSH_USER@$SSH_HOST" \
+ rssh \
"bash ~/scripts/backup-slpsoftware-db.sh ${{ inputs.environment }}"
# Uploads the published output to a fresh, timestamped release directory rather than
@@ -92,16 +155,10 @@ jobs:
SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
run: |
echo "Environment: ${{ inputs.environment }}, transport: ${{ inputs.transport }}"
- sudo apt-get update && sudo apt-get install -y sshpass
RELEASE_DIR="${{ inputs.deploy_path }}/releases/${{ steps.release.outputs.timestamp }}"
- sshpass -p "$SSH_PASS" ssh \
- -p "$SSH_PORT" \
- -o StrictHostKeyChecking=no \
- "$SSH_USER@$SSH_HOST" \
+ rssh \
"mkdir -p $RELEASE_DIR"
- sshpass -p "$SSH_PASS" scp \
- -P "$SSH_PORT" \
- -o StrictHostKeyChecking=no \
+ rscp \
-r ${{ inputs.artifact_name }}/* \
"$SSH_USER@$SSH_HOST:$RELEASE_DIR/"
@@ -123,10 +180,7 @@ jobs:
SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
run: |
RELEASE_DIR="${{ inputs.deploy_path }}/releases/${{ steps.release.outputs.timestamp }}"
- sshpass -p "$SSH_PASS" ssh \
- -p "$SSH_PORT" \
- -o StrictHostKeyChecking=no \
- "$SSH_USER@$SSH_HOST" \
+ rssh \
"mkdir -p ${{ inputs.deploy_path }}/shared/wwwroot-web && \
mkdir -p $RELEASE_DIR/wwwroot && \
rm -rf $RELEASE_DIR/wwwroot/web && \
@@ -150,10 +204,7 @@ jobs:
SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
run: |
RELEASE_DIR="${{ inputs.deploy_path }}/releases/${{ steps.release.outputs.timestamp }}"
- sshpass -p "$SSH_PASS" ssh \
- -p "$SSH_PORT" \
- -o StrictHostKeyChecking=no \
- "$SSH_USER@$SSH_HOST" \
+ rssh \
"mkdir -p ${{ inputs.deploy_path }}/shared/modules && \
ls ${{ inputs.deploy_path }}/shared/modules/*.dll 2>/dev/null | while read -r f; do \
name=\$(basename \"\$f\"); \
@@ -172,10 +223,7 @@ jobs:
SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
run: |
RELEASE_DIR="${{ inputs.deploy_path }}/releases/${{ steps.release.outputs.timestamp }}"
- sshpass -p "$SSH_PASS" ssh \
- -p "$SSH_PORT" \
- -o StrictHostKeyChecking=no \
- "$SSH_USER@$SSH_HOST" \
+ rssh \
"ln -sfn $RELEASE_DIR ${{ inputs.deploy_path }}/current && \
systemctl --user restart ${{ inputs.service_name }}"
@@ -206,8 +254,9 @@ jobs:
SSH_PORT: ${{ secrets.PI_MAIN_PORT }}
SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
run: |
- sshpass -p "$SSH_PASS" ssh \
- -p "$SSH_PORT" \
- -o StrictHostKeyChecking=no \
- "$SSH_USER@$SSH_HOST" \
+ rssh \
"cd ${{ inputs.deploy_path }}/releases && ls -1t | tail -n +3 | xargs -r rm -rf"
+
+ - name: Remove deploy key
+ if: always()
+ run: rm -rf "${DEPLOY_TMP:-/nonexistent}"
diff --git a/README.md b/README.md
index a7b2831..f6f8165 100644
--- a/README.md
+++ b/README.md
@@ -5,8 +5,8 @@ Een modulaire monolith CMS gebouwd met .NET 10.
## Projectstructuur
- `src/SlpModularCms.Api`: De host applicatie en API shell (lokale ontwikkeling / dev-host).
-- `src/SlpModularCms.Api.SlpSoftware`: Tweede Client-project, de daadwerkelijk gedeployde API voor `test.slpsoftware.nl`/`slpsoftware.nl` (CI/CD-cutover vanaf `SlpModularCms.Api`). Host dezelfde modules als `SlpModularCms.Api` via dezelfde gedeelde `CmsHost`-compositie (zie hieronder), plus de `Offerings`-module. Heeft een eigen, geïsoleerde lokale ontwikkeldatabase — zie `appsettings.Development.json` in dat project.
-- `src/SlpModularCms.Api.AndreaSlopFotografie`: Derde Client-project voor Andrea Slop Fotografie (testomgeving `test.andreaslop.nl`). Host alleen de modules `Identity` en `Availability` (geen `Master`, geen `Offerings`) en serveert de voorgerenderde website uit `wwwroot/web/` (`WebsiteMode.PrerenderedPages`) plus de admin met het thema `asf` op `/admin`. Lokaal op poort `5200`, eigen database (`appsettings.Development.json`). Bijbehorende tests: `SlpModularCms.Api.AndreaSlopFotografie.Tests` (de pipelinetests daarin hebben net als `Api.Tests` een bereikbare MariaDB nodig).
+- `src/SlpModularCms.Api.SlpSoftware`: Tweede Client-project, de daadwerkelijk gedeployde API voor `test.slpsoftware.nl`/`slpsoftware.nl` (CI/CD-cutover vanaf `SlpModularCms.Api`). Host dezelfde modules als `SlpModularCms.Api` via dezelfde gedeelde `CmsHost`-compositie (zie hieronder), plus de `Offerings`- en `Contact`-module. Heeft een eigen, geïsoleerde lokale ontwikkeldatabase — zie `appsettings.Development.json` in dat project.
+- `src/SlpModularCms.Api.AndreaSlopFotografie`: Derde Client-project voor Andrea Slop Fotografie (testomgeving `test.andreaslop.nl`). Host de modules `Identity`, `Availability`, `Offerings` en `Contact` (geen `Master`) en serveert de voorgerenderde website uit `wwwroot/web/` (`Website:Mode=PrerenderedPages`) plus de admin met het thema `asf` op `/admin`. Lokaal op poort `5200`, eigen database (`appsettings.Development.json`). Geen eigen testproject: het gedrag zit in Core en de modules en wordt getest op de master-`SlpModularCms.Api` (alle modules); de samenstelling en standaardwaarden van deze site worden getest in `SlpModularCms.Api.Tests` (`SiteContractTests`, `AsfVariantPipelineTests`) en `SlpModularCms.Modules.Contact.Tests` (`SiteVariantContactTests`). `Website:Mode=PrerenderedPages` staat in de eigen `appsettings.json`.
- `src/SlpModularCms.Core`: Kern functionaliteiten, data modellen en interfaces. Bevat ook `Core/Hosting/CmsHost.cs` — de gedeelde service- en pipeline-compositie die elk Client-project (`Api`, `Api.SlpSoftware`) vanuit zijn eigen dunne `Program.cs` aanroept, zodat beide projecten niet uit elkaar kunnen groeien.
- `src/SlpModularCms.Modules.*`: Onafhankelijke functionele modules.
- `frontend/`: De CMS admin web-UI (Vite + React + TypeScript). Bewust buiten `src/` gehouden om de .NET solution schoon te houden.
@@ -105,7 +105,7 @@ De frontend leest de API-basis-URL uit een environment-variabele (zie `frontend/
```
VITE_API_BASE_URL=http://localhost:5000
```
-Per site kan de admin bij het bouwen een thema en standaardtaal krijgen: `VITE_THEME=asf` kiest `frontend/themes/asf/theme.css` (alleen CSS-variabelen, zelf gehoste lettertypen via `@fontsource`, plus een eigen favicon; een onbekende themanaam laat de build falen, leeg of afwezig = het standaardthema) en `VITE_DEFAULT_LANGUAGE=nl` (of `en`) bepaalt de taal zolang de gebruiker nog niets koos; een opgeslagen keuze wint altijd.
+Per site kan de admin bij het bouwen een thema en standaardtaal krijgen (beschikbare thema's: `asf` en `slpsoftware`, zie [docs/cms-themas.md](docs/cms-themas.md)): `VITE_THEME=asf` kiest `frontend/themes/asf/theme.css` (alleen CSS-variabelen, zelf gehoste lettertypen via `@fontsource`, plus een eigen favicon; een onbekende themanaam laat de build falen, leeg of afwezig = het standaardthema) en `VITE_DEFAULT_LANGUAGE=nl` (of `en`) bepaalt de taal zolang de gebruiker nog niets koos; een opgeslagen keuze wint altijd.
Kopieer `.env.example` naar `.env.local` en pas de waarde aan indien nodig. Optioneel kan met `VITE_ENABLE_MSW=true` de MSW-mockbackend in de browser worden ingeschakeld voor frontend-ontwikkeling zonder draaiende API.
@@ -250,6 +250,37 @@ Zolang de master-gate een slave op `NotAvailable` heeft gezet (via push of pull)
- Een lokale poging om de status alsnog te wijzigen (bijv. via een directe API-call) wordt door de backend geweigerd met `409 Conflict` (`MasterControlledAvailabilityException` in `PersistentAvailabilityService.UpdateStatusAsync`) — de master-gate kan dus niet per ongeluk of expres lokaal worden omzeild.
- `GET /api/v1/Availability/status` geeft dit door via het veld `isMasterControlled`.
+## Offerings: aanbiedingen en banner
+
+De module `SlpModularCms.Modules.Offerings` (gehost door `Api.SlpSoftware` en `Api.AndreaSlopFotografie`) beheert de aanbiedingen (pakketten, met categorieën) en de banner van de website. Hieronder alleen de banner; details en beslissingen staan in `aidlc-docs/features/offering-banners/overview.md`.
+
+Een banner heeft een **positie**: `top` (smalle balk boven de pagina, één regel) of `bottom` (grote banner; bestaande banners zijn via migratie `20261114100000_AddOfferingBannerPosition` `bottom` geworden).
+
+**Publiek:** `GET /api/v1/offerings/banner?position=top|bottom`
+- Zonder `position` geldt `bottom`; een andere waarde geeft `400`.
+- `204` zonder actieve banner; anders `200` met `title`, `text`, `linkLabel`, `linkUrl`, `position` (geen planning).
+- Anoniem, rate limit `offerings-public` (standaard 120 per 60 s per clientadres, `RateLimiting:OfferingsPublic`), antwoord met `Cache-Control: public, max-age=60`.
+
+**Beheer:** `/api/v1/offerings/banners` (`GET`, `POST`, `PUT {id}`, `DELETE {id}`), alleen voor beheerders (`AdminOnly`).
+
+**Velden en validatie:** `top`: tekst max 120 tekens, titel optioneel. `bottom`: titel verplicht (max 100), tekst max 300. Knoptekst (max 50) en link (max 500) alleen samen; een link is `https://…` of een pad dat met één `/` begint. `endsAt` moet na `startsAt` liggen. `isActive` en de planning (`startsAt`/`endsAt`) bepalen of een banner meetelt.
+
+**"Maximaal één per positie"** geldt bij het uitlezen: je kunt meer banners opslaan en aanzetten; per positie wint de laatst gewijzigde actieve banner die binnen zijn van/tot valt. Een boven- en een onderbanner kunnen dus tegelijk getoond worden.
+
+**Admin** (tabblad Banner bij Aanbiedingen): één lijst met een badge Locatie (Boven/Onder), de status (Actief, Gepland, Verlopen, Uit), de markeringen "Live" (wordt getoond) en "Wordt niet getoond" (actief, maar een nieuwere banner op dezelfde locatie wint), en een aan/uit-knop per rij. Het formulier heeft een keuzeveld Locatie dat de tekstlimiet en de titelplicht aanpast.
+
+## Contactformulier-module
+
+De module `SlpModularCms.Modules.Contact` (gehost door `Api.SlpSoftware` en `Api.AndreaSlopFotografie`; tests in `SlpModularCms.Modules.Contact.Tests`) ontvangt berichten van het contactformulier van een website, slaat ze op, mailt een melding naar de eigenaar en laat beheerders ze in de admin (Berichten) beheren. Plan en beslissingen: `aidlc-docs/features/contact-forms-module/`. Welke gegevens worden bewaard, hoe lang en wat in logs en Sentry terechtkomt: [`docs/privacy-gegevens-contactformulier.md`](docs/privacy-gegevens-contactformulier.md).
+
+- **Uit tenzij beide schakelaars aan staan:** de hostschakelaar `Contact:Enabled` (standaard `false` in beide `appsettings.json`) én de CMS-schakelaar bij Berichten. Is het formulier niet open, dan bestaan de publieke routes niet (404). De migraties van de module worden pas bij het opstarten toegepast als `Contact:Enabled` aan staat.
+- **Publiek:** `GET /api/v1/contact-messages/token` (tijdtoken, plus eventuele captcha-gegevens) en `POST /api/v1/contact-messages` (JSON, header `Idempotency-Key` met een GUID; antwoord `202`; fouten `400` in `ProblemDetails`-vorm met veldcodes `required`, `tooLong`, `invalid`, `expired`).
+- **Beheer** (`AdminOnly`): `GET /api/v1/contact-messages`, `GET`/`PATCH`/`DELETE …/{id}`, `POST …/{id}/resend`, en `GET`/`PUT /api/v1/contact-settings` (schakelaar) met `PUT …/contact-settings/recipient` (ontvangstadres).
+- **Anti-spam:** honeypot, minimumtijd tussen token en verzenden, optioneel Friendly Captcha, rate limiting per clientadres (`RateLimiting:ContactForm`, `ContactToken`, `ContactResend`). Achter een reverse proxy moet `ForwardedHeaders__KnownProxies__0` gezet zijn, anders delen alle bezoekers één limiet.
+- **Configuratie (sectie `Contact`):** `Enabled`, `SiteId`, `MinSeconds` (3), `TokenLifetimeMinutes` (120), `RetentionMonths` (12), `SpamRetentionDays` (30), `MaxSpamRowsPerDay` (200), `MaxBodyBytes` (16384), `ProblemTypeBase`, `RecipientEmail` (alleen via omgevingsvariabele `Contact__RecipientEmail`), `Mail:SweepSeconds`/`MaxAttempts`/`BackoffMinutes`/`ClaimMinutes`/`BatchSize`, en `Captcha:Enabled`/`Provider` (`friendlycaptcha`)/`SiteKey`/`Secret` (alleen via `Contact__Captcha__Secret`)/`Region` (`global` of `eu`)/`VerifyUrl`/`TimeoutSeconds`. Een aangezet captcha met ontbrekende of ongeldige instellingen laat de host bij opstarten falen.
+- **Opschonen:** een dagelijkse achtergrondtaak verwijdert berichten na hun bewaartermijn en idempotentie-gegevens na 24 uur.
+- **Mail:** vereist werkende e-mailconfiguratie (zie "E-mail" hierboven) en een ontvangstadres; anders blijft het bericht bewaard met de reden bij het bericht.
+
## Lokaal Master + Slave Draaien (Dev)
Om de master↔slave-connectie (zie "Master CMS Module" hierboven) lokaal te kunnen testen, kun je twee backend-instanties tegelijk draaien: een volledige "master" (met de `SlpModularCms.Modules.Master`-module) en een "slave"-instantie zonder die module. Dit is puur een lokale ontwikkel-/testopstelling — er is geen nieuwe functionaliteit aan de master/slave-protocol zelf toegevoegd.
@@ -324,7 +355,7 @@ Ontbreekt `wwwroot/web/` nog (een verse deployment vóórdat een website-workspa
Voor lokale ontwikkeling verandert er niets: `pnpm dev` blijft op `http://localhost:5173` draaien zonder `/admin`-prefix.
### 1. Build & Publish
-Publiceren gebeurt via de Gitea Actions-pipeline (`.gitea/workflows/continuous_integration.yaml` → `deploy-scp.yaml`), niet met een losse handmatige `dotnet publish`-stap: elke push naar `master` deployt automatisch naar test, productie alleen via een expliciete `workflow_dispatch` met de `deploy_production`-vlag aan. De pipeline publiceert framework-dependent voor `linux-arm64` en bouwt daarbij automatisch ook de admin-frontend mee naar `wwwroot/admin/`.
+Publiceren gebeurt via de Gitea Actions-pipeline (`.gitea/workflows/continuous_integration.yaml` → `deploy-scp.yaml`), niet met een losse handmatige `dotnet publish`-stap: elke push naar `master` deployt automatisch naar de SlpSoftware-testomgeving (en naar de ASF-testomgeving als de Gitea-variabele `ASF_TEST_DEPLOY_ENABLED` op `true` staat), productie alleen via een expliciete `workflow_dispatch` met de `deploy_production`-vlag aan. Een branch naar test deployen kan met een handmatige run (`deploy_test` en/of `deploy_asf_test`). Zie [`docs/deploy-en-testomgevingen.md`](docs/deploy-en-testomgevingen.md) voor invoer, testhosts, vereiste variabelen en secrets (alleen namen) en rollback. De pipeline publiceert framework-dependent voor `linux-arm64` en bouwt daarbij automatisch ook de admin-frontend mee naar `wwwroot/admin/`.
Elke deploy plaatst de nieuwe release in een verse map en wisselt pas daarna atomisch over naar `current` — er is dus nooit een moment waarop de applicatie een halfklare release serveert, en `wwwroot/web/` (de klantsite) staat structureel buiten die verwisselde map, zodat een deploy hem nooit kan raken. Volledige host-setup, rollback-procedure en de exacte deploy-stappen staan in de Operations-documentatie van deze feature, niet hier — dit README beschrijft alleen wat er gebouwd is, niet hoe je het voor het eerst inricht.
@@ -345,7 +376,7 @@ In productie moeten gevoelige instellingen worden doorgegeven via Environment Va
- `Observability__SentryDsn` — leeg is een normale, ondersteunde staat: Sentry wordt dan overgeslagen en alleen console-logging blijft actief
- `SecurityHeaders__AllowedScriptOrigins__0`, `SecurityHeaders__AllowedConnectOrigins__0`, ... — externe origins die de CSP van `/admin` en `/api/v1` mag toestaan (bijv. de Umami-scripthost en Sentry's ingest-endpoint). Zie `appsettings.json → SecurityHeaders` voor de volledige optiesvorm; een onbekende `PathPolicies`-policy-naam laat de applicatie bij **opstarten** falen, niet pas bij de eerste request
-- **Voorgerenderde website (`WebsiteMode.PrerenderedPages`)** — een client kiest dit in zijn `Program.cs` via `CmsHostOptions` (standaard `SpaFallback`: alles blijft zoals het was). Instellingen voor deze modus: `Website__NoIndex=true` (testinstantie: `X-Robots-Tag` plus `robots.txt` met `Disallow: /`), `SecurityHeaders__DefaultPolicy=StrictSite` met `SecurityHeaders__AllowedSiteScriptOrigins__0`, `SecurityHeaders__AllowedSiteConnectOrigins__0`, ... (alleen gebruikt door `StrictSite`). Logging van de website (301's en 404's op `Information`) gaat via de logger-categorie `SlpModularCms.Website`: zet per omgeving `Website__LogLevel` (test `Information`, standaard en productie `Warning`; leeg = `Logging:LogLevel` beslist). Gebruik niet `Logging__LogLevel__SlpModularCms.Website` in een systemd-`EnvironmentFile`: een variabelenaam met een punt wordt daar genegeerd. Gedrag per pad staat in [`WEBSITE_WORKSPACE.md`](WEBSITE_WORKSPACE.md).
+- **Voorgerenderde website (`Website:Mode=PrerenderedPages`)** — een client kiest dit in zijn `Program.cs` via `CmsHostOptions` (standaard `SpaFallback`: alles blijft zoals het was). Instellingen voor deze modus: `Website__NoIndex=true` (testinstantie: `X-Robots-Tag` plus `robots.txt` met `Disallow: /`), `SecurityHeaders__DefaultPolicy=StrictSite` met `SecurityHeaders__AllowedSiteScriptOrigins__0`, `SecurityHeaders__AllowedSiteConnectOrigins__0`, ... (alleen gebruikt door `StrictSite`). Logging van de website (301's en 404's op `Information`) gaat via de logger-categorie `SlpModularCms.Website`: zet per omgeving `Website__LogLevel` (test `Information`, standaard en productie `Warning`; leeg = `Logging:LogLevel` beslist). Gebruik niet `Logging__LogLevel__SlpModularCms.Website` in een systemd-`EnvironmentFile`: een variabelenaam met een punt wordt daar genegeerd. Gedrag per pad staat in [`WEBSITE_WORKSPACE.md`](WEBSITE_WORKSPACE.md).
### 2a. Data Protection key ring (Master CMS Module)
De API keys van geregistreerde slaves worden versleuteld opgeslagen met ASP.NET Core Data Protection. De key ring wordt **automatisch** persistent opgeslagen in de database (`PersistKeysToDbContext`, met een expliciete, stabiele applicatie-discriminator) — dit hoeft niet meer apart geconfigureerd te worden. Dit is bewust zo gebouwd omdat de atomische release-switch (zie hierboven) bij elke deploy een nieuwe content-root-map gebruikt: zonder een database-backed key ring zou dat elke keer de key ring weggooien en alle opgeslagen slave-API-keys onleesbaar maken.
diff --git a/SlpModularCms.Ci.slnf b/SlpModularCms.Ci.slnf
new file mode 100644
index 0000000..a5045cf
--- /dev/null
+++ b/SlpModularCms.Ci.slnf
@@ -0,0 +1,21 @@
+{
+ "solution": {
+ "path": "SlpModularCms.sln",
+ "projects": [
+ "src\\SlpModularCms.Api\\SlpModularCms.Api.csproj",
+ "src\\SlpModularCms.Core\\SlpModularCms.Core.csproj",
+ "src\\SlpModularCms.Core.Tests\\SlpModularCms.Core.Tests.csproj",
+ "src\\SlpModularCms.Modules.Availability\\SlpModularCms.Modules.Availability.csproj",
+ "src\\SlpModularCms.Modules.Availability.Tests\\SlpModularCms.Modules.Availability.Tests.csproj",
+ "src\\SlpModularCms.Modules.Identity\\SlpModularCms.Modules.Identity.csproj",
+ "src\\SlpModularCms.Modules.Identity.Tests\\SlpModularCms.Modules.Identity.Tests.csproj",
+ "src\\SlpModularCms.Modules.Master\\SlpModularCms.Modules.Master.csproj",
+ "src\\SlpModularCms.Modules.Master.Tests\\SlpModularCms.Modules.Master.Tests.csproj",
+ "src\\SlpModularCms.Api.Tests\\SlpModularCms.Api.Tests.csproj",
+ "src\\SlpModularCms.Modules.Offerings\\SlpModularCms.Modules.Offerings.csproj",
+ "src\\SlpModularCms.Modules.Offerings.Tests\\SlpModularCms.Modules.Offerings.Tests.csproj",
+ "src\\SlpModularCms.Modules.Contact\\SlpModularCms.Modules.Contact.csproj",
+ "src\\SlpModularCms.Modules.Contact.Tests\\SlpModularCms.Modules.Contact.Tests.csproj"
+ ]
+ }
+}
diff --git a/SlpModularCms.sln b/SlpModularCms.sln
index aa999db..6576ff6 100644
--- a/SlpModularCms.sln
+++ b/SlpModularCms.sln
@@ -40,7 +40,9 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Offer
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Api.AndreaSlopFotografie", "src\SlpModularCms.Api.AndreaSlopFotografie\SlpModularCms.Api.AndreaSlopFotografie.csproj", "{759EE53D-EECA-4054-A17F-4172B0EC2015}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Api.AndreaSlopFotografie.Tests", "src\SlpModularCms.Api.AndreaSlopFotografie.Tests\SlpModularCms.Api.AndreaSlopFotografie.Tests.csproj", "{DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Contact", "src\SlpModularCms.Modules.Contact\SlpModularCms.Modules.Contact.csproj", "{59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Contact.Tests", "src\SlpModularCms.Modules.Contact.Tests\SlpModularCms.Modules.Contact.Tests.csproj", "{06C25AF5-D63F-4007-8796-C4BA27940EBA}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -232,18 +234,30 @@ Global
{759EE53D-EECA-4054-A17F-4172B0EC2015}.Release|x64.Build.0 = Release|Any CPU
{759EE53D-EECA-4054-A17F-4172B0EC2015}.Release|x86.ActiveCfg = Release|Any CPU
{759EE53D-EECA-4054-A17F-4172B0EC2015}.Release|x86.Build.0 = Release|Any CPU
- {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Debug|x64.ActiveCfg = Debug|Any CPU
- {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Debug|x64.Build.0 = Debug|Any CPU
- {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Debug|x86.ActiveCfg = Debug|Any CPU
- {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Debug|x86.Build.0 = Debug|Any CPU
- {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|Any CPU.Build.0 = Release|Any CPU
- {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|x64.ActiveCfg = Release|Any CPU
- {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|x64.Build.0 = Release|Any CPU
- {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|x86.ActiveCfg = Release|Any CPU
- {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|x86.Build.0 = Release|Any CPU
+ {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|x64.Build.0 = Debug|Any CPU
+ {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|x86.Build.0 = Debug|Any CPU
+ {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Release|Any CPU.Build.0 = Release|Any CPU
+ {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Release|x64.ActiveCfg = Release|Any CPU
+ {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Release|x64.Build.0 = Release|Any CPU
+ {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Release|x86.ActiveCfg = Release|Any CPU
+ {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Release|x86.Build.0 = Release|Any CPU
+ {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Debug|x64.Build.0 = Debug|Any CPU
+ {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Debug|x86.Build.0 = Debug|Any CPU
+ {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|Any CPU.Build.0 = Release|Any CPU
+ {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|x64.ActiveCfg = Release|Any CPU
+ {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|x64.Build.0 = Release|Any CPU
+ {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|x86.ActiveCfg = Release|Any CPU
+ {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -266,6 +280,7 @@ Global
{43DE02A5-DD13-42D1-9BF9-434E706B8500} = {30D8F44D-4B6E-4980-8D1F-29D1A64F438C}
{BF1054BD-DBD7-4D78-B99A-73FDC1362EA5} = {77DF6642-7863-4D67-BAEE-217EC2D99894}
{759EE53D-EECA-4054-A17F-4172B0EC2015} = {D72703E6-B021-4360-B1EE-0E99999B5899}
- {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B} = {2F43D186-C7D5-4AB1-B821-4D595CA2ECB3}
+ {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C} = {30D8F44D-4B6E-4980-8D1F-29D1A64F438C}
+ {06C25AF5-D63F-4007-8796-C4BA27940EBA} = {77DF6642-7863-4D67-BAEE-217EC2D99894}
EndGlobalSection
EndGlobal
diff --git a/aidlc-docs/active-features.md b/aidlc-docs/active-features.md
index 2f2020b..36736b6 100644
--- a/aidlc-docs/active-features.md
+++ b/aidlc-docs/active-features.md
@@ -3,11 +3,11 @@
| Type | Name | Status | Branch | Affected Components | Session Start |
|------|------|--------|--------|---------------------|---------------|
| Feature | SlpModularCms.Api Implementation (slp-modular-cms-api) | ✅ Complete | unknown | Core, Identity, Availability, Shell | 2026-06-07 |
-| Feature | CMS Frontend (cms-frontend) | ✅ Complete | unknown | Frontend, Identity (Auth), Availability | 2026-06-16 |
+| Feature | CMS Frontend (cms-frontend) | ✅ Complete (Build and Test en Operations gesloten 2026-11-16) | unknown | Frontend, Identity (Auth), Availability | 2026-06-16 |
| Feature | Master CMS Module (master-cms-module) | ✅ Complete | unknown | Modules, Availability | 2026-06-26 |
-| Feature | Tech Debt Backlog (tech-debt-backlog) | 🔵 Inception | unknown | Modules.Master, Frontend | 2026-07-01 |
+| Feature | Tech Debt Backlog (tech-debt-backlog) | 🔵 Doorlopende backlog (bewust open) | unknown | Modules.Master, Frontend | 2026-07-01 |
| Feature | Local Dev Master/Slave Setup (local-dev-master-slave-setup) | ✅ Complete | unknown | Modules.Master, Api, Frontend | 2026-07-02 |
-| Feature | Gitea Deployment Workflow (gitea-deployment-workflow) | 🟡 Operations (wacht op CI-proef en eerste test-deploy) | feature/gitea-deployment-workflow | CI/CD, Api (hosting/config), Core, Modules, Frontend (build), Docs | 2026-07-27 |
+| Feature | Gitea Deployment Workflow (gitea-deployment-workflow) | ✅ Complete (CI en test-deploys draaien; productiecontrole in de gezamenlijke checklist, 2026-11-16) | feature/gitea-deployment-workflow | CI/CD, Api (hosting/config), Core, Modules, Frontend (build), Docs | 2026-07-27 |
| Feature | SlpSoftware Production API (slpsoftware-api) | ✅ Complete | feature/slpsoftware-api | Clients (new Api.SlpSoftware), Modules (new Offerings module + Tests), Core (CmsHost), CI/CD (retargeted to Api.SlpSoftware) | 2026-08-02 |
| Feature | Andrea's site hosting (andreaslop-site-hosting) | ✅ Complete (gemerged naar master via PR #11, 2026-11-10; ASF-productie op IIS apart) | feature/andreaslop-site-hosting | Core (CmsHost, CSP, static content), Clients (new Api.AndreaSlopFotografie), Frontend (theme), CI/CD | 2026-11-06 |
| Bug | [cms-admin-nine-points](bugs/cms-admin-nine-points/bug-fix.md) | ✅ Complete (gemerged via PR #11, 2026-11-10) | feature/andreaslop-site-hosting | Core (auth, invitations), Identity, Availability, Frontend | 2026-11-08 |
@@ -16,3 +16,11 @@
| Bug | [owner-cannot-promote-requester-identity](bugs/owner-cannot-promote-requester-identity/bug-fix.md) | ✅ Complete (gemerged via PR #11, 2026-11-10) | feature/identity-email-notifications | Identity (UsersController) | 2026-11-08 |
| Bug | [availability-gate-blocks-website-and-admin](bugs/availability-gate-blocks-website-and-admin/bug-fix.md) | ✅ Complete (gemerged via PR #11, 2026-11-10) | feature/identity-email-notifications | Availability (middleware) | 2026-11-09 |
| Bug | [setup-page-after-failed-status-read](bugs/setup-page-after-failed-status-read/bug-fix.md) | ✅ Complete (gemerged via PR #11, 2026-11-10) | feature/identity-email-notifications | Frontend (router guard, login), Identity (Setup limiter) | 2026-11-09 |
+| Feature | Contact Forms Module (contact-forms-module) | ✅ Afgesloten 2026-11-16 (U1 t/m U12 gebouwd, Build and Test gesloten, Operations in de [gezamenlijke productie-checklist](../docs/release-checklist-productie.md); contactformulier door Bryan op test geaccepteerd; productie wacht op Bryans go) | feature/contact-forms-module | Modules (new Contact + Tests, Offerings category), Core (OnRejected, availability gate marker), Frontend (admin Berichten) | 2026-11-09 |
+| Feature | [Offering banners (offering-banners)](features/offering-banners/overview.md) | ✅ Afgesloten 2026-11-16 (op test; buiten AI-DLC gebouwd en achteraf gedocumenteerd) | feature/contact-forms-module | Modules.Offerings (banner met positie top/bottom), openapi, Frontend (admin Aanbiedingen > Banner) | 2026-11-12 |
+| Feature | [Offering schedule (offering-schedule)](features/offering-schedule/overview.md) | ✅ Afgesloten 2026-11-16 (op test; buiten AI-DLC gebouwd en achteraf gedocumenteerd) | feature/contact-forms-module | Modules.Offerings (aan/uit en van/tot per pakket, `/offerings/all`), openapi, Frontend (admin pakketformulier en -lijst) | 2026-11-15 |
+| Feature | [Website SEO (website-seo)](features/website-seo/overview.md) | ✅ Afgesloten 2026-11-16 (op SLP-test; productie vraagt `Website__NoIndex=false` en `Website__PublicBaseUrl`, zie de productie-checklist) | feature/contact-forms-module | Core (Hosting/Website), Modules.Offerings (index-markers), Api.SlpSoftware (appsettings) | 2026-11-11 |
+| Feature | [CI bouwt en test alleen het master-CMS (ci-master-pipeline)](features/ci-master-pipeline/overview.md) | ✅ Afgesloten 2026-11-16 (buiten AI-DLC gebouwd en achteraf gedocumenteerd) | feature/contact-forms-module | CI/CD (workflow, slnf, rooktest), Core (Website:Mode), Api (alle modules), Tests (ASF-testproject opgeheven) | 2026-11-15 |
+| Feature | [ASF: host injecteert in voorgerenderde pagina's (asf-host-injection)](features/asf-host-injection/plan.md) | ✅ Gebouwd en op test (afgesloten 2026-11-16; ASF-productie op IIS is een apart, later plan) | feature/contact-forms-module | Core (Hosting/Website), Modules.Offerings, docs | 2026-11-15 |
+| Feature | [Vertaalbestanden backend (translation-files)](../docs/translation-files.md) | ✅ Afgesloten 2026-11-16 (stappen 1-8, docs; buiten AI-DLC gebouwd; goedgekeurd door Bryan via SLS-Main; productie via de checklist) | feature/contact-forms-module | Core (Texts, Email, Identity, Hosting), Modules.Availability, Modules.Offerings | 2026-11-15 |
+| Bug | [theme-toggle-first-click](bugs/theme-toggle-first-click/bug-fix.md) | ✅ Complete (niet gecommit/gemerged; buiten AI-DLC gebouwd; oorzaak niet in een echte browser nagebootst) | feature/contact-forms-module | Frontend (useTheme, index.html) | 2026-11-15 |
diff --git a/aidlc-docs/bugs/theme-toggle-first-click/bug-fix.md b/aidlc-docs/bugs/theme-toggle-first-click/bug-fix.md
new file mode 100644
index 0000000..7906dc7
--- /dev/null
+++ b/aidlc-docs/bugs/theme-toggle-first-click/bug-fix.md
@@ -0,0 +1,43 @@
+# Bug Fix: the first click on the theme toggle does nothing
+
+- **Slug**: theme-toggle-first-click
+- **Status**: Complete (pending deploy; built outside the AI-DLC flow, documented afterwards)
+- **Issue**: None (reported by Bryan)
+- **Branch**: feature/contact-forms-module
+- **Started**: unknown
+- **Documentation Language**: English
+- **Conversation Language**: Dutch (user language)
+
+## Report
+
+In the admin, the first click on the light/dark toggle sometimes changed nothing visible; only the second click switched the theme.
+
+## Root Cause
+
+The `useTheme` hook (`frontend/src/hooks/useTheme.ts`) kept its own state, initialised from `localStorage` (`cms-theme`) or else from the OS preference (`prefers-color-scheme`). What is actually shown is decided by the class (`light` / `dark`) on ``, which the start script in `frontend/index.html` sets before React runs. The two were not the same source: when the hook's state and the class on `` differed, the first click flipped the hook's state and applied *that* theme, which could be the theme already shown, so nothing visible happened.
+
+Two ways they could differ, both visible in the old code:
+
+1. The start script in `index.html` took any stored value as a class name (`s ? s : ...`), while the hook only accepted `light` or `dark`. A stored value such as `system` put the class `system` on `` (no theme at all) while the hook fell back to the OS preference.
+2. Every toggle (desktop sidebar, mobile overlay) called `useTheme()` and so had its own state; flipping one left the others stale, so the next click on another toggle could re-apply the theme already shown.
+
+**Not reproduced in a real browser.** The cause was derived from reading the old code; the only evidence is that the new tests fail against the old hook (reported by the developer; not re-run for this document). Which of the two cases (or another) happened in the browser session that was reported is not known.
+
+## The Fix
+
+- `useTheme.ts`: one source of truth, the class on ``, read through `useSyncExternalStore`. If the page carries neither class, the stored value or OS preference is applied right away, so the reported state and what is shown cannot differ. `toggleTheme` flips what is shown now, stores it (inside `try/catch`, since storage can be unavailable), applies it and notifies every subscriber, so all toggles on the page share one state.
+- `index.html`: the start script accepts only `light` or `dark` from storage; anything else falls back to the OS preference.
+
+## Verification
+
+**Path used**: Automated test framework (`frontend/src/hooks/useTheme.test.ts`, new block `first click`, 4 tests): with the OS preferring light and with it preferring dark and nothing stored or applied, the first click flips the shown theme; an unusable stored value (`system`) with class `system` on `` still flips from what is shown; when the shown theme differs from the stored one the toggle follows the shown one and stores the new value; two toggles on one page stay in step.
+
+**Before the fix**: according to the developer, the new tests fail against the old hook. Not re-run for this document. **After the fix**: not re-run for this document either.
+
+**Not verified**: behaviour in a real browser (no manual reproduction before or after the fix).
+
+## Result
+
+- **PR(s)**: None
+- **Commit(s)**: commit "CMS: één bannerlijst met Locatie, SLP-thema, thema-schakelaar" on feature/contact-forms-module (2026-11-15)
+- **Completed**: 2026-11-15 (documentation)
diff --git a/aidlc-docs/features/asf-host-injection/plan.md b/aidlc-docs/features/asf-host-injection/plan.md
new file mode 100644
index 0000000..14697da
--- /dev/null
+++ b/aidlc-docs/features/asf-host-injection/plan.md
@@ -0,0 +1,61 @@
+# Host injection into ASF's prerendered pages (asf-host-injection)
+
+- **Slug**: asf-host-injection
+- **Type**: Feature, **proposal; not approved, build not started**
+- **Status**: **Built** on `feature/contact-forms-module` (commits 7d66944, a136615, ef4fb9d, 4baadf3 and the one after it; tests green locally), **not yet deployed**: needs the website build with the markers and `Website__PublicBaseUrl=https://test.andreaslop.nl` in the ASF-test env file. Before: plan agreed with the ASF session (their counterpart: `AndreaSlopFotografie-packages/aidlc-docs/features/asf-cms-host-injection/plan.md`, section "Host contract"). Bryan accepted the approach (neutral list first, styled cards after hydration; the host writes the list HTML) on 2026-11-15 but said **not to start building yet**: he first reads the plan and finds out whether .NET 10 can run on the hosting package (hosting bundle or self-contained).
+- **Affected components (planned)**: `SlpModularCms.Core` (`Hosting/Website`: generalise `IndexHtmlInjector`, hook in `PrerenderedSiteMiddleware`), `SlpModularCms.Modules.Offerings` (marker providers), `scripts/smoke-site.sh`, docs
+- **Documented**: 2026-11-15
+- **Documentation Language**: English
+- **Conversation Language**: Dutch (user language)
+
+## Why
+
+Bryan's hosting package has one entry per website: the CMS host is that entry and serves the website, the prerendered pages and `/admin`. So ASF in production also runs entirely through Kestrel (IIS passes every request on, serves no static files and caches no HTML). Packages, banners and (later) gallery data can therefore be written into the prerendered HTML by the host: visible to crawlers within about a minute of a CMS change, without a nightly build. A rebuild webhook stays an option only for build-processed gallery images.
+
+## Host contract (agreed with ASF)
+
+All markers are found in one pass; a page without markers and without the authored address is still served as a plain static file. **Fail-open everywhere**: missing marker = nothing; invalid data or a provider failure = the baked page is served.
+
+| Marker | Host behaviour |
+|---|---|
+| `…` | Replace the content between the markers by a simple crawlable list from the live offerings (C# template following ASF's "Neutral HTML spec" and their golden files; everything HTML-encoded). The markers stay. |
+| `…`, `…` | Same, from the live banner of that position as `
+ )}
+
+ {tab === 'offerings' && (
+
+
+
+ )}
+
+
+
{
+ _resetSetupStatusCache();
+ resetMockOfferings();
+ mockAuthenticated();
+});
+
+afterEach(async () => {
+ await i18n.changeLanguage('en');
+});
+
+describe('Offerings page on small and large screens', () => {
+ it('has a floating add button that is only shown below sm, at least 44px, in the safe area', async () => {
+ renderApp('/offerings');
+ const fab = await screen.findByTestId('offerings-add-fab', {}, LONG);
+
+ expect(fab).toHaveAttribute('href', '/offerings/new');
+ expect(fab).toHaveAccessibleName('Add Offering');
+ expect(fab.className).toContain('sm:hidden');
+ expect(fab.className).toContain('fixed');
+ expect(fab.className).toContain('right-[max(1rem,env(safe-area-inset-right))]');
+ expect(fab.className).toContain('bottom-[max(1rem,env(safe-area-inset-bottom))]');
+ expect(fab.className).toContain('size-14'); // 56px, above the 44px minimum
+ expect(fab.querySelector('svg')).toHaveAttribute('aria-hidden', 'true');
+ });
+
+ it('shows the text add button only from sm up', async () => {
+ renderApp('/offerings');
+ const button = await screen.findByTestId('offerings-add-button', {}, LONG);
+
+ expect(button.className).toContain('hidden');
+ expect(button.className).toContain('sm:inline-flex');
+ expect(button).toHaveTextContent('Add Offering');
+ });
+
+ it('has an icon-only categories button below sm with an accessible name and tooltip, text button from sm up', async () => {
+ renderApp('/offerings');
+ const icon = await screen.findByTestId('offerings-categories-icon-button', {}, LONG);
+ const text = screen.getByTestId('offerings-categories-button');
+
+ expect(icon).toHaveAccessibleName('Manage categories');
+ expect(icon).toHaveAttribute('title', 'Manage categories');
+ expect(icon.className).toContain('sm:hidden');
+ expect(icon.className).toContain('size-11'); // 44px
+ expect(icon).toHaveTextContent('');
+ expect(text.className).toContain('hidden');
+ expect(text.className).toContain('sm:inline-flex');
+ expect(text).toHaveTextContent('Manage categories');
+ });
+
+ it('keeps extra bottom space below sm so the FAB does not cover the last row', async () => {
+ renderApp('/offerings');
+ const page = await screen.findByTestId('offerings-page', {}, LONG);
+
+ expect(page.className).toContain('pb-24');
+ expect(page.className).toContain('sm:pb-4');
+ });
+
+ it('opens the categories dialog from the icon button', async () => {
+ renderApp('/offerings');
+ await userEvent.click(
+ await screen.findByTestId('offerings-categories-icon-button', {}, LONG),
+ );
+
+ expect(await screen.findByRole('dialog')).toBeInTheDocument();
+ });
+
+ it('uses Dutch names when the language is Dutch', async () => {
+ await i18n.changeLanguage('nl');
+ renderApp('/offerings');
+
+ expect(await screen.findByTestId('offerings-add-fab', {}, LONG)).toHaveAccessibleName(
+ 'Aanbieding toevoegen',
+ );
+ expect(screen.getByTestId('offerings-categories-icon-button')).toHaveAccessibleName(
+ 'Categorieën beheren',
+ );
+ });
+});
diff --git a/frontend/src/features/offerings/schemas/offering.test.ts b/frontend/src/features/offerings/schemas/offering.test.ts
index b754d4d..28589fb 100644
--- a/frontend/src/features/offerings/schemas/offering.test.ts
+++ b/frontend/src/features/offerings/schemas/offering.test.ts
@@ -10,6 +10,9 @@ function validOffering() {
features: ['1 page'],
ctaLabel: 'Get started',
featured: false,
+ isActive: true,
+ startsAt: '',
+ endsAt: '',
};
}
@@ -48,4 +51,19 @@ describe('offeringFormSchema', () => {
const result = offeringFormSchema.safeParse({ ...validOffering(), title: '' });
expect(result.success).toBe(false);
});
+
+ it('accepts an empty schedule and a valid one', () => {
+ expect(offeringFormSchema.safeParse(validOffering()).success).toBe(true);
+ expect(
+ offeringFormSchema.safeParse({ ...validOffering(), startsAt: '2026-11-15T10:00', endsAt: '2026-11-16T10:00' }).success,
+ ).toBe(true);
+ });
+
+ it('rejects an end that is not after the start', () => {
+ const same = offeringFormSchema.safeParse({ ...validOffering(), startsAt: '2026-11-15T10:00', endsAt: '2026-11-15T10:00' });
+ const before = offeringFormSchema.safeParse({ ...validOffering(), startsAt: '2026-11-15T10:00', endsAt: '2026-11-14T10:00' });
+
+ expect(same.success).toBe(false);
+ expect(before.success).toBe(false);
+ });
});
diff --git a/frontend/src/features/offerings/schemas/offering.ts b/frontend/src/features/offerings/schemas/offering.ts
index 683d11c..7adb6c9 100644
--- a/frontend/src/features/offerings/schemas/offering.ts
+++ b/frontend/src/features/offerings/schemas/offering.ts
@@ -1,28 +1,38 @@
import { z } from 'zod';
-export const offeringFormSchema = z.object({
- title: z.string().min(1, 'Title is required').max(100, 'Title must be 100 characters or fewer'),
- description: z
- .string()
- .min(1, 'Description is required')
- .max(500, 'Description must be 500 characters or fewer'),
- price: z.string().min(1, 'Price is required').max(50, 'Price must be 50 characters or fewer'),
- priceNote: z
- .string()
- .min(1, 'Price note is required')
- .max(100, 'Price note must be 100 characters or fewer'),
- features: z
- .array(z.string().min(1, 'Feature cannot be empty').max(200, 'Feature must be 200 characters or fewer'))
- .min(1, 'At least 1 feature is required')
- .max(10, 'At most 10 features are allowed'),
- ctaLabel: z.string().min(1, 'CTA label is required').max(50, 'CTA label must be 50 characters or fewer'),
- featured: z.boolean(),
- slug: z
- .string()
- .max(130, 'Slug must be 130 characters or fewer')
- .regex(/^[a-z0-9]+(-[a-z0-9]+)*$/, 'Slug may only contain lowercase letters, digits and hyphens')
- .optional()
- .or(z.literal('')),
-});
+export const offeringFormSchema = z
+ .object({
+ title: z.string().min(1, 'Title is required').max(100, 'Title must be 100 characters or fewer'),
+ /** Optional: an empty value is stored as an empty string. */
+ description: z.string().max(500, 'Description must be 500 characters or fewer'),
+ price: z.string().min(1, 'Price is required').max(50, 'Price must be 50 characters or fewer'),
+ priceNote: z.string().max(100, 'Price note must be 100 characters or fewer'),
+ features: z
+ .array(z.string().min(1, 'Feature cannot be empty').max(200, 'Feature must be 200 characters or fewer'))
+ .min(1, 'At least 1 feature is required')
+ .max(10, 'At most 10 features are allowed'),
+ ctaLabel: z.string().min(1, 'CTA label is required').max(50, 'CTA label must be 50 characters or fewer'),
+ featured: z.boolean(),
+ slug: z
+ .string()
+ .max(130, 'Slug must be 130 characters or fewer')
+ .regex(/^[a-z0-9]+(-[a-z0-9]+)*$/, 'Slug may only contain lowercase letters, digits and hyphens')
+ .optional()
+ .or(z.literal('')),
+ /** Id of the chosen category; null/absent = no category. */
+ categoryId: z.string().nullable().optional(),
+ isActive: z.boolean(),
+ /** datetime-local value ("YYYY-MM-DDTHH:mm") in the browser's time zone, or ''. */
+ startsAt: z.string(),
+ endsAt: z.string(),
+ })
+ .superRefine((v, ctx) => {
+ if (v.startsAt && v.endsAt && new Date(v.endsAt).getTime() <= new Date(v.startsAt).getTime()) {
+ ctx.addIssue({ code: 'custom', path: ['endsAt'], message: 'End must be after start' });
+ }
+ });
export type OfferingFormData = z.infer;
+
+/** A category name as typed by an admin (already trimmed by the caller). */
+export const categoryNameSchema = z.string().min(1).max(100);
diff --git a/frontend/src/features/offerings/schemas/offeringBanner.ts b/frontend/src/features/offerings/schemas/offeringBanner.ts
new file mode 100644
index 0000000..cd6ecd3
--- /dev/null
+++ b/frontend/src/features/offerings/schemas/offeringBanner.ts
@@ -0,0 +1,96 @@
+import { z } from 'zod';
+import type { BannerPosition } from '../services/types';
+
+/** https:// address or a site path with a single leading slash; mirrors the API rule. */
+export function isAllowedBannerLink(url: string): boolean {
+ if (/[\s\\]/.test(url) || [...url].some((c) => c.charCodeAt(0) < 32)) return false;
+ if (url.startsWith('/')) return !url.startsWith('//');
+ try {
+ const parsed = new URL(url);
+ return parsed.protocol === 'https:' && parsed.hostname !== '';
+ } catch {
+ return false;
+ }
+}
+
+export const BANNER_TOP_TEXT_MAX = 120;
+export const BANNER_BOTTOM_TEXT_MAX = 300;
+
+export const bannerTextMaxLength = (position: BannerPosition) =>
+ position === 'top' ? BANNER_TOP_TEXT_MAX : BANNER_BOTTOM_TEXT_MAX;
+
+export const offeringBannerFormSchema = z
+ .object({
+ position: z.enum(['top', 'bottom']),
+ /** Required for 'bottom', optional for 'top' (checked in superRefine). */
+ title: z.string().trim().max(100, 'Title must be 100 characters or fewer'),
+ /** Max length depends on the position (checked in superRefine). */
+ text: z.string().trim().min(1, 'Text is required'),
+ linkLabel: z.string().trim().max(50, 'Button text must be 50 characters or fewer'),
+ linkUrl: z.string().trim().max(500, 'Link must be 500 characters or fewer'),
+ isActive: z.boolean(),
+ /** datetime-local value ("YYYY-MM-DDTHH:mm") in the browser's time zone, or ''. */
+ startsAt: z.string(),
+ endsAt: z.string(),
+ })
+ .superRefine((v, ctx) => {
+ if (v.position === 'bottom' && v.title === '') {
+ ctx.addIssue({ code: 'custom', path: ['title'], message: 'Title is required' });
+ }
+ const maxText = bannerTextMaxLength(v.position);
+ if (v.text.length > maxText) {
+ ctx.addIssue({ code: 'custom', path: ['text'], message: `Text must be ${maxText} characters or fewer` });
+ }
+ const hasLabel = v.linkLabel !== '';
+ const hasUrl = v.linkUrl !== '';
+ if (hasLabel !== hasUrl) {
+ ctx.addIssue({
+ code: 'custom',
+ path: [hasUrl ? 'linkLabel' : 'linkUrl'],
+ message: 'Button text and link must be given together',
+ });
+ } else if (hasUrl && !isAllowedBannerLink(v.linkUrl)) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['linkUrl'],
+ message: 'Link must start with https:// or be a path starting with /',
+ });
+ }
+ if (v.startsAt && v.endsAt && new Date(v.endsAt).getTime() <= new Date(v.startsAt).getTime()) {
+ ctx.addIssue({ code: 'custom', path: ['endsAt'], message: 'End must be after start' });
+ }
+ });
+
+export type OfferingBannerFormData = z.infer;
+
+const pad = (n: number) => String(n).padStart(2, '0');
+
+/** ISO (UTC) → value for in the browser's time zone. */
+export function toLocalInput(iso: string | null): string {
+ if (!iso) return '';
+ const d = new Date(iso);
+ if (Number.isNaN(d.getTime())) return '';
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
+}
+
+/** datetime-local value → ISO (UTC), '' → null. */
+export function fromLocalInput(value: string): string | null {
+ if (!value) return null;
+ const d = new Date(value);
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
+}
+
+export type BannerStatus = 'off' | 'scheduled' | 'expired' | 'live';
+
+export function bannerStatus(b: { isActive: boolean; startsAt: string | null; endsAt: string | null }, now = new Date()): BannerStatus {
+ if (!b.isActive) return 'off';
+ if (b.startsAt && new Date(b.startsAt) > now) return 'scheduled';
+ if (b.endsAt && new Date(b.endsAt) <= now) return 'expired';
+ return 'live';
+}
+
+/** Same rule for packages: switched on, started and not yet ended. */
+export const scheduleStatus = (
+ b: { isActive: boolean; startsAt: string | null; endsAt: string | null },
+ now = new Date(),
+) => bannerStatus(b, now);
diff --git a/frontend/src/features/offerings/services/types.ts b/frontend/src/features/offerings/services/types.ts
index 00daed0..fcce514 100644
--- a/frontend/src/features/offerings/services/types.ts
+++ b/frontend/src/features/offerings/services/types.ts
@@ -1,4 +1,4 @@
-export interface OfferingAdminDto {
+export interface OfferingDto {
id: string;
slug: string;
title: string;
@@ -9,6 +9,16 @@ export interface OfferingAdminDto {
ctaLabel: string;
featured: boolean;
displayOrder: number;
+ /** Id of the category, or null/absent when the offering has none. */
+ categoryId?: string | null;
+ /** Name of the category (renames show up here automatically). */
+ category?: string | null;
+ /** Switched on. A switched-off offering is never shown on the website. */
+ isActive: boolean;
+ /** ISO date-time (UTC) or null = no start limit. */
+ startsAt: string | null;
+ /** ISO date-time (UTC) or null = no end limit. */
+ endsAt: string | null;
}
export interface CreateOfferingRequest {
@@ -21,8 +31,48 @@ export interface CreateOfferingRequest {
featured: boolean;
/** Omit to auto-generate from title; set to explicitly override. */
slug?: string;
+ /** Category id; null clears the category. */
+ categoryId?: string | null;
+ isActive: boolean;
+ startsAt: string | null;
+ endsAt: string | null;
}
export type UpdateOfferingRequest = CreateOfferingRequest;
+export interface OfferingCategoryDto {
+ id: string;
+ name: string;
+ sortOrder: number;
+ offeringCount: number;
+}
+
export type MoveDirection = 'up' | 'down';
+
+export type BannerPosition = 'top' | 'bottom';
+
+export interface OfferingBannerDto {
+ id: string;
+ position: BannerPosition;
+ title: string;
+ text: string;
+ linkLabel: string | null;
+ linkUrl: string | null;
+ isActive: boolean;
+ /** ISO date-time (UTC) or null = no start limit. */
+ startsAt: string | null;
+ /** ISO date-time (UTC) or null = no end limit. */
+ endsAt: string | null;
+ updatedAt: string;
+}
+
+export interface OfferingBannerRequest {
+ position: BannerPosition;
+ title: string;
+ text: string;
+ linkLabel: string | null;
+ linkUrl: string | null;
+ isActive: boolean;
+ startsAt: string | null;
+ endsAt: string | null;
+}
diff --git a/frontend/src/features/offerings/services/useCreateOffering.ts b/frontend/src/features/offerings/services/useCreateOffering.ts
index 722cf64..049557a 100644
--- a/frontend/src/features/offerings/services/useCreateOffering.ts
+++ b/frontend/src/features/offerings/services/useCreateOffering.ts
@@ -1,15 +1,15 @@
import { useMutation, useQueryClient, type UseMutationOptions } from '@tanstack/react-query';
import { api } from '@/lib/api-client';
-import type { CreateOfferingRequest, OfferingAdminDto } from './types';
+import type { CreateOfferingRequest, OfferingDto } from './types';
export function useCreateOffering(
- options?: Pick, 'onSuccess' | 'onError'>,
+ options?: Pick, 'onSuccess' | 'onError'>,
) {
const queryClient = useQueryClient();
- return useMutation({
- mutationFn: (data) => api.post('/api/v1/offerings/admin', data),
+ return useMutation({
+ mutationFn: (data) => api.post('/api/v1/offerings', data),
onSuccess: (data, variables, ...rest) => {
- queryClient.invalidateQueries({ queryKey: ['offerings', 'admin'] });
+ queryClient.invalidateQueries({ queryKey: ['offerings', 'list'] });
options?.onSuccess?.(data, variables, ...rest);
},
onError: options?.onError,
diff --git a/frontend/src/features/offerings/services/useCreateOfferingCategory.ts b/frontend/src/features/offerings/services/useCreateOfferingCategory.ts
new file mode 100644
index 0000000..7a286e5
--- /dev/null
+++ b/frontend/src/features/offerings/services/useCreateOfferingCategory.ts
@@ -0,0 +1,15 @@
+import { useMutation, useQueryClient } from '@tanstack/react-query';
+import { api } from '@/lib/api-client';
+import { OFFERING_CATEGORIES_KEY } from './useOfferingCategories';
+import type { OfferingCategoryDto } from './types';
+
+export function useCreateOfferingCategory() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (name) =>
+ api.post('/api/v1/offerings/categories', { name }),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: OFFERING_CATEGORIES_KEY });
+ },
+ });
+}
diff --git a/frontend/src/features/offerings/services/useDeleteOffering.ts b/frontend/src/features/offerings/services/useDeleteOffering.ts
index c3001be..10d92d2 100644
--- a/frontend/src/features/offerings/services/useDeleteOffering.ts
+++ b/frontend/src/features/offerings/services/useDeleteOffering.ts
@@ -6,9 +6,9 @@ export function useDeleteOffering(
) {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: (id) => api.delete(`/api/v1/offerings/admin/${id}`),
+ mutationFn: (id) => api.delete(`/api/v1/offerings/${id}`),
onSuccess: (data, variables, ...rest) => {
- queryClient.invalidateQueries({ queryKey: ['offerings', 'admin'] });
+ queryClient.invalidateQueries({ queryKey: ['offerings', 'list'] });
options?.onSuccess?.(data, variables, ...rest);
},
onError: options?.onError,
diff --git a/frontend/src/features/offerings/services/useDeleteOfferingBanner.ts b/frontend/src/features/offerings/services/useDeleteOfferingBanner.ts
new file mode 100644
index 0000000..3f15462
--- /dev/null
+++ b/frontend/src/features/offerings/services/useDeleteOfferingBanner.ts
@@ -0,0 +1,13 @@
+import { useMutation, useQueryClient } from '@tanstack/react-query';
+import { api } from '@/lib/api-client';
+import { OFFERING_BANNERS_KEY } from './useOfferingBanners';
+
+export function useDeleteOfferingBanner() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (id) => api.delete(`/api/v1/offerings/banners/${id}`),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: OFFERING_BANNERS_KEY });
+ },
+ });
+}
diff --git a/frontend/src/features/offerings/services/useDeleteOfferingCategory.ts b/frontend/src/features/offerings/services/useDeleteOfferingCategory.ts
new file mode 100644
index 0000000..9d81c42
--- /dev/null
+++ b/frontend/src/features/offerings/services/useDeleteOfferingCategory.ts
@@ -0,0 +1,14 @@
+import { useMutation, useQueryClient } from '@tanstack/react-query';
+import { api } from '@/lib/api-client';
+import { OFFERING_CATEGORIES_KEY } from './useOfferingCategories';
+
+export function useDeleteOfferingCategory() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (id) => api.delete(`/api/v1/offerings/categories/${id}`),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: OFFERING_CATEGORIES_KEY });
+ queryClient.invalidateQueries({ queryKey: ['offerings', 'list'] });
+ },
+ });
+}
diff --git a/frontend/src/features/offerings/services/useMoveOffering.ts b/frontend/src/features/offerings/services/useMoveOffering.ts
index eb73568..642c4a5 100644
--- a/frontend/src/features/offerings/services/useMoveOffering.ts
+++ b/frontend/src/features/offerings/services/useMoveOffering.ts
@@ -1,16 +1,32 @@
import { useMutation, useQueryClient, type UseMutationOptions } from '@tanstack/react-query';
import { api } from '@/lib/api-client';
-import type { MoveDirection } from './types';
+import type { MoveDirection, OfferingDto } from './types';
+const OFFERINGS_KEY = ['offerings', 'list'];
+
+/**
+ * Moves one offering a step up or down. The API has no move endpoint (the collection is reordered
+ * as a whole via `PUT /api/v1/offerings/order`), so the new order is computed from the cached list.
+ * Moving past either end is a no-op.
+ */
export function useMoveOffering(
direction: MoveDirection,
options?: Pick, 'onSuccess' | 'onError'>,
) {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: (id) => api.post(`/api/v1/offerings/admin/${id}/move-${direction}`),
+ mutationFn: async (id) => {
+ const offerings = queryClient.getQueryData(OFFERINGS_KEY) ?? [];
+ const ids = [...offerings].sort((a, b) => a.displayOrder - b.displayOrder).map((o) => o.id);
+ const index = ids.indexOf(id);
+ const target = direction === 'up' ? index - 1 : index + 1;
+ if (index === -1 || target < 0 || target >= ids.length) return;
+
+ [ids[index], ids[target]] = [ids[target], ids[index]];
+ await api.put('/api/v1/offerings/order', { orderedIds: ids });
+ },
onSuccess: (data, variables, ...rest) => {
- queryClient.invalidateQueries({ queryKey: ['offerings', 'admin'] });
+ queryClient.invalidateQueries({ queryKey: OFFERINGS_KEY });
options?.onSuccess?.(data, variables, ...rest);
},
onError: options?.onError,
diff --git a/frontend/src/features/offerings/services/useOfferingBanners.ts b/frontend/src/features/offerings/services/useOfferingBanners.ts
new file mode 100644
index 0000000..4428c42
--- /dev/null
+++ b/frontend/src/features/offerings/services/useOfferingBanners.ts
@@ -0,0 +1,12 @@
+import { useQuery } from '@tanstack/react-query';
+import { api } from '@/lib/api-client';
+import type { OfferingBannerDto } from './types';
+
+export const OFFERING_BANNERS_KEY = ['offerings', 'banners'];
+
+export function useOfferingBanners() {
+ return useQuery({
+ queryKey: OFFERING_BANNERS_KEY,
+ queryFn: () => api.get('/api/v1/offerings/banners'),
+ });
+}
diff --git a/frontend/src/features/offerings/services/useOfferingCategories.ts b/frontend/src/features/offerings/services/useOfferingCategories.ts
new file mode 100644
index 0000000..1194542
--- /dev/null
+++ b/frontend/src/features/offerings/services/useOfferingCategories.ts
@@ -0,0 +1,12 @@
+import { useQuery } from '@tanstack/react-query';
+import { api } from '@/lib/api-client';
+import type { OfferingCategoryDto } from './types';
+
+export const OFFERING_CATEGORIES_KEY = ['offerings', 'categories'];
+
+export function useOfferingCategories() {
+ return useQuery({
+ queryKey: OFFERING_CATEGORIES_KEY,
+ queryFn: () => api.get('/api/v1/offerings/categories'),
+ });
+}
diff --git a/frontend/src/features/offerings/services/useOfferings.ts b/frontend/src/features/offerings/services/useOfferings.ts
index 73de56b..fb7b445 100644
--- a/frontend/src/features/offerings/services/useOfferings.ts
+++ b/frontend/src/features/offerings/services/useOfferings.ts
@@ -1,10 +1,10 @@
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api-client';
-import type { OfferingAdminDto } from './types';
+import type { OfferingDto } from './types';
export function useOfferings() {
- return useQuery({
- queryKey: ['offerings', 'admin'],
- queryFn: () => api.get('/api/v1/offerings/admin'),
+ return useQuery({
+ queryKey: ['offerings', 'list'],
+ queryFn: () => api.get('/api/v1/offerings/all'),
});
}
diff --git a/frontend/src/features/offerings/services/useRenameOfferingCategory.ts b/frontend/src/features/offerings/services/useRenameOfferingCategory.ts
new file mode 100644
index 0000000..66d3b4c
--- /dev/null
+++ b/frontend/src/features/offerings/services/useRenameOfferingCategory.ts
@@ -0,0 +1,19 @@
+import { useMutation, useQueryClient } from '@tanstack/react-query';
+import { api } from '@/lib/api-client';
+import { OFFERING_CATEGORIES_KEY } from './useOfferingCategories';
+import type { OfferingCategoryDto } from './types';
+
+type RenameVariables = { id: string; name: string };
+
+export function useRenameOfferingCategory() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: ({ id, name }) =>
+ api.put(`/api/v1/offerings/categories/${id}`, { name }),
+ onSuccess: () => {
+ // The category name is part of every offering that uses it, so refresh both lists.
+ queryClient.invalidateQueries({ queryKey: OFFERING_CATEGORIES_KEY });
+ queryClient.invalidateQueries({ queryKey: ['offerings', 'list'] });
+ },
+ });
+}
diff --git a/frontend/src/features/offerings/services/useReorderOfferings.ts b/frontend/src/features/offerings/services/useReorderOfferings.ts
index 0343e19..fa9d473 100644
--- a/frontend/src/features/offerings/services/useReorderOfferings.ts
+++ b/frontend/src/features/offerings/services/useReorderOfferings.ts
@@ -6,9 +6,9 @@ export function useReorderOfferings(
) {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: (orderedIds) => api.put('/api/v1/offerings/admin/reorder', { orderedIds }),
+ mutationFn: (orderedIds) => api.put('/api/v1/offerings/order', { orderedIds }),
onSuccess: (data, variables, ...rest) => {
- queryClient.invalidateQueries({ queryKey: ['offerings', 'admin'] });
+ queryClient.invalidateQueries({ queryKey: ['offerings', 'list'] });
options?.onSuccess?.(data, variables, ...rest);
},
onError: options?.onError,
diff --git a/frontend/src/features/offerings/services/useSaveOfferingBanner.ts b/frontend/src/features/offerings/services/useSaveOfferingBanner.ts
new file mode 100644
index 0000000..e8065b0
--- /dev/null
+++ b/frontend/src/features/offerings/services/useSaveOfferingBanner.ts
@@ -0,0 +1,18 @@
+import { useMutation, useQueryClient } from '@tanstack/react-query';
+import { api } from '@/lib/api-client';
+import { OFFERING_BANNERS_KEY } from './useOfferingBanners';
+import type { OfferingBannerDto, OfferingBannerRequest } from './types';
+
+/** Creates a banner, or replaces it when an id is given. */
+export function useSaveOfferingBanner() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: ({ id, body }) =>
+ id
+ ? api.put(`/api/v1/offerings/banners/${id}`, body)
+ : api.post('/api/v1/offerings/banners', body),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: OFFERING_BANNERS_KEY });
+ },
+ });
+}
diff --git a/frontend/src/features/offerings/services/useUpdateOffering.ts b/frontend/src/features/offerings/services/useUpdateOffering.ts
index 5f1b1f3..28690b5 100644
--- a/frontend/src/features/offerings/services/useUpdateOffering.ts
+++ b/frontend/src/features/offerings/services/useUpdateOffering.ts
@@ -1,17 +1,17 @@
import { useMutation, useQueryClient, type UseMutationOptions } from '@tanstack/react-query';
import { api } from '@/lib/api-client';
-import type { OfferingAdminDto, UpdateOfferingRequest } from './types';
+import type { OfferingDto, UpdateOfferingRequest } from './types';
type UpdateVariables = { id: string } & UpdateOfferingRequest;
export function useUpdateOffering(
- options?: Pick, 'onSuccess' | 'onError'>,
+ options?: Pick, 'onSuccess' | 'onError'>,
) {
const queryClient = useQueryClient();
- return useMutation({
- mutationFn: ({ id, ...body }) => api.put(`/api/v1/offerings/admin/${id}`, body),
+ return useMutation({
+ mutationFn: ({ id, ...body }) => api.put(`/api/v1/offerings/${id}`, body),
onSuccess: (data, variables, ...rest) => {
- queryClient.invalidateQueries({ queryKey: ['offerings', 'admin'] });
+ queryClient.invalidateQueries({ queryKey: ['offerings', 'list'] });
options?.onSuccess?.(data, variables, ...rest);
},
onError: options?.onError,
diff --git a/frontend/src/features/settings/pages/SettingsPage.test.tsx b/frontend/src/features/settings/pages/SettingsPage.test.tsx
index 960c179..3941579 100644
--- a/frontend/src/features/settings/pages/SettingsPage.test.tsx
+++ b/frontend/src/features/settings/pages/SettingsPage.test.tsx
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, it } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
@@ -60,6 +60,37 @@ describe('SettingsPage', () => {
expect(maintenanceBtn.className).toContain('bg-primary');
});
+ it('changes the status with PUT on the status resource (no admin route), sending the chosen status', async () => {
+ let sent: { method: string; url: string; body: { newStatus: string } } | undefined;
+ server.use(
+ http.put(`${API_BASE}/api/v1/Availability/status`, async ({ request }) => {
+ sent = {
+ method: request.method,
+ url: new URL(request.url).pathname,
+ body: (await request.json()) as { newStatus: string },
+ };
+ return HttpResponse.json({
+ status: 'Maintenance',
+ checkedAt: new Date().toISOString(),
+ message: '',
+ isMasterControlled: false,
+ });
+ }),
+ );
+ mockAuthenticated();
+ renderApp('/settings');
+
+ await screen.findByTestId('availability-mode-selector', {}, { timeout: 10000 });
+ await userEvent.click(screen.getByTestId('mode-option-Maintenance'));
+ await userEvent.click(screen.getByTestId('availability-save-button'));
+
+ await vi.waitFor(() => expect(sent).toBeDefined());
+ expect(sent!.method).toBe('PUT');
+ expect(sent!.url).toBe('/api/v1/Availability/status');
+ expect(sent!.url).not.toContain('admin');
+ expect(sent!.body.newStatus).toBe('Maintenance');
+ });
+
it('saves availability and shows success toast', async () => {
mockAuthenticated();
renderApp('/settings');
@@ -72,7 +103,7 @@ describe('SettingsPage', () => {
it('shows error toast when save fails', async () => {
server.use(
- http.post(`${API_BASE}/api/v1/Availability/admin/status`, () =>
+ http.put(`${API_BASE}/api/v1/Availability/status`, () =>
HttpResponse.json({ title: 'Error' }, { status: 500 }),
),
);
@@ -118,7 +149,7 @@ describe('SettingsPage', () => {
it('shows a master-controlled error toast on a 409 conflict from the server', async () => {
server.use(
- http.post(`${API_BASE}/api/v1/Availability/admin/status`, () =>
+ http.put(`${API_BASE}/api/v1/Availability/status`, () =>
HttpResponse.json({ title: 'Conflict' }, { status: 409 }),
),
);
diff --git a/frontend/src/hooks/useTheme.test.ts b/frontend/src/hooks/useTheme.test.ts
index 273279c..dfa1956 100644
--- a/frontend/src/hooks/useTheme.test.ts
+++ b/frontend/src/hooks/useTheme.test.ts
@@ -48,3 +48,57 @@ describe('useTheme', () => {
expect(document.documentElement.classList.contains('light')).toBe(true);
});
});
+
+describe('first click', () => {
+ const media = (dark: boolean) => vi.spyOn(window, 'matchMedia').mockReturnValue({ matches: dark } as MediaQueryList);
+ const shown = () => (document.documentElement.classList.contains('dark') ? 'dark' : 'light');
+
+ it.each([
+ ['light', 'dark'],
+ ['dark', 'light'],
+ ])('flips the shown theme straight away when the OS prefers %s and nothing is stored or applied', (os, expected) => {
+ media(os === 'dark');
+ const { result } = renderHook(() => useTheme());
+
+ expect(shown()).toBe(os);
+ act(() => { result.current.toggleTheme(); });
+
+ expect(shown()).toBe(expected);
+ expect(result.current.theme).toBe(expected);
+ });
+
+ it('flips from what is shown even when the stored value is unusable', () => {
+ localStorage.setItem('cms-theme', 'system');
+ media(true);
+ document.documentElement.className = 'system';
+ const { result } = renderHook(() => useTheme());
+
+ expect(shown()).toBe('dark');
+ act(() => { result.current.toggleTheme(); });
+ expect(shown()).toBe('light');
+ });
+
+ it('follows the shown theme when it differs from the stored one', () => {
+ localStorage.setItem('cms-theme', 'light');
+ document.documentElement.className = 'dark';
+ const { result } = renderHook(() => useTheme());
+
+ expect(result.current.theme).toBe('dark');
+ act(() => { result.current.toggleTheme(); });
+ expect(shown()).toBe('light');
+ expect(localStorage.getItem('cms-theme')).toBe('light');
+ });
+
+ it('keeps two toggles on the page in step', () => {
+ localStorage.setItem('cms-theme', 'light');
+ const a = renderHook(() => useTheme());
+ const b = renderHook(() => useTheme());
+
+ act(() => { a.result.current.toggleTheme(); });
+ expect(b.result.current.theme).toBe('dark');
+
+ act(() => { b.result.current.toggleTheme(); });
+ expect(shown()).toBe('light');
+ expect(a.result.current.theme).toBe('light');
+ });
+});
diff --git a/frontend/src/hooks/useTheme.ts b/frontend/src/hooks/useTheme.ts
index 3ba325c..2309e51 100644
--- a/frontend/src/hooks/useTheme.ts
+++ b/frontend/src/hooks/useTheme.ts
@@ -1,26 +1,62 @@
-import { useState, useCallback } from 'react';
+import { useCallback, useSyncExternalStore } from 'react';
type Theme = 'light' | 'dark';
const STORAGE_KEY = 'cms-theme';
-function getInitialTheme(): Theme {
+const listeners = new Set<() => void>();
+
+function isTheme(value: string | null): value is Theme {
+ return value === 'light' || value === 'dark';
+}
+
+function preferredTheme(): Theme {
const stored = localStorage.getItem(STORAGE_KEY);
- if (stored === 'light' || stored === 'dark') return stored;
+ if (isTheme(stored)) return stored;
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
+function apply(theme: Theme) {
+ document.documentElement.classList.remove('light', 'dark');
+ document.documentElement.classList.add(theme);
+}
+
+/**
+ * The theme that is actually shown, which is what the class says: the stylesheet only
+ * knows that class. The stored value and the OS preference are only the way to pick a theme when
+ * the page carries none (or an unusable one); in that case it is applied right away, so the state
+ * we report and what the user sees can never differ. A first click then always flips what is shown.
+ */
+function currentTheme(): Theme {
+ const classes = document.documentElement.classList;
+ if (classes.contains('dark')) return 'dark';
+ if (classes.contains('light')) return 'light';
+
+ const theme = preferredTheme();
+ apply(theme);
+ return theme;
+}
+
+function subscribe(listener: () => void) {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
export function useTheme() {
- const [theme, setTheme] = useState(getInitialTheme);
+ // One source of truth shared by every toggle on the page (desktop sidebar, mobile overlay).
+ const theme = useSyncExternalStore(subscribe, currentTheme, () => 'light' as Theme);
const toggleTheme = useCallback(() => {
- setTheme((current) => {
- const next: Theme = current === 'dark' ? 'light' : 'dark';
+ const next: Theme = currentTheme() === 'dark' ? 'light' : 'dark';
+ try {
localStorage.setItem(STORAGE_KEY, next);
- document.documentElement.classList.remove('light', 'dark');
- document.documentElement.classList.add(next);
- return next;
- });
+ } catch {
+ // Storage can be unavailable (private mode); the switch itself still works.
+ }
+ apply(next);
+ listeners.forEach((notify) => notify());
}, []);
return { theme, isDark: theme === 'dark', toggleTheme };
diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json
index 98db0ae..f547247 100644
--- a/frontend/src/i18n/locales/en/translation.json
+++ b/frontend/src/i18n/locales/en/translation.json
@@ -11,6 +11,7 @@
"users": "Users",
"cms": "CMS",
"offerings": "Offerings",
+ "messages": "Messages",
"profile": "Profile",
"settings": "Settings",
"openMenu": "Open navigation",
@@ -323,6 +324,72 @@
"offerings": {
"title": "Offerings",
"addButton": "Add Offering",
+ "banners": {
+ "intro": "A banner is a wide announcement or promotion on the website. Plan ahead with a start and end time. At most one banner is shown per location (top and bottom) at any time: the most recently changed active one.",
+ "position": {
+ "label": "Location",
+ "top": "Top",
+ "bottom": "Bottom"
+ },
+ "shownBadge": "Live",
+ "notShownBadge": "Not shown",
+ "notShownHint": "Not shown: a newer banner at this location",
+ "turnOffButton": "Turn banner off",
+ "turnOnButton": "Turn banner on",
+ "titleLabelOptional": "Title (optional)",
+ "textTooLong": "The text is {{length}} characters; this location allows at most {{max}}. Shorten the text or pick another location.",
+ "textHintTop": "One short line, up to 120 characters.",
+ "addButton": "Add banner",
+ "empty": "No banners yet.",
+ "editButton": "Edit banner",
+ "deleteButton": "Delete banner",
+ "createTitle": "New banner",
+ "editTitle": "Edit banner",
+ "titleLabel": "Title",
+ "textLabel": "Text",
+ "linkLabelLabel": "Button text (optional)",
+ "linkUrlLabel": "Link (optional)",
+ "linkHint": "Button text and link go together. A link starts with https:// or is a path on the site, for example /privacy.",
+ "startsLabel": "Visible from (optional)",
+ "endsLabel": "Visible until (optional)",
+ "scheduleHint": "Times are in your time zone. On Andrea's website the schedule applies at the next (nightly) build.",
+ "activeLabel": "Enabled",
+ "savedToast": "Banner saved",
+ "deletedToast": "Banner deleted",
+ "deleteTitle": "Delete banner",
+ "deleteMessage": "Are you sure you want to delete the banner \"{{title}}\"?",
+ "deleteConfirm": "Delete",
+ "status": {
+ "live": "Active",
+ "scheduled": "Scheduled",
+ "expired": "Expired",
+ "off": "Off"
+ },
+ "tabPackages": "Offerings",
+ "tabBanner": "Banner",
+ "tabsLabel": "Sections"
+ },
+ "categories": {
+ "manageButton": "Manage categories",
+ "title": "Manage categories",
+ "emptyState": "No categories yet. Add the first one.",
+ "offeringCount_one": "{{count}} offering",
+ "offeringCount_other": "{{count}} offerings",
+ "newLabel": "New category",
+ "addButton": "Add",
+ "editButton": "Rename category",
+ "confirmEditButton": "Confirm name",
+ "cancelButton": "Cancel",
+ "deleteButton": "Delete category",
+ "deleteConfirm": "Are you sure?",
+ "deleteConfirmButton": "Delete",
+ "errors": {
+ "nameRequired": "Enter a name.",
+ "nameTooLong": "The name can be at most 100 characters.",
+ "duplicate": "A category named '{{name}}' already exists.",
+ "inUse": "This category is still used by {{count}} offering(s). Move them to another category first."
+ }
+ },
"emptyState": {
"heading": "No offerings yet",
"description": "Add your first offering to get started."
@@ -334,6 +401,8 @@
"actions": "Actions"
},
"actions": {
+ "turnOff": "Switch package off",
+ "turnOn": "Switch package on",
"drag": "Drag to reorder",
"edit": "Edit",
"delete": "Delete",
@@ -351,20 +420,27 @@
"form": {
"createTitle": "New Offering",
"editTitle": "Edit Offering",
+ "activeLabel": "Switched on",
+ "startsLabel": "Visible from (optional)",
+ "endsLabel": "Visible until (optional)",
+ "scheduleHint": "A switched-off or planned package is not shown on the website. Times are in your time zone. On Andrea's website the schedule applies at the next (nightly) build.",
+ "endBeforeStart": "The end must be after the start.",
"titleLabel": "Title",
"slugLabel": "Slug",
"slugAutoHint": "Auto-generated from the title",
"editSlugButton": "Edit",
"confirmSlugButton": "Confirm slug",
"cancelSlugEditButton": "Cancel slug edit",
- "descriptionLabel": "Description",
+ "descriptionLabel": "Description (optional)",
"priceLabel": "Price",
- "priceNoteLabel": "Price note",
+ "priceNoteLabel": "Price note (optional)",
"featuresLabel": "Features",
"addFeatureButton": "Add feature",
"removeFeatureButton": "Remove",
"ctaLabelLabel": "Button text",
"featuredLabel": "Featured",
+ "categoryLabel": "Category",
+ "noCategory": "No category",
"submitButton": "Save",
"successToast": "Offering saved successfully"
}
@@ -392,5 +468,137 @@
"invalidInvitationToken": "Invalid or expired invitation token.",
"featureUnavailableTitle": "Not available on this instance",
"featureUnavailable": "This feature is only available on a Master CMS instance."
+ },
+ "contact": {
+ "title": "Messages",
+ "switch": {
+ "title": "Contact form on the website",
+ "stateOn": "The form is on: visitors can send you a message.",
+ "stateOff": "The form is off: visitors only see your e-mail address.",
+ "on": "On",
+ "off": "Off",
+ "turnOn": "Turn on",
+ "turnOff": "Turn off",
+ "nowOn": "The contact form is now on.",
+ "nowOff": "The contact form is now off.",
+ "shortLabel": "Contact form on/off",
+ "explanation": "While the form is off, visitors only see your e-mail address. Turning it off helps against spam or during maintenance.",
+ "firstTimeHint": "The form stays closed until you turn it on.",
+ "hostOff": "The form is switched off at server level.",
+ "noRecipientBanner": "No recipient address is set: messages are kept but not mailed. Enter an address below."
+ },
+ "filter": {
+ "label": "Filter messages",
+ "inbox": "Inbox",
+ "new": "New",
+ "read": "Read",
+ "archived": "Archived",
+ "spam": "Spam"
+ },
+ "table": {
+ "received": "Received",
+ "name": "Name",
+ "email": "E-mail address",
+ "subject": "Subject",
+ "status": "Status",
+ "mail": "Mail"
+ },
+ "status": {
+ "new": "New",
+ "read": "Read",
+ "archived": "Archived",
+ "spam": "Spam",
+ "converted": "Converted"
+ },
+ "mailStatus": {
+ "pending": "Mail waiting to be sent",
+ "sent": "Mail sent",
+ "failed": "Mail failed",
+ "notApplicable": "No mail applicable"
+ },
+ "empty": {
+ "inbox": "No messages yet.",
+ "new": "No new messages.",
+ "read": "No read messages.",
+ "archived": "No archived messages.",
+ "spam": "No spam."
+ },
+ "pager": {
+ "range": "{{from}}–{{to}} of {{total}}",
+ "previous": "Previous",
+ "next": "Next"
+ },
+ "tabs": {
+ "label": "Messages sections",
+ "messages": "Messages",
+ "settings": "Settings"
+ },
+ "unread": {
+ "label": "Unread"
+ },
+ "tile": {
+ "unread_one": "unread message",
+ "unread_other": "unread messages",
+ "error": "The number of unread messages could not be loaded."
+ },
+ "detail": {
+ "title": "Message",
+ "retention": "Kept until",
+ "attempts": "({{count}} attempts)",
+ "nextAttempt": "Next attempt: {{time}}",
+ "delete": "Delete",
+ "resend": "Send mail again",
+ "archive": "Archive",
+ "restore": "Restore",
+ "markUnread": "Mark as unread",
+ "notSpam": "Not spam"
+ },
+ "resend": {
+ "sent": "Sent.",
+ "notSent": "Not sent (mail is off).",
+ "mailOff": "Mail is off on this site."
+ },
+ "deleteDialog": {
+ "title": "Delete message?",
+ "message": "The message is deleted permanently. This cannot be undone.",
+ "confirm": "Delete"
+ },
+ "errors": {
+ "rateLimited": "Try again in {{seconds}} seconds.",
+ "spamResend": "Mark the message as not spam first.",
+ "notFound": "This message no longer exists."
+ },
+ "mailError": {
+ "disabled": "Mail is off.",
+ "recipient_not_configured": "No recipient is configured.",
+ "not_configured": "Mail is not configured.",
+ "timeout": "The mail server was too slow.",
+ "timeout_connect": "Connecting to the mail server took too long.",
+ "timeout_auth": "Logging in to the mail server took too long.",
+ "timeout_send": "Sending took too long.",
+ "auth_failed": "Logging in to the mail server failed.",
+ "rejected": "The mail server refused the message.",
+ "rejected_sender": "The mail server refused the sender address.",
+ "rejected_recipient": "The mail server refused the recipient.",
+ "tls_failed": "The secure connection to the mail server failed.",
+ "connection_failed": "Cannot reach the mail server.",
+ "unknown": "Unknown error while sending."
+ },
+ "recipient": {
+ "title": "Recipient address for contact messages",
+ "description": "We mail every new message to this address. You can reply to that mail directly: the reply goes to the visitor.",
+ "label": "E-mail address",
+ "placeholder": "name@example.com",
+ "save": "Save",
+ "reset": "Back to the server setting",
+ "saved": "Recipient address saved.",
+ "cleared": "The server setting applies again.",
+ "invalid": "Enter a valid e-mail address.",
+ "source": {
+ "setting": "Messages go to this address.",
+ "config": "No address of your own is set: the server setting applies.",
+ "none": "There is no recipient address yet: messages are kept but not mailed."
+ }
+ }
}
}
diff --git a/frontend/src/i18n/locales/nl/translation.json b/frontend/src/i18n/locales/nl/translation.json
index fa2c9df..4830c87 100644
--- a/frontend/src/i18n/locales/nl/translation.json
+++ b/frontend/src/i18n/locales/nl/translation.json
@@ -11,6 +11,7 @@
"users": "Gebruikers",
"cms": "CMS",
"offerings": "Aanbiedingen",
+ "messages": "Berichten",
"profile": "Profiel",
"settings": "Instellingen",
"openMenu": "Navigatie openen",
@@ -323,6 +324,72 @@
"offerings": {
"title": "Aanbiedingen",
"addButton": "Aanbieding toevoegen",
+ "banners": {
+ "intro": "Een banner is een brede mededeling of actie op de website. Plan vooruit met een begin- en eindtijd. Per locatie (boven en onder) wordt maximaal één banner getoond: de laatst gewijzigde actieve.",
+ "position": {
+ "label": "Locatie",
+ "top": "Boven",
+ "bottom": "Onder"
+ },
+ "shownBadge": "Live",
+ "notShownBadge": "Wordt niet getoond",
+ "notShownHint": "Wordt niet getoond: nieuwere banner op deze locatie",
+ "turnOffButton": "Banner uitzetten",
+ "turnOnButton": "Banner aanzetten",
+ "titleLabelOptional": "Titel (optioneel)",
+ "textTooLong": "De tekst is {{length}} tekens; voor deze locatie zijn maximaal {{max}} tekens toegestaan. Kort de tekst in of kies een andere locatie.",
+ "textHintTop": "Eén korte regel, maximaal 120 tekens.",
+ "addButton": "Banner toevoegen",
+ "empty": "Nog geen banners.",
+ "editButton": "Banner bewerken",
+ "deleteButton": "Banner verwijderen",
+ "createTitle": "Nieuwe banner",
+ "editTitle": "Banner bewerken",
+ "titleLabel": "Titel",
+ "textLabel": "Tekst",
+ "linkLabelLabel": "Knoptekst (optioneel)",
+ "linkUrlLabel": "Link (optioneel)",
+ "linkHint": "Knoptekst en link horen bij elkaar. Een link begint met https:// of is een pad op de site, bijvoorbeeld /privacy.",
+ "startsLabel": "Zichtbaar vanaf (optioneel)",
+ "endsLabel": "Zichtbaar tot (optioneel)",
+ "scheduleHint": "Tijden gelden in jouw tijdzone. Bij de website van Andrea geldt de planning bij de eerstvolgende (nachtelijke) build.",
+ "activeLabel": "Ingeschakeld",
+ "savedToast": "Banner opgeslagen",
+ "deletedToast": "Banner verwijderd",
+ "deleteTitle": "Banner verwijderen",
+ "deleteMessage": "Weet je zeker dat je de banner \"{{title}}\" wilt verwijderen?",
+ "deleteConfirm": "Verwijderen",
+ "status": {
+ "live": "Actief",
+ "scheduled": "Gepland",
+ "expired": "Verlopen",
+ "off": "Uit"
+ },
+ "tabPackages": "Aanbiedingen",
+ "tabBanner": "Banner",
+ "tabsLabel": "Onderdelen"
+ },
+ "categories": {
+ "manageButton": "Categorieën beheren",
+ "title": "Categorieën beheren",
+ "emptyState": "Nog geen categorieën. Voeg de eerste toe.",
+ "offeringCount_one": "{{count}} aanbieding",
+ "offeringCount_other": "{{count}} aanbiedingen",
+ "newLabel": "Nieuwe categorie",
+ "addButton": "Toevoegen",
+ "editButton": "Categorie hernoemen",
+ "confirmEditButton": "Naam bevestigen",
+ "cancelButton": "Annuleren",
+ "deleteButton": "Categorie verwijderen",
+ "deleteConfirm": "Weet je het zeker?",
+ "deleteConfirmButton": "Verwijderen",
+ "errors": {
+ "nameRequired": "Vul een naam in.",
+ "nameTooLong": "De naam mag maximaal 100 tekens bevatten.",
+ "duplicate": "Er bestaat al een categorie met de naam '{{name}}'.",
+ "inUse": "Deze categorie wordt nog gebruikt door {{count}} aanbieding(en). Verplaats die eerst naar een andere categorie."
+ }
+ },
"emptyState": {
"heading": "Nog geen aanbiedingen",
"description": "Voeg je eerste aanbieding toe om te beginnen."
@@ -334,6 +401,8 @@
"actions": "Acties"
},
"actions": {
+ "turnOff": "Pakket uitzetten",
+ "turnOn": "Pakket aanzetten",
"drag": "Sleep om te herordenen",
"edit": "Bewerken",
"delete": "Verwijderen",
@@ -351,20 +420,27 @@
"form": {
"createTitle": "Nieuwe aanbieding",
"editTitle": "Aanbieding bewerken",
+ "activeLabel": "Ingeschakeld",
+ "startsLabel": "Zichtbaar vanaf (optioneel)",
+ "endsLabel": "Zichtbaar tot (optioneel)",
+ "scheduleHint": "Een uitgeschakeld of gepland pakket wordt niet op de website getoond. Tijden gelden in jouw tijdzone. Bij de website van Andrea geldt de planning bij de eerstvolgende (nachtelijke) build.",
+ "endBeforeStart": "Het einde moet na het begin liggen.",
"titleLabel": "Titel",
"slugLabel": "Slug",
"slugAutoHint": "Wordt automatisch gegenereerd uit de titel",
"editSlugButton": "Aanpassen",
"confirmSlugButton": "Slug bevestigen",
"cancelSlugEditButton": "Slug-bewerking annuleren",
- "descriptionLabel": "Beschrijving",
+ "descriptionLabel": "Beschrijving (optioneel)",
"priceLabel": "Prijs",
- "priceNoteLabel": "Prijsnotitie",
+ "priceNoteLabel": "Prijsnotitie (optioneel)",
"featuresLabel": "Kenmerken",
"addFeatureButton": "Kenmerk toevoegen",
"removeFeatureButton": "Verwijderen",
"ctaLabelLabel": "Knoptekst",
"featuredLabel": "Uitgelicht",
+ "categoryLabel": "Categorie",
+ "noCategory": "Geen categorie",
"submitButton": "Opslaan",
"successToast": "Aanbieding succesvol opgeslagen"
}
@@ -392,5 +468,137 @@
"invalidInvitationToken": "Ongeldig of verlopen uitnodigingstoken.",
"featureUnavailableTitle": "Niet beschikbaar op deze instantie",
"featureUnavailable": "Deze functie is alleen beschikbaar op een Master-CMS-instantie."
+ },
+ "contact": {
+ "title": "Berichten",
+ "switch": {
+ "title": "Contactformulier op de website",
+ "stateOn": "Het formulier staat aan: bezoekers kunnen je een bericht sturen.",
+ "stateOff": "Het formulier staat uit: bezoekers zien alleen je e-mailadres.",
+ "on": "Aan",
+ "off": "Uit",
+ "turnOn": "Aanzetten",
+ "turnOff": "Uitzetten",
+ "nowOn": "Het contactformulier staat nu aan.",
+ "nowOff": "Het contactformulier staat nu uit.",
+ "shortLabel": "Contactformulier aan/uit",
+ "explanation": "Als het formulier uit staat, ziet de bezoeker alleen je e-mailadres. Uitzetten helpt bij spam of onderhoud.",
+ "firstTimeHint": "Het formulier is nog gesloten tot je het aanzet.",
+ "hostOff": "Het formulier is op serverniveau uitgeschakeld.",
+ "noRecipientBanner": "Er is geen ontvangstadres ingesteld: berichten worden bewaard maar niet gemaild. Vul hieronder een adres in."
+ },
+ "filter": {
+ "label": "Filter berichten",
+ "inbox": "Inbox",
+ "new": "Nieuw",
+ "read": "Gelezen",
+ "archived": "Gearchiveerd",
+ "spam": "Spam"
+ },
+ "table": {
+ "received": "Ontvangen",
+ "name": "Naam",
+ "email": "E-mailadres",
+ "subject": "Onderwerp",
+ "status": "Status",
+ "mail": "Mail"
+ },
+ "status": {
+ "new": "Nieuw",
+ "read": "Gelezen",
+ "archived": "Gearchiveerd",
+ "spam": "Spam",
+ "converted": "Omgezet"
+ },
+ "mailStatus": {
+ "pending": "Mail wacht op verzending",
+ "sent": "Mail verstuurd",
+ "failed": "Mail mislukt",
+ "notApplicable": "Geen mail van toepassing"
+ },
+ "empty": {
+ "inbox": "Nog geen berichten.",
+ "new": "Geen nieuwe berichten.",
+ "read": "Geen gelezen berichten.",
+ "archived": "Geen gearchiveerde berichten.",
+ "spam": "Geen spam."
+ },
+ "pager": {
+ "range": "{{from}}–{{to}} van {{total}}",
+ "previous": "Vorige",
+ "next": "Volgende"
+ },
+ "tabs": {
+ "label": "Onderdelen van Berichten",
+ "messages": "Berichten",
+ "settings": "Instellingen"
+ },
+ "unread": {
+ "label": "Ongelezen"
+ },
+ "tile": {
+ "unread_one": "ongelezen bericht",
+ "unread_other": "ongelezen berichten",
+ "error": "Het aantal ongelezen berichten kon niet worden opgehaald."
+ },
+ "detail": {
+ "title": "Bericht",
+ "retention": "Bewaard tot",
+ "attempts": "({{count}} pogingen)",
+ "nextAttempt": "Volgende poging: {{time}}",
+ "delete": "Verwijderen",
+ "resend": "Opnieuw mailen",
+ "archive": "Archiveren",
+ "restore": "Terugzetten",
+ "markUnread": "Markeer als ongelezen",
+ "notSpam": "Geen spam"
+ },
+ "resend": {
+ "sent": "Verstuurd.",
+ "notSent": "Niet verstuurd (mail staat uit).",
+ "mailOff": "Mail staat uit op deze site."
+ },
+ "deleteDialog": {
+ "title": "Bericht verwijderen?",
+ "message": "Het bericht wordt definitief verwijderd. Dit kan niet ongedaan worden gemaakt.",
+ "confirm": "Verwijderen"
+ },
+ "errors": {
+ "rateLimited": "Probeer het over {{seconds}} seconden opnieuw.",
+ "spamResend": "Markeer het bericht eerst als geen spam.",
+ "notFound": "Dit bericht bestaat niet meer."
+ },
+ "mailError": {
+ "disabled": "Mail staat uit.",
+ "recipient_not_configured": "Er is geen ontvanger ingesteld.",
+ "not_configured": "Mail is niet ingesteld.",
+ "timeout": "De mailserver reageerde te langzaam.",
+ "timeout_connect": "Verbinden met de mailserver duurde te lang.",
+ "timeout_auth": "Inloggen bij de mailserver duurde te lang.",
+ "timeout_send": "Versturen duurde te lang.",
+ "auth_failed": "Inloggen bij de mailserver is mislukt.",
+ "rejected": "De mailserver weigerde het bericht.",
+ "rejected_sender": "De mailserver weigerde het afzenderadres.",
+ "rejected_recipient": "De mailserver weigerde de ontvanger.",
+ "tls_failed": "De beveiligde verbinding met de mailserver is mislukt.",
+ "connection_failed": "Geen verbinding met de mailserver.",
+ "unknown": "Onbekende fout bij het versturen."
+ },
+ "recipient": {
+ "title": "Ontvangstadres contactberichten",
+ "description": "Hierheen sturen we een mail bij elk nieuw bericht. Je kunt direct op die mail antwoorden: het antwoord gaat naar de bezoeker.",
+ "label": "E-mailadres",
+ "placeholder": "naam@voorbeeld.nl",
+ "save": "Opslaan",
+ "reset": "Terug naar serverinstelling",
+ "saved": "Ontvangstadres opgeslagen.",
+ "cleared": "De serverinstelling geldt weer.",
+ "invalid": "Voer een geldig e-mailadres in.",
+ "source": {
+ "setting": "Berichten gaan naar dit adres.",
+ "config": "Er is geen eigen adres ingesteld: de serverinstelling geldt.",
+ "none": "Er is nog geen ontvangstadres: berichten worden bewaard maar niet gemaild."
+ }
+ }
}
}
diff --git a/frontend/src/lib/api-client.ts b/frontend/src/lib/api-client.ts
index 2522a62..c975018 100644
--- a/frontend/src/lib/api-client.ts
+++ b/frontend/src/lib/api-client.ts
@@ -93,6 +93,10 @@ export class ApiClient {
return this.request(path, { ...options, method: 'PUT', body });
}
+ patch(path: string, body?: unknown, options?: RequestOptions): Promise {
+ return this.request(path, { ...options, method: 'PATCH', body });
+ }
+
delete(path: string, options?: RequestOptions): Promise {
return this.request(path, { ...options, method: 'DELETE' });
}
diff --git a/frontend/src/mocks/index.ts b/frontend/src/mocks/index.ts
index 846d606..213db9f 100644
--- a/frontend/src/mocks/index.ts
+++ b/frontend/src/mocks/index.ts
@@ -6,9 +6,10 @@ import { availabilityHandlers } from '@/features/availability/mocks/handlers';
import { cmsHandlers } from '@/features/cms/mocks/handlers';
import { systemHandlers } from '@/features/system/mocks/handlers';
import { offeringsHandlers } from '@/features/offerings/mocks/handlers';
+import { contactHandlers } from '@/features/contact/mocks/handlers';
/** All default MSW handlers, composed from feature folders (Q3-B). */
-export const handlers = [...authHandlers, ...userHandlers, ...setupHandlers, ...invitationHandlers, ...availabilityHandlers, ...cmsHandlers, ...systemHandlers, ...offeringsHandlers];
+export const handlers = [...authHandlers, ...userHandlers, ...setupHandlers, ...invitationHandlers, ...availabilityHandlers, ...cmsHandlers, ...systemHandlers, ...offeringsHandlers, ...contactHandlers];
export { authHandlers } from '@/features/auth/mocks/handlers';
export { userHandlers } from '@/features/users/mocks/handlers';
@@ -18,4 +19,5 @@ export { availabilityHandlers } from '@/features/availability/mocks/handlers';
export { cmsHandlers, resetMockCmsInstances, getMockCmsInstances } from '@/features/cms/mocks/handlers';
export { systemHandlers } from '@/features/system/mocks/handlers';
export { offeringsHandlers, resetMockOfferings, getMockOfferings } from '@/features/offerings/mocks/handlers';
+export { contactHandlers, resetMockContact, getMockContactMessages } from '@/features/contact/mocks/handlers';
export * from '@/features/auth/mocks/fixtures';
diff --git a/frontend/src/router.tsx b/frontend/src/router.tsx
index 8d89b12..5affa42 100644
--- a/frontend/src/router.tsx
+++ b/frontend/src/router.tsx
@@ -14,6 +14,7 @@ import { LoginPage } from '@/features/auth/pages/LoginPage';
import { NotFoundPage } from '@/pages/NotFoundPage';
import { RoleGuard } from '@/features/auth/components/RoleGuard';
import { ModuleGuard } from '@/features/system/components/ModuleGuard';
+import { ContactAvailabilityGuard } from '@/features/contact/components/ContactAvailabilityGuard';
export interface RouterContext {
auth: AuthContextValue;
@@ -268,6 +269,23 @@ const offeringsEditRoute = createRoute({
),
});
+const messagesRoute = createRoute({
+ getParentRoute: () => authenticatedRoute,
+ path: '/messages',
+ validateSearch: (search: Record): { tab?: 'settings' } => ({
+ tab: search.tab === 'settings' ? 'settings' : undefined,
+ }),
+ component: () => (
+
+
+
+ {lazyPage(() => import('@/features/contact/pages/MessagesPage'), 'MessagesPage')()}
+
+
+
+ ),
+});
+
const settingsRoute = createRoute({
getParentRoute: () => authenticatedRoute,
path: '/settings',
@@ -305,6 +323,7 @@ export const routeTree = rootRoute.addChildren([
offeringsRoute,
offeringsNewRoute,
offeringsEditRoute,
+ messagesRoute,
settingsRoute,
profileRoute,
]),
diff --git a/frontend/themes/resolveTheme.test.ts b/frontend/themes/resolveTheme.test.ts
index 0f5460c..9add60d 100644
--- a/frontend/themes/resolveTheme.test.ts
+++ b/frontend/themes/resolveTheme.test.ts
@@ -50,7 +50,7 @@ describe('resolveTheme', () => {
});
it('lists the available themes', () => {
- expect(availableThemes()).toContain('asf');
+ expect(availableThemes()).toEqual(expect.arrayContaining(['asf', 'slpsoftware']));
});
it.each(['nope', '../asf', 'asf/../asf', '..', 'ASF', 'asf asf'])('rejects %j loudly, naming the real themes', (name) => {
@@ -99,3 +99,35 @@ describe('asf theme tokens', () => {
expect(theme).toContain('@fontsource/marcellus');
});
});
+
+describe('slpsoftware theme', () => {
+ it('resolves stylesheet, favicon, logo pair and e-mail logo', () => {
+ const theme = resolveTheme('slpsoftware');
+
+ expect(theme.css.replaceAll('\\', '/')).toMatch(/themes\/slpsoftware\/theme\.css$/);
+ expect(fs.existsSync(theme.css)).toBe(true);
+ expect(theme.favicon !== null && fs.existsSync(theme.favicon)).toBe(true);
+ expect(theme.logo).not.toBeNull();
+ for (const f of [theme.logo!.onLight, theme.logo!.onDark, theme.logo!.mail!]) {
+ expect(fs.readFileSync(f).subarray(1, 4).toString()).toBe('PNG');
+ }
+ });
+
+ it('self-hosts Archivo and invents no structural token', () => {
+ const css = fs.readFileSync(path.resolve(__dirname, 'slpsoftware/theme.css'), 'utf-8');
+ const base = fs.readFileSync(path.resolve(__dirname, '../src/index.css'), 'utf-8');
+ const names = (src: string, block: string) => {
+ const m = src.match(new RegExp(`${block}\\s*\\{([^}]*)\\}`));
+ return new Set([...(m?.[1] ?? '').matchAll(/(--[a-z-]+)\s*:/g)].map((x) => x[1]));
+ };
+
+ expect(css).not.toMatch(/https?:\/\//);
+ expect(css).toContain('@fontsource/archivo');
+ for (const block of ['\\:root', '\\.dark']) {
+ const existing = names(base, block);
+ const themed = names(css, block);
+ for (const t of existing) expect(themed, `${block} ${t}`).toContain(t);
+ for (const t of themed) if (!existing.has(t)) expect(t).toMatch(/^--(slp-|font-sans$)/);
+ }
+ });
+});
diff --git a/frontend/themes/slpsoftware/contrast.py b/frontend/themes/slpsoftware/contrast.py
new file mode 100644
index 0000000..145510a
--- /dev/null
+++ b/frontend/themes/slpsoftware/contrast.py
@@ -0,0 +1,12 @@
+def lum(h):
+ h=h.lstrip('#'); c=[int(h[i:i+2],16)/255 for i in (0,2,4)]
+ c=[x/12.92 if x<=0.03928 else ((x+0.055)/1.055)**2.4 for x in c]
+ return .2126*c[0]+.7152*c[1]+.0722*c[2]
+def cr(a,b):
+ la,lb=sorted([lum(a),lum(b)],reverse=True); return (la+.05)/(lb+.05)
+L=dict(bg='#ffffff',fg='#1a1a1a',card='#f7f7f7',primary='#7a1414',pf='#ffffff',muted='#f4f4f5',mfg='#5c5c5c',accent='#f6e9e9',afg='#7a1414',destr='#c62828',dfg='#ffffff',ring='#7a1414')
+D=dict(bg='#141414',fg='#f5f5f5',card='#1e1e1e',primary='#e0646c',pf='#141414',muted='#2a2a2a',mfg='#b0b0b0',accent='#3a1f21',afg='#f0a0a6',destr='#ff7b72',dfg='#141414',ring='#e0646c')
+for n,t in (('light',L),('dark',D)):
+ print(n)
+ for lab,a,b,m in [('foreground/background','fg','bg',4.5),('card-foreground/card','fg','card',4.5),('primary-foreground/primary','pf','primary',4.5),('primary(link)/background','primary','bg',4.5),('primary/card','primary','card',4.5),('muted-foreground/background','mfg','bg',4.5),('muted-foreground/card','mfg','card',4.5),('muted-foreground/muted','mfg','muted',4.5),('accent-foreground/accent','afg','accent',4.5),('destructive-foreground/destructive','dfg','destr',4.5),('destructive/background','destr','bg',4.5),('ring/background','ring','bg',3),('ring/card','ring','card',3)]:
+ r=cr(t[a],t[b]); print(f' {lab:38s}{r:6.2f} {"OK" if r>=m else "FAIL"} (min {m})')
diff --git a/frontend/themes/slpsoftware/favicon.png b/frontend/themes/slpsoftware/favicon.png
new file mode 100644
index 0000000..d42a8c7
Binary files /dev/null and b/frontend/themes/slpsoftware/favicon.png differ
diff --git a/frontend/themes/slpsoftware/logo-mail.png b/frontend/themes/slpsoftware/logo-mail.png
new file mode 100644
index 0000000..a07d622
Binary files /dev/null and b/frontend/themes/slpsoftware/logo-mail.png differ
diff --git a/frontend/themes/slpsoftware/logo-on-dark.png b/frontend/themes/slpsoftware/logo-on-dark.png
new file mode 100644
index 0000000..fb55f0b
Binary files /dev/null and b/frontend/themes/slpsoftware/logo-on-dark.png differ
diff --git a/frontend/themes/slpsoftware/logo-on-light.png b/frontend/themes/slpsoftware/logo-on-light.png
new file mode 100644
index 0000000..cef614a
Binary files /dev/null and b/frontend/themes/slpsoftware/logo-on-light.png differ
diff --git a/frontend/themes/slpsoftware/logo.svg b/frontend/themes/slpsoftware/logo.svg
new file mode 100644
index 0000000..325140a
--- /dev/null
+++ b/frontend/themes/slpsoftware/logo.svg
@@ -0,0 +1,8 @@
+
diff --git a/frontend/themes/slpsoftware/make-logo.py b/frontend/themes/slpsoftware/make-logo.py
new file mode 100644
index 0000000..c9fdeaa
--- /dev/null
+++ b/frontend/themes/slpsoftware/make-logo.py
@@ -0,0 +1,100 @@
+"""
+Builds the SLP Software brand logo: logo-on-light.png, logo-on-dark.png, logo-mail.png and logo.svg.
+
+The mark is the text in Archivo ExtraBold; the angle brackets and slash are bordeaux accents,
+"SLP" is ink. Displayed 40 px high in the admin; PNGs are rendered at 3x (about 120 px high).
+
+Needs: pip install pillow fonttools brotli; and `pnpm install` in frontend/ (font comes from @fontsource/archivo).
+Run from this folder: python make-logo.py
+"""
+import io
+import os
+from fontTools.ttLib import TTFont
+from fontTools.pens.svgPathPen import SVGPathPen
+from PIL import Image, ImageDraw, ImageFont
+
+SCALE = 3
+H = 40 * SCALE
+PAD = 2 * SCALE
+FONT_WOFF2 = "../../node_modules/@fontsource/archivo/files/archivo-latin-800-normal.woff2"
+TTF = "archivo-800.tmp.ttf"
+PARTS = [("<", "accent"), ("SLP", "ink"), ("/>", "accent")]
+VARIANTS = {
+ "logo-on-light.png": {"ink": (26, 26, 26), "accent": (122, 20, 20)},
+ "logo-on-dark.png": {"ink": (245, 245, 245), "accent": (224, 100, 108)},
+}
+
+f = TTFont(FONT_WOFF2)
+f.flavor = None
+f.save(TTF)
+
+# Pick the pixel size so that the ink bounding box of the whole text is about H - 2*PAD high.
+size = 100
+probe = ImageFont.truetype(TTF, size)
+text = "".join(p for p, _ in PARTS)
+b = probe.getbbox(text)
+size = round(size * (H - 2 * PAD) / (b[3] - b[1]))
+font = ImageFont.truetype(TTF, size)
+full = font.getbbox(text)
+asc_top, asc_bot = full[1], full[3]
+
+def render(colors):
+ # Draw the parts one after another using advance widths (keeps the font's own kerning-free spacing).
+ width = round(font.getlength(text)) + 2 * PAD + 4
+ img = Image.new("RGBA", (width, 2 * H), (0, 0, 0, 0))
+ d = ImageDraw.Draw(img)
+ x = PAD
+ for part, role in PARTS:
+ d.text((x, PAD - asc_top), part, font=font, fill=colors[role] + (255,))
+ x += font.getlength(part)
+ img = img.crop(img.getchannel("A").getbbox())
+ out = Image.new("RGBA", (img.width + 2 * PAD, img.height + 2 * PAD), (0, 0, 0, 0))
+ out.alpha_composite(img, (PAD, PAD))
+ return out
+
+for name, colors in VARIANTS.items():
+ im = render(colors)
+ im.save(name, optimize=True)
+ print(f"{name} {im.width}x{im.height}")
+
+# logo-mail.png: the light variant on a white rounded badge (same approach as themes/asf/make-mail-logo.py).
+src = Image.open("logo-on-light.png").convert("RGBA")
+src = src.crop(src.getchannel("A").getbbox())
+CONTENT_H, MPAD, RADIUS = 40 * SCALE, 8 * SCALE, 8 * SCALE
+logo = src.resize((round(src.width * CONTENT_H / src.height), CONTENT_H), Image.LANCZOS)
+w, h = logo.width + 2 * MPAD, CONTENT_H + 2 * MPAD
+badge = Image.new("RGBA", (w, h), (0, 0, 0, 0))
+ImageDraw.Draw(badge).rounded_rectangle((0, 0, w - 1, h - 1), radius=RADIUS, fill=(255, 255, 255, 255))
+badge.alpha_composite(logo, (MPAD, MPAD))
+badge.save("logo-mail.png", optimize=True)
+print(f"logo-mail.png {w}x{h}")
+
+# logo.svg: text converted to paths (archive/source; the build uses the PNGs).
+gs = f.getGlyphSet()
+cmap = f.getBestCmap()
+upm = f["head"].unitsPerEm
+hmtx = f["hmtx"]
+paths, x = [], 0
+ymin, ymax = 10**9, -10**9
+from fontTools.pens.boundsPen import BoundsPen
+for part, role in PARTS:
+ for ch in part:
+ g = cmap[ord(ch)]
+ pen = SVGPathPen(gs)
+ gs[g].draw(pen)
+ bp = BoundsPen(gs)
+ gs[g].draw(bp)
+ if bp.bounds:
+ ymin, ymax = min(ymin, bp.bounds[1]), max(ymax, bp.bounds[3])
+ paths.append((pen.getCommands(), x, role))
+ x += hmtx[g][0]
+pad = 20
+vb_h = ymax - ymin + 2 * pad
+fill = {"ink": "#1a1a1a", "accent": "#7a1414"}
+body = "\n".join(
+ f' ' for d, px, r in paths
+)
+svg = f'\n'
+open("logo.svg", "w", encoding="utf-8", newline="\n").write(svg)
+print("logo.svg", len(svg), "bytes")
+os.remove(TTF)
diff --git a/frontend/themes/slpsoftware/theme.css b/frontend/themes/slpsoftware/theme.css
new file mode 100644
index 0000000..a203f29
--- /dev/null
+++ b/frontend/themes/slpsoftware/theme.css
@@ -0,0 +1,110 @@
+/*
+ * Theme "slpsoftware" - SLP Software.
+ *
+ * Re-declares the admin design tokens only (colours, radius, font); no layout or component changes.
+ * Brand: bordeaux #7A1414 (website variant B) as primary/ring/accent basis on a white, neutral surface.
+ * Font: Archivo, self-hosted through @fontsource (the admin CSP is font-src 'self').
+ * Selected at build time with VITE_THEME=slpsoftware.
+ *
+ * Contrast (WCAG 2.x, computed by contrast.py next to this file; AA = 4.5:1 text, 3:1 UI/large):
+ *
+ * Pair Light Dark
+ * foreground / background 17.40 16.90
+ * card-foreground / card 16.25 15.29
+ * primary-foreground / primary 10.84 5.45
+ * primary (links) / background 10.84 5.45
+ * primary / card 10.12 4.93
+ * muted-foreground / background 6.69 8.49
+ * muted-foreground / card 6.24 7.69
+ * muted-foreground / muted 6.08 6.62
+ * accent-foreground / accent 9.16 7.36
+ * destructive-foreground / destructive 5.62 7.31
+ * destructive / background 5.62 7.31
+ * ring / background (min 3.0) 10.84 5.45
+ * ring / card (min 3.0) 10.12 4.93
+ *
+ * All pairs pass AA in both modes. Dark mode has no website counterpart: its primary is a lighter,
+ * derived bordeaux (#e0646c) so button text and links stay above 4.5:1 on the dark surfaces.
+ */
+@import '@fontsource/archivo/latin-400.css';
+@import '@fontsource/archivo/latin-500.css';
+@import '@fontsource/archivo/latin-600.css';
+@import '@fontsource/archivo/latin-700.css';
+
+:root {
+ --slp-bordeaux: #7a1414;
+ --slp-ink: #1a1a1a;
+ --slp-ink-2: #5c5c5c;
+ --slp-surface: #f7f7f7;
+ --slp-tint: #f6e9e9;
+ --slp-error: #c62828;
+ --slp-line: #e4e4e7;
+
+ --slp-font-body: 'Archivo', system-ui, 'Segoe UI', Roboto, sans-serif;
+
+ --background: #ffffff;
+ --foreground: var(--slp-ink);
+
+ --card: var(--slp-surface);
+ --card-foreground: var(--slp-ink);
+
+ --popover: #ffffff;
+ --popover-foreground: var(--slp-ink);
+
+ --primary: var(--slp-bordeaux);
+ --primary-foreground: #ffffff;
+
+ --secondary: #f4f4f5;
+ --secondary-foreground: var(--slp-ink);
+
+ --muted: #f4f4f5;
+ --muted-foreground: var(--slp-ink-2);
+
+ --accent: var(--slp-tint);
+ --accent-foreground: var(--slp-bordeaux);
+
+ --destructive: var(--slp-error);
+ --destructive-foreground: #ffffff;
+
+ --border: var(--slp-line);
+ --input: var(--slp-line);
+ --ring: var(--slp-bordeaux);
+
+ --radius: 0.375rem;
+
+ --font-sans: var(--slp-font-body);
+}
+
+.dark {
+ --background: #141414;
+ --foreground: #f5f5f5;
+
+ --card: #1e1e1e;
+ --card-foreground: #f5f5f5;
+
+ --popover: #1e1e1e;
+ --popover-foreground: #f5f5f5;
+
+ --primary: #e0646c;
+ --primary-foreground: #141414;
+
+ --secondary: #2a2a2a;
+ --secondary-foreground: #f5f5f5;
+
+ --muted: #2a2a2a;
+ --muted-foreground: #b0b0b0;
+
+ --accent: #3a1f21;
+ --accent-foreground: #f0a0a6;
+
+ --destructive: #ff7b72;
+ --destructive-foreground: #141414;
+
+ --border: #333333;
+ --input: #333333;
+ --ring: #e0646c;
+}
+
+body {
+ font-family: var(--slp-font-body);
+}
diff --git a/openapi/slpsoftware.v1.json b/openapi/slpsoftware.v1.json
new file mode 100644
index 0000000..087a0a7
--- /dev/null
+++ b/openapi/slpsoftware.v1.json
@@ -0,0 +1,2722 @@
+{
+ "components": {
+ "responses": {
+ "RateLimited": {
+ "content": {
+ "application/problem+json": {
+ "schema": {
+ "$ref": "#/components/schemas/Problem"
+ }
+ }
+ },
+ "description": "Too many requests. Retry after the number of seconds in the Retry-After header.",
+ "headers": {
+ "Retry-After": {
+ "description": "Seconds to wait before retrying.",
+ "schema": {
+ "format": "int32",
+ "type": "integer"
+ }
+ }
+ }
+ },
+ "TooLarge": {
+ "content": {
+ "application/problem+json": {
+ "schema": {
+ "$ref": "#/components/schemas/Problem"
+ }
+ }
+ },
+ "description": "The request body is too large."
+ },
+ "Validation": {
+ "content": {
+ "application/problem+json": {
+ "schema": {
+ "$ref": "#/components/schemas/ValidationProblem"
+ }
+ }
+ },
+ "description": "Validation failed (also an expired, forged or other-site token as errors.token=[\"expired\"], a missing or non-UUID Idempotency-Key, and an unreadable body as errors.body=[\"invalid\"])."
+ }
+ },
+ "schemas": {
+ "AvailabilityStatus": {
+ "type": "integer"
+ },
+ "ChangePasswordRequest": {
+ "properties": {
+ "currentPassword": {
+ "type": "string"
+ },
+ "newPassword": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "currentPassword",
+ "newPassword"
+ ],
+ "type": "object"
+ },
+ "ChangeRoleRequest": {
+ "properties": {
+ "newRole": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "newRole"
+ ],
+ "type": "object"
+ },
+ "CompleteSetupRequest": {
+ "properties": {
+ "name": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "password": {
+ "type": "string"
+ },
+ "token": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "token",
+ "password"
+ ],
+ "type": "object"
+ },
+ "ContactCaptchaInfo": {
+ "properties": {
+ "apiEndpoint": {
+ "default": "global",
+ "type": "string"
+ },
+ "provider": {
+ "type": "string"
+ },
+ "siteKey": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "provider",
+ "siteKey"
+ ],
+ "type": "object"
+ },
+ "ContactMessageDetail": {
+ "properties": {
+ "email": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "mailAttempts": {
+ "format": "int32",
+ "pattern": "^-?(?:0|[1-9]\\d*)$",
+ "type": [
+ "integer",
+ "string"
+ ]
+ },
+ "mailError": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "mailStatus": {
+ "type": "string"
+ },
+ "message": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "nextMailAttemptAt": {
+ "format": "date-time",
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "receivedAt": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "retentionUntil": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "status": {
+ "type": "string"
+ },
+ "subject": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "receivedAt",
+ "name",
+ "email",
+ "subject",
+ "message",
+ "status",
+ "mailStatus",
+ "mailAttempts",
+ "mailError",
+ "retentionUntil"
+ ],
+ "type": "object"
+ },
+ "ContactMessageList": {
+ "properties": {
+ "items": {
+ "items": {
+ "$ref": "#/components/schemas/ContactMessageListItem"
+ },
+ "type": "array"
+ },
+ "page": {
+ "format": "int32",
+ "pattern": "^-?(?:0|[1-9]\\d*)$",
+ "type": [
+ "integer",
+ "string"
+ ]
+ },
+ "pageSize": {
+ "format": "int32",
+ "pattern": "^-?(?:0|[1-9]\\d*)$",
+ "type": [
+ "integer",
+ "string"
+ ]
+ },
+ "totalCount": {
+ "format": "int32",
+ "pattern": "^-?(?:0|[1-9]\\d*)$",
+ "type": [
+ "integer",
+ "string"
+ ]
+ },
+ "unreadCount": {
+ "format": "int32",
+ "pattern": "^-?(?:0|[1-9]\\d*)$",
+ "type": [
+ "integer",
+ "string"
+ ]
+ }
+ },
+ "required": [
+ "items",
+ "page",
+ "pageSize",
+ "totalCount",
+ "unreadCount"
+ ],
+ "type": "object"
+ },
+ "ContactMessageListItem": {
+ "properties": {
+ "email": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "mailStatus": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "receivedAt": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "status": {
+ "type": "string"
+ },
+ "subject": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "receivedAt",
+ "name",
+ "email",
+ "subject",
+ "status",
+ "mailStatus"
+ ],
+ "type": "object"
+ },
+ "ContactMessageRequest": {
+ "properties": {
+ "captchaToken": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "email": {
+ "maxLength": 254,
+ "type": "string"
+ },
+ "hpCheck": {
+ "maxLength": 0,
+ "type": "string"
+ },
+ "message": {
+ "maxLength": 2000,
+ "type": "string"
+ },
+ "name": {
+ "maxLength": 100,
+ "type": "string"
+ },
+ "subject": {
+ "maxLength": 100,
+ "type": "string"
+ },
+ "token": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "name",
+ "email",
+ "subject",
+ "message",
+ "hpCheck",
+ "token"
+ ],
+ "type": "object"
+ },
+ "ContactResendResult": {
+ "properties": {
+ "mailAttempts": {
+ "format": "int32",
+ "pattern": "^-?(?:0|[1-9]\\d*)$",
+ "type": [
+ "integer",
+ "string"
+ ]
+ },
+ "mailError": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "mailStatus": {
+ "type": "string"
+ },
+ "mailed": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "mailStatus",
+ "mailAttempts",
+ "mailed"
+ ],
+ "type": "object"
+ },
+ "ContactSettingsDto": {
+ "properties": {
+ "enabled": {
+ "type": "boolean"
+ },
+ "hostEnabled": {
+ "type": "boolean"
+ },
+ "recipientEmail": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "recipientSource": {
+ "default": "none",
+ "type": "string"
+ }
+ },
+ "required": [
+ "enabled",
+ "hostEnabled"
+ ],
+ "type": "object"
+ },
+ "ContactTokenResponse": {
+ "properties": {
+ "captcha": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/ContactCaptchaInfo"
+ }
+ ]
+ },
+ "minSeconds": {
+ "format": "int32",
+ "pattern": "^-?(?:0|[1-9]\\d*)$",
+ "type": [
+ "integer",
+ "string"
+ ]
+ },
+ "token": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "token",
+ "minSeconds",
+ "captcha"
+ ],
+ "type": "object"
+ },
+ "CreateCmsInstanceRequest": {
+ "properties": {
+ "apiKey": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "url": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "name",
+ "url",
+ "apiKey"
+ ],
+ "type": "object"
+ },
+ "CreateOfferingRequest": {
+ "properties": {
+ "categoryId": {
+ "format": "uuid",
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "ctaLabel": {
+ "type": "string"
+ },
+ "description": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "endsAt": {
+ "format": "date-time",
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "featured": {
+ "default": false,
+ "type": "boolean"
+ },
+ "features": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "isActive": {
+ "default": true,
+ "type": "boolean"
+ },
+ "price": {
+ "type": "string"
+ },
+ "priceNote": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "slug": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "startsAt": {
+ "format": "date-time",
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "title": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "title",
+ "description",
+ "price",
+ "priceNote",
+ "features",
+ "ctaLabel"
+ ],
+ "type": "object"
+ },
+ "CreateOwnerRequest": {
+ "properties": {
+ "email": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "password": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "name",
+ "email",
+ "password"
+ ],
+ "type": "object"
+ },
+ "ForgotPasswordRequest": {
+ "properties": {
+ "email": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "email"
+ ],
+ "type": "object"
+ },
+ "InviteUserRequest": {
+ "properties": {
+ "email": {
+ "type": "string"
+ },
+ "language": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "role": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "email",
+ "role"
+ ],
+ "type": "object"
+ },
+ "LoginRequest": {
+ "properties": {
+ "email": {
+ "type": "string"
+ },
+ "password": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "email",
+ "password"
+ ],
+ "type": "object"
+ },
+ "OfferingBannerRequest": {
+ "properties": {
+ "endsAt": {
+ "format": "date-time",
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "isActive": {
+ "default": true,
+ "type": "boolean"
+ },
+ "linkLabel": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "linkUrl": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "position": {
+ "default": "bottom",
+ "type": "string"
+ },
+ "startsAt": {
+ "format": "date-time",
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "text": {
+ "type": "string"
+ },
+ "title": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "title",
+ "text"
+ ],
+ "type": "object"
+ },
+ "OfferingCategoryRequest": {
+ "properties": {
+ "name": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "name"
+ ],
+ "type": "object"
+ },
+ "Problem": {
+ "description": "RFC 9457 problem details. Only the standard members are sent; nothing about the limiter, the policy or the caller.",
+ "properties": {
+ "status": {
+ "format": "int32",
+ "type": "integer"
+ },
+ "title": {
+ "type": "string"
+ },
+ "type": {
+ "type": "string"
+ }
+ },
+ "type": "object"
+ },
+ "ProblemDetails": {
+ "properties": {
+ "detail": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "instance": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "status": {
+ "format": "int32",
+ "pattern": "^-?(?:0|[1-9]\\d*)$",
+ "type": [
+ "null",
+ "integer",
+ "string"
+ ]
+ },
+ "title": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "type": {
+ "type": [
+ "null",
+ "string"
+ ]
+ }
+ },
+ "type": "object"
+ },
+ "PushStatusRequest": {
+ "properties": {
+ "disableMessage": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "isAvailable": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "isAvailable",
+ "disableMessage"
+ ],
+ "type": "object"
+ },
+ "ReceivedResponse": {
+ "properties": {
+ "status": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "status"
+ ],
+ "type": "object"
+ },
+ "RegenerateInviteRequest": {
+ "properties": {
+ "sendEmail": {
+ "default": false,
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+ },
+ "RegisterMasterRequest": {
+ "properties": {
+ "masterUrl": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "masterUrl"
+ ],
+ "type": "object"
+ },
+ "ReorderOfferingsRequest": {
+ "properties": {
+ "orderedIds": {
+ "items": {
+ "format": "uuid",
+ "type": "string"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "orderedIds"
+ ],
+ "type": "object"
+ },
+ "ResetPasswordRequest": {
+ "properties": {
+ "newPassword": {
+ "type": "string"
+ },
+ "token": {
+ "type": "string"
+ },
+ "userId": {
+ "format": "uuid",
+ "type": "string"
+ }
+ },
+ "required": [
+ "userId",
+ "token",
+ "newPassword"
+ ],
+ "type": "object"
+ },
+ "SetUserActiveRequest": {
+ "properties": {
+ "isActive": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "isActive"
+ ],
+ "type": "object"
+ },
+ "UpdateContactMessageStatusRequest": {
+ "properties": {
+ "status": {
+ "type": [
+ "null",
+ "string"
+ ]
+ }
+ },
+ "required": [
+ "status"
+ ],
+ "type": "object"
+ },
+ "UpdateContactRecipientRequest": {
+ "properties": {
+ "recipientEmail": {
+ "type": [
+ "null",
+ "string"
+ ]
+ }
+ },
+ "required": [
+ "recipientEmail"
+ ],
+ "type": "object"
+ },
+ "UpdateContactSettingsRequest": {
+ "properties": {
+ "enabled": {
+ "type": [
+ "null",
+ "boolean"
+ ]
+ }
+ },
+ "required": [
+ "enabled"
+ ],
+ "type": "object"
+ },
+ "UpdateMailSettingsRequest": {
+ "properties": {
+ "fromAddress": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "fromName": {
+ "type": [
+ "null",
+ "string"
+ ]
+ }
+ },
+ "required": [
+ "fromAddress",
+ "fromName"
+ ],
+ "type": "object"
+ },
+ "UpdateOfferingRequest": {
+ "properties": {
+ "categoryId": {
+ "format": "uuid",
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "ctaLabel": {
+ "type": "string"
+ },
+ "description": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "endsAt": {
+ "format": "date-time",
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "featured": {
+ "default": false,
+ "type": "boolean"
+ },
+ "features": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "isActive": {
+ "default": true,
+ "type": "boolean"
+ },
+ "price": {
+ "type": "string"
+ },
+ "priceNote": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "slug": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "startsAt": {
+ "format": "date-time",
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "title": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "title",
+ "description",
+ "price",
+ "priceNote",
+ "features",
+ "ctaLabel"
+ ],
+ "type": "object"
+ },
+ "UpdateProfileRequest": {
+ "properties": {
+ "email": {
+ "type": "string"
+ },
+ "language": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "name": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "name",
+ "email"
+ ],
+ "type": "object"
+ },
+ "UpdateStatusRequest": {
+ "properties": {
+ "newStatus": {
+ "$ref": "#/components/schemas/AvailabilityStatus"
+ },
+ "reason": {
+ "type": [
+ "null",
+ "string"
+ ]
+ }
+ },
+ "required": [
+ "newStatus",
+ "reason"
+ ],
+ "type": "object"
+ },
+ "ValidationProblem": {
+ "description": "A 400 answer. 'errors' maps the JSON field name (name, email, subject, message, token, idempotencyKey, body) to its error codes; the client maps codes to texts.",
+ "properties": {
+ "errors": {
+ "additionalProperties": {
+ "items": {
+ "enum": [
+ "required",
+ "tooLong",
+ "invalid",
+ "expired"
+ ],
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "type": "object"
+ },
+ "status": {
+ "format": "int32",
+ "type": "integer"
+ },
+ "title": {
+ "type": "string"
+ },
+ "type": {
+ "type": "string"
+ }
+ },
+ "type": "object"
+ },
+ "ValidationProblemDetails": {
+ "properties": {
+ "detail": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "errors": {
+ "additionalProperties": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "type": "object"
+ },
+ "instance": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "status": {
+ "format": "int32",
+ "pattern": "^-?(?:0|[1-9]\\d*)$",
+ "type": [
+ "null",
+ "integer",
+ "string"
+ ]
+ },
+ "title": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "type": {
+ "type": [
+ "null",
+ "string"
+ ]
+ }
+ },
+ "type": "object"
+ }
+ }
+ },
+ "info": {
+ "title": "SlpModularCms.Api | v1",
+ "version": "1.0.0"
+ },
+ "openapi": "3.1.1",
+ "paths": {
+ "/api/v1/Availability/status": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Availability"
+ ]
+ },
+ "put": {
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateStatusRequest"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateStatusRequest"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateStatusRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Availability"
+ ]
+ }
+ },
+ "/api/v1/CmsInstances": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "CmsInstance"
+ ]
+ },
+ "post": {
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateCmsInstanceRequest"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateCmsInstanceRequest"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateCmsInstanceRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "CmsInstance"
+ ]
+ }
+ },
+ "/api/v1/CmsInstances/{id}/status": {
+ "put": {
+ "parameters": [
+ {
+ "in": "path",
+ "name": "id",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateStatusRequest"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateStatusRequest"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateStatusRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "CmsInstance"
+ ]
+ }
+ },
+ "/api/v1/Invitation/complete": {
+ "post": {
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "$ref": "#/components/schemas/CompleteSetupRequest"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CompleteSetupRequest"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CompleteSetupRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Invitation"
+ ]
+ }
+ },
+ "/api/v1/Invitation/validate": {
+ "get": {
+ "parameters": [
+ {
+ "in": "query",
+ "name": "token",
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Invitation"
+ ]
+ }
+ },
+ "/api/v1/Master/register": {
+ "post": {
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "$ref": "#/components/schemas/RegisterMasterRequest"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RegisterMasterRequest"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RegisterMasterRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Master"
+ ]
+ }
+ },
+ "/api/v1/Master/registered-url": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Master"
+ ]
+ }
+ },
+ "/api/v1/Master/status": {
+ "post": {
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "$ref": "#/components/schemas/PushStatusRequest"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PushStatusRequest"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PushStatusRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Master"
+ ]
+ }
+ },
+ "/api/v1/Setup/owner": {
+ "post": {
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateOwnerRequest"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateOwnerRequest"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateOwnerRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Setup"
+ ]
+ }
+ },
+ "/api/v1/Setup/status": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Setup"
+ ]
+ }
+ },
+ "/api/v1/SiteSettings/mail": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "SiteSettings"
+ ]
+ },
+ "put": {
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateMailSettingsRequest"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateMailSettingsRequest"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateMailSettingsRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "SiteSettings"
+ ]
+ }
+ },
+ "/api/v1/SlaveStatus": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "SlaveStatus"
+ ]
+ }
+ },
+ "/api/v1/System/capabilities": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "System"
+ ]
+ }
+ },
+ "/api/v1/Users": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Users"
+ ]
+ }
+ },
+ "/api/v1/Users/invite": {
+ "post": {
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "$ref": "#/components/schemas/InviteUserRequest"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/InviteUserRequest"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/InviteUserRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Users"
+ ]
+ }
+ },
+ "/api/v1/Users/me": {
+ "put": {
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateProfileRequest"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateProfileRequest"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateProfileRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Users"
+ ]
+ }
+ },
+ "/api/v1/Users/{invitationId}/regenerate-invite": {
+ "post": {
+ "parameters": [
+ {
+ "in": "path",
+ "name": "invitationId",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/RegenerateInviteRequest"
+ }
+ ]
+ }
+ },
+ "application/json": {
+ "schema": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/RegenerateInviteRequest"
+ }
+ ]
+ }
+ },
+ "text/json": {
+ "schema": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/RegenerateInviteRequest"
+ }
+ ]
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Users"
+ ]
+ }
+ },
+ "/api/v1/Users/{invitationId}/resend-invite": {
+ "post": {
+ "parameters": [
+ {
+ "in": "path",
+ "name": "invitationId",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Users"
+ ]
+ }
+ },
+ "/api/v1/Users/{userId}": {
+ "delete": {
+ "parameters": [
+ {
+ "in": "path",
+ "name": "userId",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Users"
+ ]
+ }
+ },
+ "/api/v1/Users/{userId}/active": {
+ "put": {
+ "parameters": [
+ {
+ "in": "path",
+ "name": "userId",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "$ref": "#/components/schemas/SetUserActiveRequest"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SetUserActiveRequest"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SetUserActiveRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Users"
+ ]
+ }
+ },
+ "/api/v1/Users/{userId}/role": {
+ "put": {
+ "parameters": [
+ {
+ "in": "path",
+ "name": "userId",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "$ref": "#/components/schemas/ChangeRoleRequest"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ChangeRoleRequest"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ChangeRoleRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Users"
+ ]
+ }
+ },
+ "/api/v1/auth/change-password": {
+ "post": {
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "$ref": "#/components/schemas/ChangePasswordRequest"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ChangePasswordRequest"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ChangePasswordRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Auth"
+ ]
+ }
+ },
+ "/api/v1/auth/forgot-password": {
+ "post": {
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "$ref": "#/components/schemas/ForgotPasswordRequest"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ForgotPasswordRequest"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ForgotPasswordRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Auth"
+ ]
+ }
+ },
+ "/api/v1/auth/login": {
+ "post": {
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "$ref": "#/components/schemas/LoginRequest"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/LoginRequest"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/LoginRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Auth"
+ ]
+ }
+ },
+ "/api/v1/auth/refresh": {
+ "post": {
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Auth"
+ ]
+ }
+ },
+ "/api/v1/auth/reset-password": {
+ "post": {
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "$ref": "#/components/schemas/ResetPasswordRequest"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ResetPasswordRequest"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ResetPasswordRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Auth"
+ ]
+ }
+ },
+ "/api/v1/auth/revoke": {
+ "post": {
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Auth"
+ ]
+ }
+ },
+ "/api/v1/contact-messages": {
+ "get": {
+ "parameters": [
+ {
+ "in": "query",
+ "name": "status",
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "in": "query",
+ "name": "page",
+ "schema": {
+ "default": 1,
+ "format": "int32",
+ "pattern": "^-?(?:0|[1-9]\\d*)$",
+ "type": [
+ "integer",
+ "string"
+ ]
+ }
+ },
+ {
+ "in": "query",
+ "name": "pageSize",
+ "schema": {
+ "default": 25,
+ "format": "int32",
+ "pattern": "^-?(?:0|[1-9]\\d*)$",
+ "type": [
+ "integer",
+ "string"
+ ]
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ContactMessageList"
+ }
+ }
+ },
+ "description": "OK"
+ },
+ "400": {
+ "content": {
+ "application/problem+json": {
+ "schema": {
+ "$ref": "#/components/schemas/ValidationProblemDetails"
+ }
+ }
+ },
+ "description": "Bad Request"
+ }
+ },
+ "tags": [
+ "ContactMessagesAdmin"
+ ]
+ },
+ "post": {
+ "description": "Stores a message. While the captcha is on, 'captchaToken' (the widget response) is required: a missing, empty or rejected value is treated as spam and answered exactly like a genuine message (202, stored with status spam), never with a 400. A captcha provider that does not answer in time, or fails, lets the visitor through (fail-open).",
+ "parameters": [
+ {
+ "description": "A UUID chosen by the client per attempt series. A replay within 24 hours is answered with the same 202 without storing the message twice.",
+ "in": "header",
+ "name": "Idempotency-Key",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ContactMessageRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "202": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ReceivedResponse"
+ }
+ }
+ },
+ "description": "Accepted"
+ },
+ "400": {
+ "$ref": "#/components/responses/Validation"
+ },
+ "404": {
+ "description": "The contact form is closed on this site (the website shows its mailto fallback)."
+ },
+ "413": {
+ "$ref": "#/components/responses/TooLarge"
+ },
+ "429": {
+ "$ref": "#/components/responses/RateLimited"
+ }
+ },
+ "tags": [
+ "ContactMessages"
+ ]
+ }
+ },
+ "/api/v1/contact-messages/token": {
+ "get": {
+ "description": "Returns a signed form token and the minimum number of seconds before a submission counts as human. 'captcha' is null while the captcha is off; otherwise it is { provider: \"friendlycaptcha\", siteKey, apiEndpoint: \"global\"|\"eu\" } (Friendly Captcha v2; apiEndpoint is the widget's data region and follows the server configuration), which the website widget needs. Nothing else about the captcha (secret, verify URL) is ever returned.",
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ContactTokenResponse"
+ }
+ }
+ },
+ "description": "OK"
+ },
+ "404": {
+ "description": "The contact form is closed on this site (the website shows its mailto fallback)."
+ },
+ "429": {
+ "$ref": "#/components/responses/RateLimited"
+ }
+ },
+ "tags": [
+ "ContactMessages"
+ ]
+ }
+ },
+ "/api/v1/contact-messages/{id}": {
+ "delete": {
+ "parameters": [
+ {
+ "in": "path",
+ "name": "id",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "No Content"
+ },
+ "404": {
+ "description": "Not Found"
+ }
+ },
+ "tags": [
+ "ContactMessagesAdmin"
+ ]
+ },
+ "get": {
+ "parameters": [
+ {
+ "in": "path",
+ "name": "id",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ContactMessageDetail"
+ }
+ }
+ },
+ "description": "OK"
+ },
+ "404": {
+ "description": "Not Found"
+ }
+ },
+ "tags": [
+ "ContactMessagesAdmin"
+ ]
+ },
+ "patch": {
+ "parameters": [
+ {
+ "in": "path",
+ "name": "id",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/UpdateContactMessageStatusRequest"
+ }
+ ]
+ }
+ },
+ "application/json": {
+ "schema": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/UpdateContactMessageStatusRequest"
+ }
+ ]
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ContactMessageDetail"
+ }
+ }
+ },
+ "description": "OK"
+ },
+ "400": {
+ "content": {
+ "application/problem+json": {
+ "schema": {
+ "$ref": "#/components/schemas/ValidationProblemDetails"
+ }
+ }
+ },
+ "description": "Bad Request"
+ },
+ "404": {
+ "description": "Not Found"
+ }
+ },
+ "tags": [
+ "ContactMessagesAdmin"
+ ]
+ }
+ },
+ "/api/v1/contact-messages/{id}/resend": {
+ "post": {
+ "parameters": [
+ {
+ "in": "path",
+ "name": "id",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ContactResendResult"
+ }
+ }
+ },
+ "description": "OK"
+ },
+ "404": {
+ "description": "Not Found"
+ },
+ "409": {
+ "content": {
+ "application/problem+json": {
+ "schema": {
+ "$ref": "#/components/schemas/ProblemDetails"
+ }
+ }
+ },
+ "description": "Conflict"
+ },
+ "429": {
+ "content": {
+ "application/problem+json": {
+ "schema": {
+ "$ref": "#/components/schemas/ProblemDetails"
+ }
+ }
+ },
+ "description": "Too Many Requests"
+ }
+ },
+ "tags": [
+ "ContactMessagesAdmin"
+ ]
+ }
+ },
+ "/api/v1/contact-settings": {
+ "get": {
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ContactSettingsDto"
+ }
+ }
+ },
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "ContactSettings"
+ ]
+ },
+ "put": {
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/UpdateContactSettingsRequest"
+ }
+ ]
+ }
+ },
+ "application/json": {
+ "schema": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/UpdateContactSettingsRequest"
+ }
+ ]
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ContactSettingsDto"
+ }
+ }
+ },
+ "description": "OK"
+ },
+ "400": {
+ "content": {
+ "application/problem+json": {
+ "schema": {
+ "$ref": "#/components/schemas/ValidationProblemDetails"
+ }
+ }
+ },
+ "description": "Bad Request"
+ }
+ },
+ "tags": [
+ "ContactSettings"
+ ]
+ }
+ },
+ "/api/v1/contact-settings/recipient": {
+ "put": {
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/UpdateContactRecipientRequest"
+ }
+ ]
+ }
+ },
+ "application/json": {
+ "schema": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/UpdateContactRecipientRequest"
+ }
+ ]
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ContactSettingsDto"
+ }
+ }
+ },
+ "description": "OK"
+ },
+ "400": {
+ "content": {
+ "application/problem+json": {
+ "schema": {
+ "$ref": "#/components/schemas/ValidationProblemDetails"
+ }
+ }
+ },
+ "description": "Bad Request"
+ }
+ },
+ "tags": [
+ "ContactSettings"
+ ]
+ }
+ },
+ "/api/v1/offerings": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Offerings"
+ ]
+ },
+ "post": {
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateOfferingRequest"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateOfferingRequest"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateOfferingRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Offerings"
+ ]
+ }
+ },
+ "/api/v1/offerings/all": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Offerings"
+ ]
+ }
+ },
+ "/api/v1/offerings/banner": {
+ "get": {
+ "parameters": [
+ {
+ "in": "query",
+ "name": "position",
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "PublicOfferingBanner"
+ ]
+ }
+ },
+ "/api/v1/offerings/banners": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "OfferingBanners"
+ ]
+ },
+ "post": {
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "$ref": "#/components/schemas/OfferingBannerRequest"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/OfferingBannerRequest"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/OfferingBannerRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "OfferingBanners"
+ ]
+ }
+ },
+ "/api/v1/offerings/banners/{id}": {
+ "delete": {
+ "parameters": [
+ {
+ "in": "path",
+ "name": "id",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "OfferingBanners"
+ ]
+ },
+ "put": {
+ "parameters": [
+ {
+ "in": "path",
+ "name": "id",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "$ref": "#/components/schemas/OfferingBannerRequest"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/OfferingBannerRequest"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/OfferingBannerRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "OfferingBanners"
+ ]
+ }
+ },
+ "/api/v1/offerings/categories": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "OfferingCategories"
+ ]
+ },
+ "post": {
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "$ref": "#/components/schemas/OfferingCategoryRequest"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/OfferingCategoryRequest"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/OfferingCategoryRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "OfferingCategories"
+ ]
+ }
+ },
+ "/api/v1/offerings/categories/{id}": {
+ "delete": {
+ "parameters": [
+ {
+ "in": "path",
+ "name": "id",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "OfferingCategories"
+ ]
+ },
+ "put": {
+ "parameters": [
+ {
+ "in": "path",
+ "name": "id",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "$ref": "#/components/schemas/OfferingCategoryRequest"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/OfferingCategoryRequest"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/OfferingCategoryRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "OfferingCategories"
+ ]
+ }
+ },
+ "/api/v1/offerings/order": {
+ "put": {
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "$ref": "#/components/schemas/ReorderOfferingsRequest"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ReorderOfferingsRequest"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ReorderOfferingsRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Offerings"
+ ]
+ }
+ },
+ "/api/v1/offerings/{id}": {
+ "delete": {
+ "parameters": [
+ {
+ "in": "path",
+ "name": "id",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Offerings"
+ ]
+ },
+ "put": {
+ "parameters": [
+ {
+ "in": "path",
+ "name": "id",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/*+json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateOfferingRequest"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateOfferingRequest"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateOfferingRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "Offerings"
+ ]
+ }
+ },
+ "/health": {
+ "get": {
+ "operationId": "HealthCheck",
+ "responses": {
+ "200": {
+ "description": "OK"
+ }
+ },
+ "tags": [
+ "SlpModularCms.Api"
+ ]
+ }
+ }
+ },
+ "tags": [
+ {
+ "name": "SlpModularCms.Api"
+ },
+ {
+ "name": "System"
+ },
+ {
+ "name": "Availability"
+ },
+ {
+ "name": "Master"
+ },
+ {
+ "name": "ContactMessagesAdmin"
+ },
+ {
+ "name": "ContactMessages"
+ },
+ {
+ "name": "ContactSettings"
+ },
+ {
+ "name": "Auth"
+ },
+ {
+ "name": "Invitation"
+ },
+ {
+ "name": "Setup"
+ },
+ {
+ "name": "SiteSettings"
+ },
+ {
+ "name": "Users"
+ },
+ {
+ "name": "CmsInstance"
+ },
+ {
+ "name": "SlaveStatus"
+ },
+ {
+ "name": "OfferingBanners"
+ },
+ {
+ "name": "PublicOfferingBanner"
+ },
+ {
+ "name": "OfferingCategories"
+ },
+ {
+ "name": "Offerings"
+ }
+ ]
+}
diff --git a/scripts/Export-MailTexts.ps1 b/scripts/Export-MailTexts.ps1
new file mode 100644
index 0000000..e39129d
--- /dev/null
+++ b/scripts/Export-MailTexts.ps1
@@ -0,0 +1,92 @@
+<#
+.SYNOPSIS
+ Writes docs/mail-teksten.md: a readable overview of every mail the CMS sends (the texts per kind in Dutch and English,
+ and the plain-text version of each Dutch and English example).
+
+.DESCRIPTION
+ Reads src/SlpModularCms.Core/Texts/nl.json and en.json (the single source of the sentences) and the recorded example
+ mails in src/SlpModularCms.Core.Tests/Golden/mail. Run it after changing a mail text; the file is generated, do not
+ edit it by hand.
+
+.EXAMPLE
+ ./scripts/Export-MailTexts.ps1
+#>
+[CmdletBinding()]
+param([string] $Output)
+
+$ErrorActionPreference = 'Stop'
+$here = if ($PSScriptRoot) { $PSScriptRoot } else { Split-Path -Parent $MyInvocation.MyCommand.Path }
+$root = Resolve-Path (Join-Path $here '..')
+if (-not $Output) { $Output = Join-Path $root 'docs\mail-teksten.md' }
+$nl = Get-Content -LiteralPath (Join-Path $root 'src\SlpModularCms.Core\Texts\nl.json') -Raw -Encoding UTF8 | ConvertFrom-Json
+$en = Get-Content -LiteralPath (Join-Path $root 'src\SlpModularCms.Core\Texts\en.json') -Raw -Encoding UTF8 | ConvertFrom-Json
+$golden = Join-Path $root 'src\SlpModularCms.Core.Tests\Golden\mail'
+
+$kinds = [ordered]@{
+ Invitation = @{ Key = 'invitation'; Title = 'Uitnodiging'; When = 'Een beheerder nodigt iemand uit.' }
+ NewInvitationLink = @{ Key = 'newInvitationLink'; Title = 'Nieuwe uitnodigingslink'; When = 'Een beheerder maakt een nieuwe uitnodigingslink aan.' }
+ PasswordReset = @{ Key = 'passwordReset'; Title = 'Wachtwoord opnieuw instellen'; When = 'Iemand vraagt een nieuw wachtwoord aan.' }
+ AccountDeactivated = @{ Key = 'accountDeactivated'; Title = 'Account gedeactiveerd'; When = 'Een beheerder deactiveert een account.' }
+ AccountReactivated = @{ Key = 'accountReactivated'; Title = 'Account weer actief'; When = 'Een beheerder activeert een account weer.' }
+ RoleChanged = @{ Key = 'roleChanged'; Title = 'Rol gewijzigd'; When = 'Een beheerder wijzigt de rol van een gebruiker.' }
+ ContactMessage = @{ Key = 'contactMessage'; Title = 'Nieuw contactbericht'; When = 'Een bezoeker verstuurt het contactformulier; de mail gaat naar de eigenaar van de site.' }
+}
+$parts = [ordered]@{ subject = 'Onderwerp'; heading = 'Kop'; intro = 'Inleiding'; button = 'Knop'; note = 'Opmerking onderaan' }
+
+function Cell([string] $text) { if ([string]::IsNullOrEmpty($text)) { '-' } else { $text.Replace('|', '\|') } }
+
+$sb = [System.Text.StringBuilder]::new()
+[void]$sb.AppendLine('# Teksten van de mails van het CMS')
+[void]$sb.AppendLine()
+[void]$sb.AppendLine('Gegenereerd door `scripts/Export-MailTexts.ps1` uit `src/SlpModularCms.Core/Texts/nl.json` en `en.json` (en de voorbeeldmails in `src/SlpModularCms.Core.Tests/Golden/mail`). Niet met de hand wijzigen: pas de tekstbestanden aan en draai het script opnieuw. Zie [translation-files.md](translation-files.md) voor de opzet.')
+[void]$sb.AppendLine()
+[void]$sb.AppendLine('In de teksten staan plaatshouders tussen accolades die bij het versturen worden ingevuld: `{site}` (naam van de site), `{validity}` (hoe lang een link geldig is, bijvoorbeeld "48 uur" of "30 minuten"), `{role}` (de nieuwe rol) en `{name}` (naam van de ontvanger). Elke mail heeft bovenaan een kop, optioneel een aanhef, de inleiding, eventueel een knop met de link, een opmerking en onderaan een vaste voettekst.')
+[void]$sb.AppendLine()
+[void]$sb.AppendLine('## Vaste onderdelen')
+[void]$sb.AppendLine()
+[void]$sb.AppendLine('| Onderdeel | Nederlands | Engels |')
+[void]$sb.AppendLine('|---|---|---|')
+foreach ($row in @(
+ @('Aanhef (als de naam van de ontvanger bekend is)', 'greeting'),
+ @('Voettekst onder elke mail', 'footer'),
+ @('Rol: eigenaar', 'role.owner'), @('Rol: beheerder', 'role.administrator'), @('Rol: gebruiker', 'role.user'),
+ @('Geldigheid, 1 uur', 'validity.hoursOne'), @('Geldigheid, meerdere uren', 'validity.hoursOther'), @('Geldigheid, minuten', 'validity.minutes'))) {
+ $get = { param($o, $path) $v = $o.core.mail; foreach ($p in $path.Split('.')) { $v = $v.$p }; $v }
+ [void]$sb.AppendLine("| $($row[0]) | $(Cell (& $get $nl $row[1])) | $(Cell (& $get $en $row[1])) |")
+}
+
+foreach ($kind in $kinds.Keys) {
+ $info = $kinds[$kind]
+ [void]$sb.AppendLine()
+ [void]$sb.AppendLine("## $($info.Title)")
+ [void]$sb.AppendLine()
+ [void]$sb.AppendLine("Wanneer: $($info.When)")
+ [void]$sb.AppendLine()
+ [void]$sb.AppendLine('| Onderdeel | Nederlands | Engels |')
+ [void]$sb.AppendLine('|---|---|---|')
+ foreach ($part in $parts.Keys) {
+ $n = $nl.core.mail.($info.Key).$part
+ $e = $en.core.mail.($info.Key).$part
+ if (-not $n -and -not $e) { continue }
+ [void]$sb.AppendLine("| $($parts[$part]) | $(Cell $n) | $(Cell $e) |")
+ }
+ foreach ($lang in 'nl', 'en') {
+ $file = Join-Path $golden "$kind.$lang.full.txt"
+ if (-not (Test-Path $file)) { continue }
+ $text = (Get-Content -LiteralPath $file -Raw -Encoding UTF8) -replace "`r`n", "`n"
+ $idx = $text.IndexOf("--TEXT--`n")
+ if ($idx -lt 0) { continue }
+ $plain = $text.Substring($idx + 9).TrimEnd()
+ $label = if ($lang -eq 'nl') { 'Voorbeeld (tekstversie, Nederlands)' } else { 'Voorbeeld (tekstversie, Engels)' }
+ [void]$sb.AppendLine()
+ [void]$sb.AppendLine("**$label**, met voorbeeldwaarden (site 'Test & Co', ontvanger 'Jan ""de"" Vries'):")
+ [void]$sb.AppendLine()
+ [void]$sb.AppendLine('```text')
+ [void]$sb.AppendLine($plain)
+ [void]$sb.AppendLine('```')
+ }
+}
+
+$full = [System.IO.Path]::GetFullPath($Output)
+[System.IO.File]::WriteAllText($full, $sb.ToString().Replace("`r`n", "`n"), [System.Text.UTF8Encoding]::new($false))
+Write-Host "Written $full"
diff --git a/scripts/Seed-Offerings.ps1 b/scripts/Seed-Offerings.ps1
new file mode 100644
index 0000000..f2131cb
--- /dev/null
+++ b/scripts/Seed-Offerings.ps1
@@ -0,0 +1,104 @@
+<#
+.SYNOPSIS
+ Creates offerings (packages) in a CMS through the admin API. Idempotent: a slug that already exists is skipped.
+
+.DESCRIPTION
+ Logs in with an admin account (the password is asked interactively, as a secure string; it is never
+ written to disk, to the console or to a log), then creates the offerings from -PackagesFile in file
+ order with an explicit slug. DisplayOrder is assigned by the server in creation order (0, 1, 2, ...).
+ Test hosts only unless you deliberately point it somewhere else.
+
+.PARAMETER BaseUrl
+ Root of the host, e.g. https://test.andreaslop.nl (no trailing /api).
+
+.PARAMETER Email
+ Admin e-mail address. Asked when omitted.
+
+.PARAMETER PackagesFile
+ JSON array; default: offerings-asf.json next to this script. Each item: slug, title, description,
+ price, priceNote, features (array), ctaLabel, layout (card|banner, default card), featured (default false).
+
+.PARAMETER WhatIf
+ Shows what would be created without logging in or writing anything.
+
+.EXAMPLE
+ ./scripts/Seed-Offerings.ps1 -BaseUrl https://test.andreaslop.nl
+#>
+[CmdletBinding(SupportsShouldProcess)]
+param(
+ [Parameter(Mandatory)] [string] $BaseUrl,
+ [string] $Email,
+ [string] $PackagesFile = (Join-Path $PSScriptRoot 'offerings-asf.json')
+)
+
+$ErrorActionPreference = 'Stop'
+$BaseUrl = $BaseUrl.TrimEnd('/')
+$api = "$BaseUrl/api/v1"
+
+$packages = Get-Content -LiteralPath $PackagesFile -Raw -Encoding UTF8 | ConvertFrom-Json
+if (-not $packages -or $packages.Count -eq 0) { throw "No packages in $PackagesFile." }
+
+# Refuse unfinished templates: no guessed copy ends up in a CMS.
+foreach ($p in $packages) {
+ foreach ($field in 'slug', 'title', 'price') {
+ $v = $p.$field
+ if ([string]::IsNullOrWhiteSpace($v) -or $v -like 'TODO*') { throw "Package '$($p.slug)': '$field' is empty or still TODO." }
+ }
+ # description, priceNote and ctaLabel may be empty (the API accepts empty strings), but never TODO.
+ foreach ($field in 'description', 'priceNote', 'ctaLabel') {
+ if ("$($p.$field)" -like 'TODO*') { throw "Package '$($p.slug)': '$field' is still TODO." }
+ }
+ if (-not $p.features -or $p.features.Count -eq 0 -or ($p.features | Where-Object { $_ -like 'TODO*' })) {
+ throw "Package '$($p.slug)': 'features' is empty or still TODO."
+ }
+}
+
+if ($WhatIfPreference) {
+ $packages | ForEach-Object { Write-Host "Would create '$($_.slug)' ($($_.title), $($_.price)) on $BaseUrl" }
+ return
+}
+
+if (-not $Email) { $Email = Read-Host 'Admin e-mail' }
+$secure = Read-Host "Password for $Email" -AsSecureString
+$bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)
+try {
+ $plain = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr)
+ $body = @{ email = $Email; password = $plain } | ConvertTo-Json -Compress
+ $login = Invoke-RestMethod -Method Post -Uri "$api/auth/login" -ContentType 'application/json' -Body $body
+}
+finally {
+ [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)
+ $plain = $null; $body = $null
+}
+$headers = @{ Authorization = "Bearer $($login.accessToken)" }
+
+# The public list tells which slugs exist already.
+# Windows PowerShell 5.1 hands a JSON array over as ONE object; wrap it so every item is enumerated.
+$list = @(Invoke-RestMethod -Method Get -Uri "$api/offerings" -Headers $headers)
+$existing = @(foreach ($o in $list) { $o.slug })
+
+foreach ($p in $packages) {
+ if ($existing -contains $p.slug) { Write-Host "skip $($p.slug) (exists)"; continue }
+ $payload = [ordered]@{
+ slug = $p.slug
+ title = $p.title
+ description = $p.description
+ price = $p.price
+ priceNote = $p.priceNote
+ features = @($p.features)
+ ctaLabel = $p.ctaLabel
+ featured = [bool]$p.featured
+ layout = if ($p.layout) { $p.layout } else { 'card' }
+ } | ConvertTo-Json -Depth 5
+ try {
+ $created = Invoke-RestMethod -Method Post -Uri "$api/offerings" -Headers $headers -ContentType 'application/json; charset=utf-8' -Body ([Text.Encoding]::UTF8.GetBytes($payload))
+ Write-Host "create $($created.slug) (displayOrder $($created.displayOrder))"
+ }
+ catch {
+ Write-Error "Creating '$($p.slug)' failed: $($_.Exception.Message) $($_.ErrorDetails.Message)"
+ }
+}
+
+Write-Host 'Result:'
+$final = @(Invoke-RestMethod -Method Get -Uri "$api/offerings")
+foreach ($o in $final) { Write-Host (" {0,2} {1} {2} [{3}]" -f $o.displayOrder, $o.slug, $o.price, $o.layout) }
diff --git a/scripts/offerings-asf.json b/scripts/offerings-asf.json
new file mode 100644
index 0000000..2fa2133
--- /dev/null
+++ b/scripts/offerings-asf.json
@@ -0,0 +1,44 @@
+[
+ {
+ "slug": "zwangerschap",
+ "title": "Zwangerschap",
+ "description": "",
+ "price": "€ 175",
+ "priceNote": "",
+ "features": [
+ "1 uur fotografie",
+ "Minstens 30 zorgvuldig nabewerkte foto's",
+ "Persoonlijke online fotogalerij"
+ ],
+ "ctaLabel": "",
+ "layout": "card"
+ },
+ {
+ "slug": "newborn",
+ "title": "Newborn",
+ "description": "",
+ "price": "€ 185",
+ "priceNote": "",
+ "features": [
+ "1-2 uur fotografie",
+ "Minstens 40 zorgvuldig nabewerkte foto's",
+ "Persoonlijke online fotogalerij"
+ ],
+ "ctaLabel": "",
+ "layout": "card"
+ },
+ {
+ "slug": "gezin",
+ "title": "Gezin",
+ "description": "",
+ "price": "€ 175",
+ "priceNote": "",
+ "features": [
+ "1 uur fotografie",
+ "Minstens 30 zorgvuldig nabewerkte foto's",
+ "Persoonlijke online fotogalerij"
+ ],
+ "ctaLabel": "",
+ "layout": "card"
+ }
+]
diff --git a/scripts/smoke-site.sh b/scripts/smoke-site.sh
new file mode 100644
index 0000000..cb32ef9
--- /dev/null
+++ b/scripts/smoke-site.sh
@@ -0,0 +1,97 @@
+#!/usr/bin/env bash
+# Smoke test of a deployed site: anonymous GET requests only, no secrets.
+#
+# Usage: scripts/smoke-site.sh
+# any URL of the host, for example its /health URL; only scheme and host are used
+# sls-test | asf-test
+#
+# A site project is a thin composition (modules + appsettings.json), so what can still go wrong at deploy time is
+# the composition itself: a module missing, the wrong website mode, a missing setting. The CI builds and tests the
+# master CMS only; this script is the check that the deployed composition of a site is the one that was intended.
+# A failing check makes the CI run fail.
+set -u
+
+base="$(printf '%s' "${1:?usage: smoke-site.sh }" | sed -E 's#^(https?://[^/]+).*#\1#')"
+profile="${2:?profile (sls-test | asf-test) is required}"
+failures=0
+
+curl_get() { curl -sS --max-time 20 --retry 4 --retry-delay 3 --retry-all-errors "$@"; }
+status_of() { curl_get -o /dev/null -w '%{http_code}' "$base$1"; }
+
+pass() { echo "ok $1"; }
+fail() { echo "FAIL $1"; failures=$((failures + 1)); }
+
+expect_status() { # path expected description
+ local got; got="$(status_of "$1")"
+ if [ "$got" = "$2" ]; then pass "$3 ($1 -> $got)"; else fail "$3 ($1 -> $got, expected $2)"; fi
+}
+
+expect_header() { # path header-name expected-substring description
+ local got; got="$(curl_get -D - -o /dev/null "$base$1" | tr -d '\r' | grep -i "^$2:" | head -1)"
+ if printf '%s' "$got" | grep -qi "$3"; then pass "$4 ($1 $2)"; else fail "$4 ($1 $2: '${got:-}')"; fi
+}
+
+expect_body() { # path expected-substring description
+ if curl_get "$base$1" | grep -qF "$2"; then pass "$3 ($1)"; else fail "$3 ($1 does not contain '$2')"; fi
+}
+
+echo "Smoke test '$profile' on $base"
+
+expect_status /health 200 "health"
+
+caps="$(curl_get "$base/api/v1/System/capabilities" || true)"
+module_listed() { printf '%s' "$caps" | grep -q "\"$1\""; }
+expect_module() { if module_listed "$1"; then pass "module $1 is loaded"; else fail "module $1 is NOT loaded (capabilities: ${caps:-})"; fi; }
+expect_no_module() { if module_listed "$1"; then fail "module $1 is loaded but must not be"; else pass "module $1 is not loaded"; fi; }
+
+expect_status /api/v1/offerings 200 "public offerings"
+# 204 = no active banner, 200 = there is one; both are a healthy answer.
+banner="$(status_of '/api/v1/offerings/banner')"
+if [ "$banner" = "200" ] || [ "$banner" = "204" ]; then pass "public banner (/api/v1/offerings/banner -> $banner)"; else fail "public banner (-> $banner, expected 200 or 204)"; fi
+expect_status /api/v1/offerings/all 401 "the administrator list is protected"
+
+# A test host is never indexed.
+expect_header / X-Robots-Tag noindex "noindex on the website"
+expect_body /robots.txt "Disallow: /" "robots.txt disallows everything"
+
+# The home page is served by the host. When the website build left CMS markers in it, the host must have processed
+# them: an unprocessed or JSON-LD marker means the page does not go through the injector (a proxy or
+# IIS serving files itself, or a host without the injection), and a deployed data block must carry this host's address.
+home="$(curl_get "$base/" || true)"
+if printf '%s' "$home" | grep -qE '
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/SlpModularCms.Api.AndreaSlopFotografie/Program.cs b/src/SlpModularCms.Api.AndreaSlopFotografie/Program.cs
index 8521d39..01fd3db 100644
--- a/src/SlpModularCms.Api.AndreaSlopFotografie/Program.cs
+++ b/src/SlpModularCms.Api.AndreaSlopFotografie/Program.cs
@@ -6,8 +6,9 @@ var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: true);
// Andrea Slop Fotografie serves a prerendered website from wwwroot/web (nginx-equivalent behaviour)
-// instead of the SPA-style website mount the other clients use.
-var hostOptions = new CmsHostOptions { WebsiteMode = WebsiteMode.PrerenderedPages };
+// instead of the SPA-style website mount the other clients use. That is chosen by Website:Mode in
+// appsettings.json, not here: this project is a composition (which modules, which settings) and nothing else.
+var hostOptions = new CmsHostOptions();
var orchestrator = CmsHost.ConfigureServices(builder, hostOptions);
@@ -17,5 +18,3 @@ CmsHost.ConfigurePipeline(app, orchestrator, hostOptions);
app.Run();
-// Exposed so the host regression tests can start the real application in-memory.
-public partial class Program;
diff --git a/src/SlpModularCms.Api.AndreaSlopFotografie/SlpModularCms.Api.AndreaSlopFotografie.csproj b/src/SlpModularCms.Api.AndreaSlopFotografie/SlpModularCms.Api.AndreaSlopFotografie.csproj
index 431adb8..9d89f19 100644
--- a/src/SlpModularCms.Api.AndreaSlopFotografie/SlpModularCms.Api.AndreaSlopFotografie.csproj
+++ b/src/SlpModularCms.Api.AndreaSlopFotografie/SlpModularCms.Api.AndreaSlopFotografie.csproj
@@ -18,14 +18,19 @@
+
+
diff --git a/src/SlpModularCms.Api.AndreaSlopFotografie/appsettings.json b/src/SlpModularCms.Api.AndreaSlopFotografie/appsettings.json
index 957375a..3c773dc 100644
--- a/src/SlpModularCms.Api.AndreaSlopFotografie/appsettings.json
+++ b/src/SlpModularCms.Api.AndreaSlopFotografie/appsettings.json
@@ -44,9 +44,21 @@
"KnownProxies": []
},
"Website": {
+ // Andrea's site is a prerendered multi-page website (served from wwwroot/web like nginx would), not a SPA.
+ // Chosen here, in configuration, so the host project needs no code of its own and a test can run the same
+ // host in either mode. A missing value means SpaFallback.
+ "Mode": "PrerenderedPages",
// Secure default: every website response carries noindex and /robots.txt disallows all. A
// production instance must set Website__NoIndex=false explicitly.
- "NoIndex": true
+ "NoIndex": true,
+ // The public address of this instance (env: Website__PublicBaseUrl), e.g. https://test.andreaslop.nl on the test
+ // host. Empty = the address the site was built with is served as it is (production).
+ "PublicBaseUrl": "",
+ // The address the website build writes into its pages, sitemap.xml and robots.txt (canonical, og:*, JSON-LD).
+ // When PublicBaseUrl is set to something else, the host replaces it by PublicBaseUrl while serving those files,
+ // so test and production run the same website build. Also used as the data block's siteUrl when
+ // PublicBaseUrl is empty.
+ "AuthoredBaseUrl": "https://andreaslop.nl"
},
// Mail (invitations, password reset, notices). Mail is OFF while Email:Smtp:Host is empty and every
// flow then works as before (copy the link). Enable per environment with environment variables:
@@ -77,6 +89,24 @@
"Cors": {
"AllowedOrigins": []
},
+ // Contact form of the website. OFF: no routes, no database access, until it is released on purpose.
+ // Release conditions, in this order (see aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md):
+ // 1. ForwardedHeaders__KnownProxies__0 = the IP address of the reverse proxy (IIS). Without it every visitor
+ // reaches the API from the proxy's address and the whole site shares ONE rate-limit bucket.
+ // 2. Contact__RecipientEmail (environment variable only; no address belongs in this file) and working mail
+ // (Email__Smtp__*, App__PublicBaseUrl); the sender is the site's From address (Email:FromAddress or the
+ // value chosen in the site settings from Email:AllowedFromAddresses).
+ // 3. Captcha (recommended): Contact__Captcha__Enabled=true, Contact__Captcha__Provider=friendlycaptcha,
+ // Contact__Captcha__SiteKey, and the API key ONLY as the environment variable Contact__Captcha__Secret.
+ // 4. Contact__Enabled=true, then switch the form on in the admin (Berichten).
+ "Contact": {
+ "Enabled": false,
+ "SiteId": "andreaslop",
+ "MinSeconds": 3,
+ "Captcha": {
+ "Enabled": false
+ }
+ },
"RateLimiting": {
"Login": {
"PermitLimit": 5,
@@ -93,6 +123,18 @@
"OfferingsPublic": {
"PermitLimit": 120,
"WindowSeconds": 60
+ },
+ "ContactForm": {
+ "PermitLimit": 5,
+ "WindowSeconds": 600
+ },
+ "ContactToken": {
+ "PermitLimit": 20,
+ "WindowSeconds": 600
+ },
+ "ContactResend": {
+ "PermitLimit": 5,
+ "WindowSeconds": 600
}
},
"SecurityHeaders": {
diff --git a/src/SlpModularCms.Api.SlpSoftware/Program.Coverage.cs b/src/SlpModularCms.Api.SlpSoftware/Program.Coverage.cs
new file mode 100644
index 0000000..5d379c2
--- /dev/null
+++ b/src/SlpModularCms.Api.SlpSoftware/Program.Coverage.cs
@@ -0,0 +1,3 @@
+// Exposes the top-level-statements Program class so WebApplicationFactory can start the
+// composed host in tests (same approach as SlpModularCms.Api/Program.Coverage.cs).
+public partial class Program { }
diff --git a/src/SlpModularCms.Api.SlpSoftware/SlpModularCms.Api.SlpSoftware.csproj b/src/SlpModularCms.Api.SlpSoftware/SlpModularCms.Api.SlpSoftware.csproj
index 3f43383..bad6be2 100644
--- a/src/SlpModularCms.Api.SlpSoftware/SlpModularCms.Api.SlpSoftware.csproj
+++ b/src/SlpModularCms.Api.SlpSoftware/SlpModularCms.Api.SlpSoftware.csproj
@@ -20,6 +20,7 @@
+
diff --git a/src/SlpModularCms.Api.SlpSoftware/appsettings.json b/src/SlpModularCms.Api.SlpSoftware/appsettings.json
index f4dbb4b..ab3dcd8 100644
--- a/src/SlpModularCms.Api.SlpSoftware/appsettings.json
+++ b/src/SlpModularCms.Api.SlpSoftware/appsettings.json
@@ -9,6 +9,19 @@
}
},
"AllowedHosts": "*",
+ "Website": {
+ // Secure default: every response carries noindex and /robots.txt disallows all. A production
+ // instance must set Website__NoIndex=false and Website__PublicBaseUrl=https://slpsoftware.nl explicitly;
+ // robots.txt then allows crawling and points to /sitemap.xml.
+ "NoIndex": true,
+ "PublicBaseUrl": "",
+ // The address the static index.html is written with. On a test instance (PublicBaseUrl set to its own address)
+ // the host swaps it for PublicBaseUrl; on production both are equal, so nothing changes.
+ "AuthoredBaseUrl": "https://slpsoftware.nl",
+ "Sitemap": { "Paths": [ "/", "/privacy" ] },
+ // Only these website paths are pages (200); any other path is a real 404. /api, /admin and assets keep working.
+ "KnownPaths": [ "/", "/privacy" ]
+ },
"ConnectionStrings": {
"DefaultConnection": "Server=;Port=3306;Database=SlpSoftware;Uid=;Pwd="
},
@@ -61,6 +74,24 @@
"Cors": {
"AllowedOrigins": []
},
+ "Contact": {
+ // OFF by default. The contact rate limits are per visitor (see ContactRateLimitPartition), but that only
+ // works with the real client address: behind a reverse proxy (IIS) set ForwardedHeaders__KnownProxies__0 to the
+ // proxy's address first, otherwise all visitors share ONE bucket. Release conditions, in order: that setting;
+ // Contact__RecipientEmail and working mail (environment only); captcha (recommended); then Contact__Enabled=true.
+ // The full list is in the Contact section of the Api.AndreaSlopFotografie appsettings.json.
+ "Enabled": false,
+ "SiteId": "slpsoftware",
+ "MinSeconds": 3,
+ "TokenLifetimeMinutes": 120,
+ "RetentionMonths": 12,
+ "SpamRetentionDays": 30,
+ "MaxSpamRowsPerDay": 200,
+ "MaxBodyBytes": 16384,
+ "Captcha": {
+ "Enabled": false
+ }
+ },
"RateLimiting": {
"Login": {
"PermitLimit": 5,
@@ -77,6 +108,18 @@
"OfferingsPublic": {
"PermitLimit": 120,
"WindowSeconds": 60
+ },
+ "ContactForm": {
+ "PermitLimit": 5,
+ "WindowSeconds": 600
+ },
+ "ContactToken": {
+ "PermitLimit": 20,
+ "WindowSeconds": 600
+ },
+ "ContactResend": {
+ "PermitLimit": 5,
+ "WindowSeconds": 600
}
},
"SecurityHeaders": {
diff --git a/src/SlpModularCms.Api.Tests/AsfInjectionPipelineTests.cs b/src/SlpModularCms.Api.Tests/AsfInjectionPipelineTests.cs
new file mode 100644
index 0000000..c15ccef
--- /dev/null
+++ b/src/SlpModularCms.Api.Tests/AsfInjectionPipelineTests.cs
@@ -0,0 +1,150 @@
+using System.Net;
+using System.Text.Json;
+using FluentAssertions;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using SlpModularCms.Modules.Offerings.Models;
+using SlpModularCms.Modules.Offerings.Services;
+
+namespace SlpModularCms.Api.Tests;
+
+///
+/// The whole chain on the master host with Andrea Slop Fotografie's settings: a prerendered page with the website
+/// build's markers, the real Offerings module over a real database, and the injector. A change made through the
+/// module's services must show in the served HTML at once (cache invalidation), including the ETag.
+///
+public sealed class AsfInjectionFactory : AsfVariantFactory, IDisposable
+{
+ public string WebRoot { get; } = Path.Combine(Path.GetTempPath(), "slp-asf-injection-" + Guid.NewGuid().ToString("N"));
+
+ public AsfInjectionFactory() => Directory.CreateDirectory(Path.Combine(WebRoot, "web"));
+
+ protected override void ConfigureWebHost(IWebHostBuilder builder)
+ {
+ base.ConfigureWebHost(builder);
+ builder.UseWebRoot(WebRoot);
+ builder.UseSetting("Website:PublicBaseUrl", "https://test.andreaslop.nl");
+ builder.ConfigureAppConfiguration((_, config) =>
+ config.AddInMemoryCollection(new Dictionary { ["Website:PublicBaseUrl"] = "https://test.andreaslop.nl" }));
+ }
+
+ protected override void Dispose(bool disposing)
+ {
+ base.Dispose(disposing);
+ if (disposing && Directory.Exists(WebRoot)) Directory.Delete(WebRoot, recursive: true);
+ }
+}
+
+public class AsfInjectionPipelineTests : IClassFixture
+{
+ private const string Page =
+ "" +
+ "" +
+ "" +
+ "" +
+ "baked top" +
+ "baked list" +
+ "
vanaf € 1
";
+
+ private readonly AsfInjectionFactory _factory;
+
+ public AsfInjectionPipelineTests(AsfInjectionFactory factory)
+ {
+ _factory = factory;
+ File.WriteAllText(Path.Combine(factory.WebRoot, "web", "smoke.html"), Page);
+ File.WriteAllText(Path.Combine(factory.WebRoot, "web", "sitemap.xml"), "https://andreaslop.nl/");
+ }
+
+ private async Task InScope(Func> action)
+ {
+ _ = _factory.CreateClient(); // starts the host and migrates the database
+ await using var scope = _factory.Services.CreateAsyncScope();
+ return await action(scope.ServiceProvider);
+ }
+
+ [Fact]
+ public async Task ACmsChange_ShowsInTheServedPage_AtOnce_AndTheAddressIsTheTestHosts()
+ {
+ var client = _factory.CreateClient();
+ var caller = Guid.NewGuid();
+
+ // Clean slate for the slug of this test (the database is shared with other tests).
+ await InScope(async sp =>
+ {
+ var service = sp.GetRequiredService();
+ foreach (var existing in (await service.ListAllAsync()).Where(o => o.Slug == "smoke")) await service.DeleteAsync(Guid.Parse(existing.Id), caller);
+ return 0;
+ });
+
+ // Nothing live: regions are emptied, the data block has no package, the price element is gone, the address is the host's.
+ var empty = await client.GetAsync("/smoke");
+ empty.StatusCode.Should().Be(HttpStatusCode.OK);
+ var emptyBody = await empty.Content.ReadAsStringAsync();
+ emptyBody.Should().Contain("");
+ emptyBody.Should().Contain("https://test.andreaslop.nl/soorten-fotoshoots/smoke").And.NotContain("https://andreaslop.nl");
+ emptyBody.Should().NotContain("\"offers\"").And.NotContain("baked");
+ var etagBefore = empty.Headers.ETag!.Tag;
+
+ // Create the package through the module: the very next request shows it.
+ await InScope(async sp =>
+ {
+ await sp.GetRequiredService().CreateAsync(
+ new CreateOfferingRequest("Smoke", null, "€ 1.250", null, ["Eén uur", "O'Brien & zoon"], "Boek", Slug: "smoke"), caller);
+ await sp.GetRequiredService().CreateAsync(
+ new OfferingBannerRequest("", "Nog twee plekken", Position: "top"), caller);
+ return 0;
+ });
+
+ var live = await client.GetAsync("/smoke");
+ var body = await live.Content.ReadAsStringAsync();
+ live.Headers.ETag!.Tag.Should().NotBe(etagBefore);
+ body.Should().Contain("
Smoke
€ 1.250
");
+ body.Should().Contain("
O'Brien & zoon
");
+ body.Should().Contain("");
+ body.Should().Contain("€ 1.250");
+ body.Should().Contain("\"price\":1250").And.Contain("\"priceCurrency\":\"EUR\"");
+
+ // The data block is the public API's answer plus the site's address.
+ var start = body.IndexOf("", start, StringComparison.Ordinal)];
+ var data = JsonDocument.Parse(json).RootElement;
+ data.GetProperty("siteUrl").GetString().Should().Be("https://test.andreaslop.nl");
+ var api = JsonDocument.Parse(await client.GetStringAsync("/api/v1/offerings")).RootElement;
+ Same(data.GetProperty("offerings"), api).Should().BeTrue("the data block carries the same JSON as GET /api/v1/offerings");
+ var topApi = await client.GetStringAsync("/api/v1/offerings/banner?position=top");
+ Same(data.GetProperty("banners").GetProperty("top"), JsonDocument.Parse(topApi).RootElement).Should().BeTrue();
+ data.GetProperty("banners").GetProperty("bottom").ValueKind.Should().Be(JsonValueKind.Null);
+
+ // A matching ETag is a 304.
+ var conditional = new HttpRequestMessage(HttpMethod.Get, "/smoke");
+ conditional.Headers.IfNoneMatch.Add(live.Headers.ETag);
+ (await client.SendAsync(conditional)).StatusCode.Should().Be(HttpStatusCode.NotModified);
+
+ // Switching the package off removes it again, and the JSON-LD loses its offers.
+ await InScope(async sp =>
+ {
+ var service = sp.GetRequiredService();
+ var id = Guid.Parse((await service.ListAllAsync()).Single(o => o.Slug == "smoke").Id);
+ await service.DeleteAsync(id, caller);
+ return 0;
+ });
+ var gone = await client.GetStringAsync("/smoke");
+ gone.Should().NotContain("data-slug=\"smoke\"").And.NotContain("\"offers\"");
+ }
+
+ // The same JSON value; the writers may differ in escaping (the API writes "€" as is, the data block as €).
+ private static bool Same(JsonElement a, JsonElement b) =>
+ System.Text.Json.Nodes.JsonNode.DeepEquals(System.Text.Json.Nodes.JsonNode.Parse(a.GetRawText()), System.Text.Json.Nodes.JsonNode.Parse(b.GetRawText()));
+
+ [Fact]
+ public async Task TheSitemap_GetsTheTestHostsAddress_ButStillComesFromTheBuild()
+ {
+ var client = _factory.CreateClient();
+
+ var response = await client.GetAsync("/sitemap.xml");
+
+ response.StatusCode.Should().Be(HttpStatusCode.OK);
+ (await response.Content.ReadAsStringAsync()).Should().Contain("https://test.andreaslop.nl/");
+ }
+}
diff --git a/src/SlpModularCms.Api.Tests/AssemblyBehavior.cs b/src/SlpModularCms.Api.Tests/AssemblyBehavior.cs
new file mode 100644
index 0000000..688f14b
--- /dev/null
+++ b/src/SlpModularCms.Api.Tests/AssemblyBehavior.cs
@@ -0,0 +1,6 @@
+// The pipeline tests start several real hosts against MariaDB/MySQL. The MySql.Data driver keeps a static,
+// non-thread-safe dictionary that is touched while a connection is opened (MySql.Data.Common.Ssl.StartSSL), so opening
+// connections from several hosts at the same time can fail with "Operations that change non-concurrent collections
+// must have exclusive access". The suite is small and fast (the pure unit tests take about a second), so the whole
+// assembly runs serially instead of guessing which classes touch the driver.
+[assembly: CollectionBehavior(DisableTestParallelization = true)]
diff --git a/src/SlpModularCms.Api.Tests/PipelineTests.cs b/src/SlpModularCms.Api.Tests/PipelineTests.cs
index 5b9e182..ddeb709 100644
--- a/src/SlpModularCms.Api.Tests/PipelineTests.cs
+++ b/src/SlpModularCms.Api.Tests/PipelineTests.cs
@@ -102,5 +102,15 @@ public class PipelineTests : IClassFixture
// request instead, which would otherwise mask a rate limiter that silently stopped
// engaging).
last!.StatusCode.Should().Be(HttpStatusCode.TooManyRequests);
+
+ // The rejection tells the client when to retry and carries a machine-readable body with
+ // only the standard fields (nothing about the limiter, the policy or the caller).
+ last.Headers.TryGetValues("Retry-After", out var retryAfter).Should().BeTrue();
+ int.Parse(retryAfter!.Single()).Should().BeGreaterThanOrEqualTo(1);
+ last.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
+ var body = await last.Content.ReadAsStringAsync();
+ using var json = System.Text.Json.JsonDocument.Parse(body);
+ json.RootElement.EnumerateObject().Select(p => p.Name).Should().BeEquivalentTo(["type", "title", "status"]);
+ json.RootElement.GetProperty("status").GetInt32().Should().Be(429);
}
}
diff --git a/src/SlpModularCms.Api.Tests/SiteContractTests.cs b/src/SlpModularCms.Api.Tests/SiteContractTests.cs
new file mode 100644
index 0000000..b634a8e
--- /dev/null
+++ b/src/SlpModularCms.Api.Tests/SiteContractTests.cs
@@ -0,0 +1,165 @@
+using FluentAssertions;
+using Microsoft.Extensions.Configuration;
+
+namespace SlpModularCms.Api.Tests;
+
+///
+/// What every site (client project) must look like, checked from its files alone: the modules it references and
+/// the defaults it commits. The sites carry no logic of their own (all behaviour lives in Core and the modules and
+/// is tested against the master SlpModularCms.Api host), so a site can only go wrong in its composition:
+/// a module reference that is missing or too much, or an unsafe default. These tests need no database.
+///
+public class SiteContractTests
+{
+ public static IEnumerable
+
+
+
+
+
diff --git a/src/SlpModularCms.Core.Tests/TextFixtures/Sample.Texts.en.json b/src/SlpModularCms.Core.Tests/TextFixtures/Sample.Texts.en.json
new file mode 100644
index 0000000..b52e894
--- /dev/null
+++ b/src/SlpModularCms.Core.Tests/TextFixtures/Sample.Texts.en.json
@@ -0,0 +1,7 @@
+{
+ "sample": {
+ "hello": "Hello {name}",
+ "nested": { "deep": "Deep" },
+ "plain": "Plain text"
+ }
+}
diff --git a/src/SlpModularCms.Core.Tests/TextFixtures/Sample.Texts.nl.json b/src/SlpModularCms.Core.Tests/TextFixtures/Sample.Texts.nl.json
new file mode 100644
index 0000000..407895a
--- /dev/null
+++ b/src/SlpModularCms.Core.Tests/TextFixtures/Sample.Texts.nl.json
@@ -0,0 +1,8 @@
+{
+ "sample": {
+ "hello": "Hallo {name}",
+ "onlynl": "Alleen nl",
+ "nested": { "deep": "Diep" },
+ "plain": "Gewone tekst"
+ }
+}
diff --git a/src/SlpModularCms.Core.Tests/Texts/CoreTextsTests.cs b/src/SlpModularCms.Core.Tests/Texts/CoreTextsTests.cs
new file mode 100644
index 0000000..1379610
--- /dev/null
+++ b/src/SlpModularCms.Core.Tests/Texts/CoreTextsTests.cs
@@ -0,0 +1,62 @@
+using FluentAssertions;
+using SlpModularCms.Core.Texts;
+using Xunit;
+
+namespace SlpModularCms.Core.Tests.Texts;
+
+/// The texts in Core: every declared key has a text in every language, with the same placeholders, and no text is unused.
+public class CoreTextsTests
+{
+ [Fact]
+ public void TheCoreTextFiles_MatchTheDeclaredKeys_InDutchAndEnglish()
+ => TextAudit.Verify(typeof(TextCatalog).Assembly, TextAudit.KeysOf(typeof(CoreTexts)), "nl", "en").Should().BeEmpty();
+
+ [Theory]
+ [InlineData("core.identity.auth.invalidCredentials", "Ongeldige inloggegevens.")]
+ [InlineData("core.identity.auth.invalidRefreshToken", "Ongeldig refresh token.")]
+ [InlineData("core.identity.auth.tokenReuse", "Mogelijk token misbruik gedetecteerd. Alle sessies zijn beëindigd.")]
+ [InlineData("core.identity.auth.userNotFound", "Gebruiker niet gevonden.")]
+ [InlineData("core.identity.invitation.userExists", "Er bestaat al een gebruiker met dit e-mailadres.")]
+ [InlineData("core.identity.invitation.openInvitation", "Er staat al een openstaande uitnodiging voor dit e-mailadres.")]
+ [InlineData("core.identity.invitation.invalid", "Ongeldige of verlopen uitnodiging.")]
+ [InlineData("core.identity.invitation.accepted", "Account succesvol ingesteld. Je kunt nu inloggen.")]
+ [InlineData("core.identity.setup.alreadyInitialized", "Systeem is al geïnitialiseerd.")]
+ [InlineData("core.identity.setup.completed", "Systeem succesvol geïnitialiseerd. De eerste eigenaar is aangemaakt.")]
+ public void TheDutchIdentityMessages_AreTheOnesThatWereInTheCode(string key, string expected)
+ => TextCatalog.Default.Get(new TextKey(key)).Should().Be(expected);
+
+ [Fact]
+ public void TheMessagesThatCarryTheErrorsOfTheIdentityStore_KeepTheirFormat()
+ {
+ TextCatalog.Default.Get(CoreTexts.Identity.Invitation.CreateFailed, args: ("errors", "a, b")).Should().Be("Kan gebruiker niet aanmaken: a, b");
+ TextCatalog.Default.Get(CoreTexts.Identity.Setup.CreateOwnerFailed, args: ("errors", "a, b")).Should().Be("Fout bij aanmaken eigenaar: a, b");
+ }
+
+ [Theory]
+ [InlineData("core.identity.auth.invalidEmail", "Enter a valid e-mail address.")]
+ [InlineData("core.identity.auth.resetRequested", "If this address belongs to an account, an e-mail with a link has been sent.")]
+ [InlineData("core.identity.auth.linkInvalid", "This link is invalid or has expired.")]
+ [InlineData("core.identity.auth.passwordSet", "Password set. You can sign in now.")]
+ [InlineData("core.identity.auth.passwordRejected", "The password does not meet the requirements.")]
+ [InlineData("core.identity.users.emailInUse", "Email is already in use.")]
+ [InlineData("core.identity.users.unsupportedLanguage", "Unsupported language.")]
+ [InlineData("core.identity.users.updateProfileFailed", "Failed to update profile.")]
+ [InlineData("core.identity.users.lastOwner", "At least one Owner must remain.")]
+ [InlineData("core.identity.users.cannotChangeOwnActive", "You cannot change your own active status.")]
+ [InlineData("core.identity.users.updateUserFailed", "Failed to update user.")]
+ [InlineData("core.identity.users.cannotDeleteSelf", "You cannot delete your own account.")]
+ [InlineData("core.identity.users.deleteUserFailed", "Failed to delete user.")]
+ public void TheEnglishTexts_OfTheFormerlyEnglishOnlyMessages_AreTheOldWording(string key, string expected)
+ => TextCatalog.Default.Get(new TextKey(key), "en").Should().Be(expected);
+
+ [Fact]
+ public void TheInternalErrorDetail_IsTheOldDutchSentence()
+ => TextCatalog.Default.Get(CoreTexts.Errors.Internal).Should().Be("Er is een interne serverfout opgetreden.");
+
+ [Fact]
+ public void TheFormerlyEnglishOnlyMessages_AreNowDutchInTheDefaultLanguage()
+ {
+ TextCatalog.Default.Get(CoreTexts.Identity.Users.CannotDeleteSelf).Should().Be("Je kunt je eigen account niet verwijderen.");
+ TextCatalog.Default.Get(CoreTexts.Identity.Auth.ResetRequested).Should().StartWith("Als dit adres bij een account hoort");
+ }
+}
diff --git a/src/SlpModularCms.Core.Tests/Texts/TextAuditTests.cs b/src/SlpModularCms.Core.Tests/Texts/TextAuditTests.cs
new file mode 100644
index 0000000..c314bc5
--- /dev/null
+++ b/src/SlpModularCms.Core.Tests/Texts/TextAuditTests.cs
@@ -0,0 +1,68 @@
+using FluentAssertions;
+using SlpModularCms.Core.Texts;
+using Xunit;
+
+namespace SlpModularCms.Core.Tests.Texts;
+
+public class TextAuditTests
+{
+ private static readonly System.Reflection.Assembly Fixtures = typeof(TextAuditTests).Assembly;
+
+ public static class AllSampleKeys
+ {
+ public static readonly TextKey Hello = new("sample.hello", "name");
+ public static readonly TextKey Plain = new("sample.plain");
+ public static readonly TextKey Deep = new("sample.nested.deep");
+ public static readonly TextKey OnlyNl = new("sample.onlynl");
+ }
+
+ public static class WrongKeys
+ {
+ public static readonly TextKey HelloWithoutPlaceholder = new("sample.hello");
+ public static readonly TextKey Plain = new("sample.plain");
+ public static readonly TextKey Misspelled = new("sample.plian");
+ }
+
+ [Fact]
+ public void KeysOf_FindsEveryDeclaredKey_FieldsAndNestedTypes()
+ => TextAudit.KeysOf(typeof(AllSampleKeys)).Select(k => k.Path).Should().BeEquivalentTo(
+ ["sample.hello", "sample.plain", "sample.nested.deep", "sample.onlynl"]);
+
+ [Fact]
+ public void AFileSetThatMatchesTheKeys_HasNoProblems_ForTheLanguagesThatHaveAFile()
+ {
+ var keys = TextAudit.KeysOf(typeof(AllSampleKeys)).Where(k => k.Path != "sample.onlynl").ToList();
+
+ TextAudit.Verify(Fixtures, keys, "nl", "en").Should().Contain(p => p.Contains("sample.onlynl") && p.StartsWith("[nl]"),
+ "the nl file has a text that no key declares");
+ }
+
+ [Fact]
+ public void AKeyMissingInALanguage_IsReported()
+ {
+ var problems = TextAudit.Verify(Fixtures, TextAudit.KeysOf(typeof(AllSampleKeys)), "nl", "en");
+
+ problems.Should().Contain("[en] missing text for key 'sample.onlynl'");
+ problems.Should().NotContain(p => p.StartsWith("[nl]"));
+ }
+
+ [Fact]
+ public void DifferingPlaceholders_AndMisspelledOrOrphanKeys_AreReported()
+ {
+ var problems = TextAudit.Verify(Fixtures, TextAudit.KeysOf(typeof(WrongKeys)), "nl", "en");
+
+ problems.Should().Contain(p => p.Contains("'sample.hello'") && p.Contains("placeholders {name}"));
+ problems.Should().Contain("[nl] missing text for key 'sample.plian'");
+ problems.Should().Contain(p => p.Contains("'sample.onlynl'") && p.Contains("not declared"));
+ }
+
+ [Fact]
+ public void ARequiredLanguageWithoutAFile_IsReported()
+ => TextAudit.Verify(Fixtures, TextAudit.KeysOf(typeof(AllSampleKeys)), "nl", "en", "de")
+ .Should().Contain(p => p.Contains("language 'de'"));
+
+ [Fact]
+ public void ADuplicateKeyDeclaration_IsReported()
+ => TextAudit.Verify(Fixtures, [new TextKey("sample.plain"), new TextKey("sample.plain")], "nl")
+ .Should().Contain("key 'sample.plain' is declared more than once");
+}
diff --git a/src/SlpModularCms.Core.Tests/Texts/TextCatalogTests.cs b/src/SlpModularCms.Core.Tests/Texts/TextCatalogTests.cs
new file mode 100644
index 0000000..d713b10
--- /dev/null
+++ b/src/SlpModularCms.Core.Tests/Texts/TextCatalogTests.cs
@@ -0,0 +1,215 @@
+using FluentAssertions;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Options;
+using SlpModularCms.Core.Texts;
+using Xunit;
+
+namespace SlpModularCms.Core.Tests.Texts;
+
+public sealed class TextCatalogTests : IDisposable
+{
+ private static readonly TextKey Hello = new("sample.hello", "name");
+ private static readonly TextKey Plain = new("sample.plain");
+ private static readonly TextKey OnlyNl = new("sample.onlynl");
+ private static readonly TextKey Deep = new("sample.nested.deep");
+ private static readonly TextKey Nope = new("sample.does.not.exist");
+
+ private readonly string _folder = Path.Combine(Path.GetTempPath(), "slp-texts-" + Guid.NewGuid().ToString("N"));
+ private readonly List _errors = [];
+
+ public void Dispose()
+ {
+ if (Directory.Exists(_folder)) Directory.Delete(_folder, recursive: true);
+ }
+
+ private sealed class ListLogger(List sink) : ILogger
+ {
+ public IDisposable? BeginScope(TState state) where TState : notnull => null;
+ public bool IsEnabled(LogLevel logLevel) => true;
+ public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter)
+ {
+ if (logLevel >= LogLevel.Warning) sink.Add(formatter(state, exception));
+ }
+ }
+
+ private sealed class FixedOverrides(Dictionary<(string Language, string Key), string> values) : ITextOverrides
+ {
+ public string? Find(string language, string key) => values.GetValueOrDefault((language, key));
+ }
+
+ private TextCatalog Catalog(string defaultLanguage = "nl", string? directory = null, params ITextOverrides[] overrides) => new(
+ Options.Create(new TextsOptions { DefaultLanguage = defaultLanguage, Directory = directory }),
+ [new TextAssembly(typeof(TextCatalogTests).Assembly)],
+ overrides,
+ new ListLogger(_errors));
+
+ private void WriteFolder(string file, string json)
+ {
+ Directory.CreateDirectory(_folder);
+ File.WriteAllText(Path.Combine(_folder, file), json);
+ }
+
+ [Fact]
+ public void TheDefaultLanguageIsUsed_WhenNoneIsAsked_AndPlaceholdersAreFilled()
+ {
+ Catalog().Get(Hello, args: ("name", "Jan")).Should().Be("Hallo Jan");
+ Catalog("en").Get(Hello, args: ("name", "Jan")).Should().Be("Hello Jan");
+ }
+
+ [Theory]
+ [InlineData("en", "Hello Jan")]
+ [InlineData("EN", "Hello Jan")]
+ [InlineData("en-GB", "Hello Jan")]
+ [InlineData("nl", "Hallo Jan")]
+ public void AnAskedLanguage_WinsOverTheDefault(string asked, string expected)
+ => Catalog().Get(Hello, asked, ("name", "Jan")).Should().Be(expected);
+
+ [Fact]
+ public void NestedJson_BecomesDottedKeys()
+ => Catalog().Get(Deep).Should().Be("Diep");
+
+ [Fact]
+ public void AnUnknownLanguage_FallsBackToTheDefault_AndIsReportedOnce()
+ {
+ var catalog = Catalog();
+
+ catalog.Get(Plain, "fr").Should().Be("Gewone tekst");
+ catalog.Get(Plain, "fr").Should().Be("Gewone tekst");
+
+ _errors.Should().ContainSingle().Which.Should().Contain("sample.plain").And.Contain("fr");
+ }
+
+ [Fact]
+ public void ATextMissingInTheAskedLanguage_FallsBack_AndIsReportedOnce()
+ {
+ var catalog = Catalog();
+
+ catalog.Get(OnlyNl, "en").Should().Be("Alleen nl");
+ catalog.Get(OnlyNl, "en");
+
+ _errors.Should().ContainSingle();
+ }
+
+ [Fact]
+ public void AMissingKey_ReturnsTheKeyPath_NeverThrows_AndIsReportedOnce()
+ {
+ var catalog = Catalog();
+
+ catalog.Get(Nope).Should().Be("sample.does.not.exist");
+ catalog.Get(Nope).Should().Be("sample.does.not.exist");
+
+ _errors.Should().ContainSingle().Which.Should().Contain("sample.does.not.exist");
+ }
+
+ [Fact]
+ public void AMissingValueForAPlaceholder_LeavesItInTheText_AndIsReported()
+ {
+ Catalog().Get(Hello).Should().Be("Hallo {name}");
+
+ _errors.Should().ContainSingle().Which.Should().Contain("name");
+ }
+
+ [Fact]
+ public void ValuesAreFormattedInvariantly_AndNullBecomesEmpty()
+ {
+ Catalog().Get(Hello, args: ("name", 1234.5m)).Should().Be("Hallo 1234.5");
+ Catalog().Get(Hello, args: ("name", null)).Should().Be("Hallo ");
+ }
+
+ // ---- layers ----
+
+ [Fact]
+ public void TheOverrideFolder_WinsOverTheEmbeddedText_KeyByKey()
+ {
+ WriteFolder("nl.json", "{ \"sample\": { \"plain\": \"Aangepast\" } }");
+
+ var catalog = Catalog(directory: _folder);
+
+ catalog.Get(Plain).Should().Be("Aangepast");
+ catalog.Get(OnlyNl).Should().Be("Alleen nl", "keys the folder does not mention keep their embedded text");
+ catalog.Get(Plain, "en").Should().Be("Plain text");
+ }
+
+ [Fact]
+ public void TheOverrideFolder_AcceptsAnyFileNamedForALanguage()
+ {
+ WriteFolder("site.en.json", "{ \"sample\": { \"plain\": \"Custom\" } }");
+
+ Catalog(directory: _folder).Get(Plain, "en").Should().Be("Custom");
+ }
+
+ [Fact]
+ public void ABrokenOverrideFile_IsIgnoredAndLogged_TheEmbeddedTextsStay()
+ {
+ WriteFolder("nl.json", "{ not json");
+
+ Catalog(directory: _folder).Get(Plain).Should().Be("Gewone tekst");
+
+ _errors.Should().ContainSingle().Which.Should().Contain("nl.json");
+ }
+
+ [Fact]
+ public void AMissingOverrideFolder_IsNoProblem_ButIsMentioned()
+ {
+ Catalog(directory: Path.Combine(_folder, "nope")).Get(Plain).Should().Be("Gewone tekst");
+
+ _errors.Should().ContainSingle().Which.Should().Contain("does not exist");
+ }
+
+ [Fact]
+ public void ADatabaseStyleOverride_WinsOverTheFolderAndTheEmbeddedText()
+ {
+ WriteFolder("nl.json", "{ \"sample\": { \"plain\": \"Map\" } }");
+ var overrides = new FixedOverrides(new() { [("nl", "sample.plain")] = "Database" });
+
+ var catalog = Catalog(directory: _folder, overrides: overrides);
+
+ catalog.Get(Plain).Should().Be("Database");
+ catalog.Get(Plain, "en").Should().Be("Plain text");
+ }
+
+ // ---- files ----
+
+ [Fact]
+ public void Flatten_AcceptsCommentsAndTrailingCommas_AndRejectsNonTextValues()
+ {
+ using var ok = new MemoryStream("{ // note\n \"a\": { \"b\": \"x\", }, }"u8.ToArray());
+ TextCatalog.Flatten(ok).Should().Equal(new Dictionary { ["a.b"] = "x" });
+
+ using var number = new MemoryStream("{ \"a\": 1 }"u8.ToArray());
+ var act = () => TextCatalog.Flatten(number);
+ act.Should().Throw().WithMessage("*'a'*");
+ }
+
+ [Theory]
+ [InlineData("SlpModularCms.Core.Texts.nl.json", "nl")]
+ [InlineData("SlpModularCms.Modules.Offerings.Texts.EN.json", "en")]
+ [InlineData("SlpModularCms.Core.Tests.TextFixtures.Sample.Texts.nl.json", "nl")]
+ [InlineData("SlpModularCms.Core.Hosting.WebsitePlaceholder.html", null)]
+ [InlineData("SlpModularCms.Core.Texts.nl.txt", null)]
+ public void OnlyTextResources_AreRecognised(string resource, string? language)
+ => TextCatalog.LanguageOfResource(resource).Should().Be(language);
+
+ [Fact]
+ public void PlaceholdersIn_ListsTheNames()
+ => TextCatalog.PlaceholdersIn("Hallo {name}, {site} {name} {1} { x }").Should().BeEquivalentTo(["name", "site"]);
+
+ // ---- registration ----
+
+ [Fact]
+ public void TheRealRegistration_ResolvesTheCatalog_WithCoreAssembly()
+ {
+ var services = new ServiceCollection();
+ services.AddLogging();
+ var configuration = new ConfigurationBuilder()
+ .AddInMemoryCollection(new Dictionary { ["Texts:DefaultLanguage"] = "en" }).Build();
+ services.AddCmsTexts(configuration).AddCmsTextsFrom(typeof(TextCatalogTests).Assembly);
+
+ var catalog = services.BuildServiceProvider().GetRequiredService();
+
+ catalog.DefaultLanguage.Should().Be("en");
+ catalog.Get(Plain).Should().Be("Plain text");
+ }
+}
diff --git a/src/SlpModularCms.Core/Availability/MasterControlledAvailabilityException.cs b/src/SlpModularCms.Core/Availability/MasterControlledAvailabilityException.cs
index e68e815..263db8c 100644
--- a/src/SlpModularCms.Core/Availability/MasterControlledAvailabilityException.cs
+++ b/src/SlpModularCms.Core/Availability/MasterControlledAvailabilityException.cs
@@ -4,10 +4,11 @@ namespace SlpModularCms.Core.Availability;
/// Thrown when an attempt is made to change the local availability status while a
/// master CMS has taken control of this instance's gate (e.g. set it to NotAvailable).
/// The local status change would have no visible effect since the master gate
-/// overrides it, so it's rejected outright instead of silently doing nothing.
+/// overrides it, so it's rejected outright instead of silently doing nothing. The message is technical (logs); the
+/// sentence shown to the administrator is the text availability.masterControlled.
///
public class MasterControlledAvailabilityException(string? masterDisableMessage)
- : InvalidOperationException("De beschikbaarheid van dit systeem wordt beheerd door de Master-CMS en kan hier niet worden gewijzigd.")
+ : InvalidOperationException("Availability is controlled by the master CMS and cannot be changed locally.")
{
public string? MasterDisableMessage { get; } = masterDisableMessage;
}
diff --git a/src/SlpModularCms.Core/Availability/PublicSiteEndpointAttribute.cs b/src/SlpModularCms.Core/Availability/PublicSiteEndpointAttribute.cs
new file mode 100644
index 0000000..b63669a
--- /dev/null
+++ b/src/SlpModularCms.Core/Availability/PublicSiteEndpointAttribute.cs
@@ -0,0 +1,15 @@
+namespace SlpModularCms.Core.Availability;
+
+///
+/// Marks an endpoint as public site functionality that stays reachable while the CMS is
+/// switched off, in maintenance or blocked by the master.
+///
+///
+/// The availability statuses exist to stop the CMS (changing data and settings through the
+/// admin). Visitors of the public website must keep working, so the few endpoints the website
+/// itself calls carry this marker. The gate is deny-by-default: an endpoint without the marker
+/// is blocked, and the marker must never be placed on an endpoint that requires authorization.
+/// It is read from the endpoint metadata by AvailabilityMiddleware.
+///
+[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
+public sealed class PublicSiteEndpointAttribute : Attribute;
diff --git a/src/SlpModularCms.Core/Email/MailTemplateRenderer.cs b/src/SlpModularCms.Core/Email/MailTemplateRenderer.cs
index cbeab6f..a0ecfd4 100644
--- a/src/SlpModularCms.Core/Email/MailTemplateRenderer.cs
+++ b/src/SlpModularCms.Core/Email/MailTemplateRenderer.cs
@@ -1,6 +1,7 @@
using System.Net;
using System.Text;
using Microsoft.Extensions.Options;
+using SlpModularCms.Core.Texts;
namespace SlpModularCms.Core.Email;
@@ -24,133 +25,83 @@ public sealed class LanguageResolver(IOptions options) : ILangua
}
///
-/// One shared layout, texts per language kept in code. Every dynamic value is HTML-encoded for the
-/// HTML part; the subject and plain-text part carry the raw values (no markup there). A missing
-/// language or key falls back to Dutch. Table layout and inline CSS only, so it renders in mail clients.
+/// One shared layout; the sentences come from the text catalogue (core.mail.*, see ).
+/// Every dynamic value is HTML-encoded for the HTML part; the subject and plain-text part carry the raw values (no
+/// markup there). A missing language or key falls back to Dutch. Table layout and inline CSS only, so it renders in
+/// mail clients.
///
-public sealed class MailTemplateRenderer : IMailTemplateRenderer
+public sealed class MailTemplateRenderer(ITextCatalog texts) : IMailTemplateRenderer
{
private const string DefaultColour = "#1f2937";
- private sealed record Texts(
- string Subject, string Heading, string Intro, string? Button, string? Note, string Footer);
+ private sealed record KindKeys(TextKey Subject, TextKey Heading, TextKey Intro, TextKey? Button, TextKey? Note);
- // {0} = site name, {1} = role, {2} = minutes/hours text. Keys: kind, then language.
- private static readonly Dictionary> Catalog = new()
+ private static readonly Dictionary Kinds = new()
{
- [MailKind.Invitation] = new()
- {
- ["nl"] = new("Uitnodiging voor {0}", "Je bent uitgenodigd",
- "Je bent uitgenodigd om een account aan te maken voor {0}. Kies met de knop hieronder je wachtwoord om je account te activeren.",
- "Account activeren", "Deze link is {2} geldig. Is hij verlopen, vraag dan de beheerder om een nieuwe uitnodiging.",
- "Deze mail is automatisch verstuurd door {0}."),
- ["en"] = new("Invitation to {0}", "You have been invited",
- "You have been invited to create an account for {0}. Use the button below to choose your password and activate your account.",
- "Activate account", "This link is valid for {2}. If it has expired, ask the administrator for a new invitation.",
- "This message was sent automatically by {0}.")
- },
- [MailKind.NewInvitationLink] = new()
- {
- ["nl"] = new("Nieuwe uitnodigingslink voor {0}", "Je hebt een nieuwe uitnodigingslink",
- "Er is een nieuwe uitnodigingslink voor je aangemaakt voor {0}. De vorige link werkt niet meer.",
- "Account activeren", "Deze link is {2} geldig.",
- "Deze mail is automatisch verstuurd door {0}."),
- ["en"] = new("New invitation link for {0}", "You have a new invitation link",
- "A new invitation link has been created for you for {0}. The previous link no longer works.",
- "Activate account", "This link is valid for {2}.",
- "This message was sent automatically by {0}.")
- },
- [MailKind.PasswordReset] = new()
- {
- ["nl"] = new("Wachtwoord opnieuw instellen voor {0}", "Wachtwoord opnieuw instellen",
- "Er is gevraagd om het wachtwoord van je account bij {0} opnieuw in te stellen. Gebruik de knop hieronder om een nieuw wachtwoord te kiezen.",
- "Nieuw wachtwoord kiezen", "Deze link is {2} geldig en werkt één keer. Heb jij dit niet gevraagd? Negeer deze mail dan: je wachtwoord blijft ongewijzigd.",
- "Deze mail is automatisch verstuurd door {0}."),
- ["en"] = new("Reset your password for {0}", "Reset your password",
- "A request was made to reset the password of your account at {0}. Use the button below to choose a new password.",
- "Choose a new password", "This link is valid for {2} and works once. Did you not ask for this? Ignore this message: your password stays unchanged.",
- "This message was sent automatically by {0}.")
- },
- [MailKind.AccountDeactivated] = new()
- {
- ["nl"] = new("Je account bij {0} is gedeactiveerd", "Account gedeactiveerd",
- "Een beheerder heeft je account bij {0} gedeactiveerd. Je kunt niet meer inloggen.",
- null, "Denk je dat dit niet klopt? Neem dan contact op met de beheerder.",
- "Deze mail is automatisch verstuurd door {0}."),
- ["en"] = new("Your account at {0} has been deactivated", "Account deactivated",
- "An administrator has deactivated your account at {0}. You can no longer sign in.",
- null, "Think this is a mistake? Please contact the administrator.",
- "This message was sent automatically by {0}.")
- },
- [MailKind.AccountReactivated] = new()
- {
- ["nl"] = new("Je account bij {0} is weer actief", "Account weer actief",
- "Een beheerder heeft je account bij {0} weer geactiveerd. Je kunt weer inloggen.",
- "Inloggen", null, "Deze mail is automatisch verstuurd door {0}."),
- ["en"] = new("Your account at {0} is active again", "Account active again",
- "An administrator has reactivated your account at {0}. You can sign in again.",
- "Sign in", null, "This message was sent automatically by {0}.")
- },
- [MailKind.RoleChanged] = new()
- {
- ["nl"] = new("Je rol bij {0} is gewijzigd", "Rol gewijzigd",
- "Een beheerder heeft je rol bij {0} gewijzigd naar: {1}.",
- null, "Denk je dat dit niet klopt? Neem dan contact op met de beheerder.",
- "Deze mail is automatisch verstuurd door {0}."),
- ["en"] = new("Your role at {0} has changed", "Role changed",
- "An administrator has changed your role at {0} to: {1}.",
- null, "Think this is a mistake? Please contact the administrator.",
- "This message was sent automatically by {0}.")
- }
- };
-
- private static readonly Dictionary> Roles = new()
- {
- ["nl"] = new() { ["Owner"] = "Eigenaar", ["Administrator"] = "Beheerder", ["User"] = "Gebruiker" },
- ["en"] = new() { ["Owner"] = "Owner", ["Administrator"] = "Administrator", ["User"] = "User" }
+ [MailKind.Invitation] = new(CoreTexts.Mail.Invitation.Subject, CoreTexts.Mail.Invitation.Heading,
+ CoreTexts.Mail.Invitation.Intro, CoreTexts.Mail.Invitation.Button, CoreTexts.Mail.Invitation.Note),
+ [MailKind.NewInvitationLink] = new(CoreTexts.Mail.NewInvitationLink.Subject, CoreTexts.Mail.NewInvitationLink.Heading,
+ CoreTexts.Mail.NewInvitationLink.Intro, CoreTexts.Mail.NewInvitationLink.Button, CoreTexts.Mail.NewInvitationLink.Note),
+ [MailKind.PasswordReset] = new(CoreTexts.Mail.PasswordReset.Subject, CoreTexts.Mail.PasswordReset.Heading,
+ CoreTexts.Mail.PasswordReset.Intro, CoreTexts.Mail.PasswordReset.Button, CoreTexts.Mail.PasswordReset.Note),
+ [MailKind.AccountDeactivated] = new(CoreTexts.Mail.AccountDeactivated.Subject, CoreTexts.Mail.AccountDeactivated.Heading,
+ CoreTexts.Mail.AccountDeactivated.Intro, null, CoreTexts.Mail.AccountDeactivated.Note),
+ [MailKind.AccountReactivated] = new(CoreTexts.Mail.AccountReactivated.Subject, CoreTexts.Mail.AccountReactivated.Heading,
+ CoreTexts.Mail.AccountReactivated.Intro, CoreTexts.Mail.AccountReactivated.Button, null),
+ [MailKind.RoleChanged] = new(CoreTexts.Mail.RoleChanged.Subject, CoreTexts.Mail.RoleChanged.Heading,
+ CoreTexts.Mail.RoleChanged.Intro, null, CoreTexts.Mail.RoleChanged.Note),
+ // The details (name, e-mail address, subject, message) come from MailModel.Details; nothing the visitor
+ // typed is part of the subject, which stays fixed text.
+ [MailKind.ContactMessage] = new(CoreTexts.Mail.ContactMessage.Subject, CoreTexts.Mail.ContactMessage.Heading,
+ CoreTexts.Mail.ContactMessage.Intro, null, null),
};
public RenderedMail Render(MailKind kind, string language, MailModel model)
{
var lang = MailLanguages.Normalize(language) ?? MailLanguages.Dutch;
- var perKind = Catalog[kind];
- var t = perKind.TryGetValue(lang, out var found) ? found : perKind[MailLanguages.Dutch];
+ var keys = Kinds[kind];
var site = Plain(model.SiteName);
var role = RoleName(lang, model.Detail);
var validity = Validity(lang, model.ValidForMinutes);
- string F(string template) => string.Format(template, site, role, validity);
+ string T(TextKey key) => texts.Get(key, lang, ("site", site), ("role", role), ("validity", validity));
- var subject = Plain(F(t.Subject));
- var heading = F(t.Heading);
- var intro = F(t.Intro);
- var note = t.Note is null ? null : F(t.Note);
- var footer = F(t.Footer);
+ var subject = Plain(T(keys.Subject));
+ var heading = T(keys.Heading);
+ var intro = T(keys.Intro);
+ var note = keys.Note is null ? null : T(keys.Note);
+ var footer = T(CoreTexts.Mail.Footer);
var greeting = string.IsNullOrWhiteSpace(model.RecipientName)
? null
- : (lang == "en" ? $"Hello {model.RecipientName.Trim()}," : $"Hallo {model.RecipientName.Trim()},");
+ : texts.Get(CoreTexts.Mail.Greeting, lang, ("name", model.RecipientName.Trim()));
+ var button = keys.Button is null ? null : T(keys.Button);
var colour = (EmailAddressRules.IsValidColour(model.BrandColor) ? model.BrandColor! : DefaultColour).ToLowerInvariant();
- var hasAction = t.Button is not null && !string.IsNullOrEmpty(model.ActionUrl);
+ var hasAction = button is not null && !string.IsNullOrEmpty(model.ActionUrl);
- return new RenderedMail(subject, BuildHtml(model, site, colour, greeting, heading, intro, hasAction ? t.Button : null, note, footer),
- BuildText(greeting, heading, intro, hasAction ? model.ActionUrl : null, note, footer));
+ return new RenderedMail(subject, BuildHtml(model, site, colour, greeting, heading, intro, hasAction ? button : null, note, footer),
+ BuildText(greeting, heading, intro, hasAction ? model.ActionUrl : null, note, footer, model.Details));
}
- private static string RoleName(string lang, string? key) =>
- key is not null && Roles[lang].TryGetValue(key, out var name) ? name : (key ?? "");
+ private string RoleName(string lang, string? key) => key switch
+ {
+ "Owner" => texts.Get(CoreTexts.Mail.RoleOwner, lang),
+ "Administrator" => texts.Get(CoreTexts.Mail.RoleAdministrator, lang),
+ "User" => texts.Get(CoreTexts.Mail.RoleUser, lang),
+ _ => key ?? "",
+ };
- private static string Validity(string lang, int? minutes)
+ private string Validity(string lang, int? minutes)
{
if (minutes is null) return "";
var m = minutes.Value;
if (m % 60 == 0)
{
var h = m / 60;
- return lang == "en" ? $"{h} hour{(h == 1 ? "" : "s")}" : $"{h} uur";
+ return texts.Get(h == 1 ? CoreTexts.Mail.ValidityHoursOne : CoreTexts.Mail.ValidityHoursOther, lang, ("count", h));
}
- return lang == "en" ? $"{m} minutes" : $"{m} minuten";
+ return texts.Get(CoreTexts.Mail.ValidityMinutes, lang, ("count", m));
}
/// For the subject and text: no markup, and no line breaks (a subject is a header).
@@ -224,6 +175,7 @@ public sealed class MailTemplateRenderer : IMailTemplateRenderer
sb.Append($"
{E(heading)}
");
if (greeting is not null) sb.Append($"
{E(greeting)}
");
sb.Append($"
{E(intro)}
");
+ AppendDetails(sb, model.Details);
if (button is not null && !string.IsNullOrEmpty(model.ActionUrl))
{
// 'Bulletproof' button: a table cell with bgcolor + style, a visible border, and the link filling the cell.
@@ -240,12 +192,50 @@ public sealed class MailTemplateRenderer : IMailTemplateRenderer
return sb.ToString();
}
- private static string BuildText(string? greeting, string heading, string intro, string? url, string? note, string footer)
+ ///
+ /// Labelled values (label on its own line in the muted colour, value below it). Only classes the dark block already
+ /// overrides carry an inline colour (.mail-muted, .mail-rule); the values inherit the card's text colour, so they
+ /// read in light and dark. Every value is HTML-encoded; line breaks in a value become <br>.
+ ///
+ private static void AppendDetails(StringBuilder sb, IReadOnlyList? details)
+ {
+ if (details is null || details.Count == 0) return;
+
+ sb.Append("
");
+ foreach (var detail in details)
+ {
+ var value = E(detail.Value.Replace("\r\n", "\n").Replace('\r', '\n')).Replace("\n", " ");
+ sb.Append("
");
+ sb.Append($"
{E(detail.Label)}
");
+ sb.Append($"
{value}
");
+ sb.Append("
");
+ }
+ sb.Append("
");
+ }
+
+ private static string BuildText(
+ string? greeting, string heading, string intro, string? url, string? note, string footer,
+ IReadOnlyList? details = null)
{
var sb = new StringBuilder();
sb.AppendLine(heading).AppendLine();
if (greeting is not null) sb.AppendLine(greeting).AppendLine();
sb.AppendLine(intro).AppendLine();
+ if (details is { Count: > 0 })
+ {
+ foreach (var detail in details)
+ {
+ // Plain text: a label line, then the value indented two spaces per line, so a visitor's own
+ // '--' line or fake headings cannot imitate the layout of the mail.
+ sb.Append(detail.Label).AppendLine(":");
+ foreach (var line in detail.Value.Replace("\r\n", "\n").Replace('\r', '\n').Split('\n'))
+ {
+ sb.Append(" ").AppendLine(line);
+ }
+
+ sb.AppendLine();
+ }
+ }
if (url is not null) sb.AppendLine(url).AppendLine();
if (note is not null) sb.AppendLine(note).AppendLine();
sb.AppendLine("--").AppendLine(footer);
diff --git a/src/SlpModularCms.Core/Email/MailTypes.cs b/src/SlpModularCms.Core/Email/MailTypes.cs
index 7ad0759..f9a899e 100644
--- a/src/SlpModularCms.Core/Email/MailTypes.cs
+++ b/src/SlpModularCms.Core/Email/MailTypes.cs
@@ -33,7 +33,9 @@ public sealed record OutgoingMail(
string HtmlBody,
string? TextBody = null,
string? FromAddress = null,
- string? FromName = null);
+ string? FromName = null,
+ string? ReplyToAddress = null,
+ string? ReplyToName = null);
public enum MailKind
{
@@ -42,9 +44,14 @@ public enum MailKind
PasswordReset,
AccountDeactivated,
AccountReactivated,
- RoleChanged
+ RoleChanged,
+ /// A visitor's message from the contact form, mailed to the site owner (details + Reply-To).
+ ContactMessage
}
+/// One labelled value in the details block of a mail (for example the visitor's name). Always encoded in HTML.
+public sealed record MailDetail(string Label, string Value);
+
/// Values the template needs. carries the role key for .
public sealed record MailModel(
string SiteName,
@@ -54,7 +61,8 @@ public sealed record MailModel(
string? Detail = null,
string? LogoUrl = null,
string? BrandColor = null,
- string? LogoDarkUrl = null);
+ string? LogoDarkUrl = null,
+ IReadOnlyList? Details = null);
public sealed record RenderedMail(string Subject, string Html, string Text);
diff --git a/src/SlpModularCms.Core/Email/SmtpEmailSender.cs b/src/SlpModularCms.Core/Email/SmtpEmailSender.cs
index f24012e..56b06b2 100644
--- a/src/SlpModularCms.Core/Email/SmtpEmailSender.cs
+++ b/src/SlpModularCms.Core/Email/SmtpEmailSender.cs
@@ -40,6 +40,14 @@ public sealed class SmtpEmailSender(IOptions options, ILogger
public static void ConfigurePipeline(WebApplication app, ModuleOrchestrator orchestrator, CmsHostOptions options)
{
+ var websiteMode = app.Services.GetService()?.Mode ?? options.ResolveWebsiteMode(app.Configuration);
// Bring the Core schema up to date before serving any traffic. Runs before the module
// middleware below, because the Data Protection keys table lives in this context and the
// modules resolve an IDataProtector as soon as they start. Fails fast: a host that cannot
@@ -115,6 +122,13 @@ public static class CmsHost
// which is almost all of the HTML this host serves.
app.UseCmsSecurityHeaders();
+ // SpaFallback sites: X-Robots-Tag on test hosts and generated robots.txt / sitemap.xml. After the
+ // security headers (so these answers carry them) and before the static files short-circuit.
+ if (websiteMode == WebsiteMode.SpaFallback)
+ {
+ app.UseCmsSpaSeo();
+ }
+
app.UseRateLimiter();
// 6. Configure Pipeline
@@ -131,12 +145,12 @@ public static class CmsHost
// wwwroot/admin/index.html + assets -> CMS admin build (see frontend/, copied in on publish)
// Registered before the module middleware below: static files short-circuit the pipeline, so
// anything that must observe them has to come first.
- app.UseCmsStaticContent(options.WebsiteMode);
+ app.UseCmsStaticContent(websiteMode);
// WebsiteMode.PrerenderedPages: the website replaces the SPA-style website mount, at the same
// position and for the same reason (it answers before the module middleware and the API).
// It never handles /admin, /api/v1 or /health.
- if (options.WebsiteMode == WebsiteMode.PrerenderedPages)
+ if (websiteMode == WebsiteMode.PrerenderedPages)
{
app.UseCmsPrerenderedSite();
}
@@ -166,11 +180,11 @@ public static class CmsHost
// SPA fallbacks so client-side routes (e.g. /admin/dashboard) resolve to the right index.html
// instead of 404ing. The "nonfile" constraint keeps genuinely missing assets (e.g. /admin/assets/x.js) as 404s.
- app.MapCmsSpaFallbacks(options.WebsiteMode);
+ app.MapCmsSpaFallbacks(websiteMode);
// WebsiteMode.PrerenderedPages: lowest-priority endpoint, so unknown website paths get
// 404.html with status 404 only AFTER every API route and the admin fallback had their turn.
- if (options.WebsiteMode == WebsiteMode.PrerenderedPages)
+ if (websiteMode == WebsiteMode.PrerenderedPages)
{
app.MapCmsWebsiteNotFound();
}
diff --git a/src/SlpModularCms.Core/Hosting/CmsHostOptions.cs b/src/SlpModularCms.Core/Hosting/CmsHostOptions.cs
index 5141426..796aabf 100644
--- a/src/SlpModularCms.Core/Hosting/CmsHostOptions.cs
+++ b/src/SlpModularCms.Core/Hosting/CmsHostOptions.cs
@@ -24,8 +24,41 @@ public enum WebsiteMode
/// , is how a Client project opts into different behaviour.
/// Defaults reproduce the behaviour every existing Client project already has.
///
+/// The website mode this host started with, decided once while the services were registered.
+///
+/// The pipeline reads this instead of resolving the mode a second time, so the registered services and the
+/// pipeline can never disagree about the mode (a half-configured host that registers SPA services but runs the
+/// prerendered pipeline would fail on its first request).
+///
+public sealed record WebsiteModeSelection(WebsiteMode Mode);
+
public sealed class CmsHostOptions
{
- /// How the public website is served. Defaults to .
+ ///
+ /// How the public website is served when the configuration does not say. Defaults to
+ /// . The configuration value Website:Mode wins over this
+ /// (see ), so a site picks its mode in its appsettings.json and a test
+ /// can run the same host in either mode.
+ ///
public WebsiteMode WebsiteMode { get; init; } = WebsiteMode.SpaFallback;
+
+ ///
+ /// The mode to use: Website:Mode (SpaFallback or PrerenderedPages, case-insensitive)
+ /// when set, otherwise . An unknown value stops the host at start-up instead of
+ /// silently serving the website the wrong way.
+ ///
+ public WebsiteMode ResolveWebsiteMode(Microsoft.Extensions.Configuration.IConfiguration configuration)
+ {
+ var value = configuration["Website:Mode"];
+ if (string.IsNullOrWhiteSpace(value))
+ return WebsiteMode;
+
+ // Names only: a bare number would also parse, and "1" is not something a person means by a mode.
+ var name = Enum.GetNames().FirstOrDefault(n => string.Equals(n, value.Trim(), StringComparison.OrdinalIgnoreCase));
+ if (name is not null)
+ return Enum.Parse(name);
+
+ throw new InvalidOperationException(
+ $"Website:Mode '{value}' is not valid; use '{nameof(WebsiteMode.SpaFallback)}' or '{nameof(WebsiteMode.PrerenderedPages)}'.");
+ }
}
diff --git a/src/SlpModularCms.Core/Hosting/Security/CspPolicyCatalog.cs b/src/SlpModularCms.Core/Hosting/Security/CspPolicyCatalog.cs
index c7c4b9e..78f566b 100644
--- a/src/SlpModularCms.Core/Hosting/Security/CspPolicyCatalog.cs
+++ b/src/SlpModularCms.Core/Hosting/Security/CspPolicyCatalog.cs
@@ -47,25 +47,43 @@ public static class CspPolicyCatalog
IEnumerable allowedScriptOrigins,
IEnumerable allowedConnectOrigins,
IEnumerable? allowedSiteScriptOrigins = null,
- IEnumerable? allowedSiteConnectOrigins = null)
+ IEnumerable? allowedSiteConnectOrigins = null,
+ IEnumerable? allowedSiteFrameOrigins = null)
{
var connect = Join("'self'", allowedConnectOrigins);
if (StrictSite.Equals(policy, StringComparison.OrdinalIgnoreCase))
{
+ var directives = new List
+ {
+ "default-src 'self'",
+ $"script-src {Join("'self'", allowedSiteScriptOrigins ?? [])}",
+ // Same documented exception as Strict: inline style attributes only, no script.
+ "style-src 'self' 'unsafe-inline'",
+ "img-src 'self' data:",
+ "font-src 'self'",
+ $"connect-src {Join("'self'", allowedSiteConnectOrigins ?? [])}",
+ };
+
+ // Only present when a site embeds a third party (for example the captcha widget's iframe); without
+ // origins the header stays byte-for-byte what it was (frames then fall back to default-src 'self').
+ var frames = (allowedSiteFrameOrigins ?? [])
+ .Where(origin => !string.IsNullOrWhiteSpace(origin)).ToArray();
+ if (frames.Length > 0)
+ {
+ directives.Add($"frame-src {Join("'self'", frames)}");
+ }
+
+ directives.AddRange(
+ [
+ "object-src 'none'",
+ "base-uri 'self'",
+ "form-action 'self'",
+ "frame-ancestors 'none'",
+ ]);
+
return new SecurityHeaderSet(
- ContentSecurityPolicy: string.Join("; ",
- "default-src 'self'",
- $"script-src {Join("'self'", allowedSiteScriptOrigins ?? [])}",
- // Same documented exception as Strict: inline style attributes only, no script.
- "style-src 'self' 'unsafe-inline'",
- "img-src 'self' data:",
- "font-src 'self'",
- $"connect-src {Join("'self'", allowedSiteConnectOrigins ?? [])}",
- "object-src 'none'",
- "base-uri 'self'",
- "form-action 'self'",
- "frame-ancestors 'none'"),
+ ContentSecurityPolicy: string.Join("; ", directives),
FrameOptions: "DENY",
ReferrerPolicy: ReferrerPolicyValue);
}
diff --git a/src/SlpModularCms.Core/Hosting/Security/CspPolicyProvider.cs b/src/SlpModularCms.Core/Hosting/Security/CspPolicyProvider.cs
index 48758b4..2408e2f 100644
--- a/src/SlpModularCms.Core/Hosting/Security/CspPolicyProvider.cs
+++ b/src/SlpModularCms.Core/Hosting/Security/CspPolicyProvider.cs
@@ -35,7 +35,8 @@ public sealed class CspPolicyProvider : ICspPolicyProvider
value.AllowedScriptOrigins,
value.AllowedConnectOrigins,
value.AllowedSiteScriptOrigins,
- value.AllowedSiteConnectOrigins),
+ value.AllowedSiteConnectOrigins,
+ value.AllowedSiteFrameOrigins),
StringComparer.OrdinalIgnoreCase);
}
diff --git a/src/SlpModularCms.Core/Hosting/Security/SecurityHeadersExtensions.cs b/src/SlpModularCms.Core/Hosting/Security/SecurityHeadersExtensions.cs
index 2d3f99a..ba31a93 100644
--- a/src/SlpModularCms.Core/Hosting/Security/SecurityHeadersExtensions.cs
+++ b/src/SlpModularCms.Core/Hosting/Security/SecurityHeadersExtensions.cs
@@ -24,7 +24,8 @@ public static class SecurityHeadersExtensions
$"SecurityHeaders:DefaultPolicy is not a known policy. Known policies: {string.Join(", ", CspPolicyCatalog.KnownPolicies)}.")
.Validate(
options => options.AllowedScriptOrigins.Concat(options.AllowedConnectOrigins)
- .Concat(options.AllowedSiteScriptOrigins).Concat(options.AllowedSiteConnectOrigins).All(IsOrigin),
+ .Concat(options.AllowedSiteScriptOrigins).Concat(options.AllowedSiteConnectOrigins)
+ .Concat(options.AllowedSiteFrameOrigins).All(IsOrigin),
"SecurityHeaders origins must be absolute scheme-and-host values without a path, e.g. https://analytics.example.com.")
// ValidateOnStart, not a constructor check: options resolve lazily, so without this
// a typo in PathPolicies is discovered when the first request arrives — by which
@@ -73,13 +74,15 @@ public static class SecurityHeadersExtensions
logger.LogInformation(
"HTTP security headers enabled. Default policy: {DefaultPolicy}. Path policies: {PathPolicies}. " +
"Allowed script origins: {ScriptOrigins}. Allowed connect origins: {ConnectOrigins}. " +
- "Allowed site script origins: {SiteScriptOrigins}. Allowed site connect origins: {SiteConnectOrigins}.",
+ "Allowed site script origins: {SiteScriptOrigins}. Allowed site connect origins: {SiteConnectOrigins}. " +
+ "Allowed site frame origins: {SiteFrameOrigins}.",
options.DefaultPolicy,
string.Join(", ", options.PathPolicies.Select(rule => $"{rule.PathPrefix} => {rule.Policy}")),
Describe(options.AllowedScriptOrigins),
Describe(options.AllowedConnectOrigins),
Describe(options.AllowedSiteScriptOrigins),
- Describe(options.AllowedSiteConnectOrigins));
+ Describe(options.AllowedSiteConnectOrigins),
+ Describe(options.AllowedSiteFrameOrigins));
return app.UseMiddleware();
}
diff --git a/src/SlpModularCms.Core/Hosting/Security/SecurityHeadersOptions.cs b/src/SlpModularCms.Core/Hosting/Security/SecurityHeadersOptions.cs
index ec6ccf9..67d01da 100644
--- a/src/SlpModularCms.Core/Hosting/Security/SecurityHeadersOptions.cs
+++ b/src/SlpModularCms.Core/Hosting/Security/SecurityHeadersOptions.cs
@@ -70,6 +70,13 @@ public sealed class SecurityHeadersOptions
/// analytics and error-reporting hosts called directly by the website).
///
public IList AllowedSiteConnectOrigins { get; set; } = [];
+
+ ///
+ /// Origins added as a frame-src directive under the StrictSite policy only (for example the Friendly
+ /// Captcha widget, which renders in an iframe: https://global.frcapi.com, https://eu.frcapi.com).
+ /// Empty (the default) adds no frame-src at all, so existing headers are unchanged.
+ ///
+ public IList AllowedSiteFrameOrigins { get; set; } = [];
}
/// One entry in .
diff --git a/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs b/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs
index ee4b76b..ddce67a 100644
--- a/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs
+++ b/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs
@@ -1,3 +1,4 @@
+using SlpModularCms.Core.Texts;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Policy;
@@ -36,6 +37,9 @@ public static class ServiceCollectionExtensions
{
public static IServiceCollection AddCoreInfrastructure(this IServiceCollection services, IConfiguration configuration)
{
+ // Static user-facing texts (mails, messages, host pages), see docs/translation-files.md
+ services.AddCmsTexts(configuration);
+
// 1. Database
services.AddDbContext(options =>
{
@@ -171,7 +175,7 @@ public static class ServiceCollectionExtensions
// Without this callback a brute-force attempt against /api/v1/Auth/login returns 429
// and leaves NO trace anywhere — the one rate limiter this application has would be
// entirely unobservable, and the alert rule for it could never fire.
- options.OnRejected = (context, _) =>
+ options.OnRejected = async (context, cancellationToken) =>
{
var logger = context.HttpContext.RequestServices
.GetRequiredService()
@@ -202,11 +206,24 @@ public static class ServiceCollectionExtensions
var window = configuration.GetValue($"RateLimiting:{section}:WindowSeconds", 60);
waitSeconds = policyName == "refresh" ? window / 4.0 : window;
}
+ // Every 429 carries a retry hint, also for policies that report no wait (the contact and offerings policies).
+ waitSeconds ??= 60;
if (waitSeconds is not null)
context.HttpContext.Response.Headers.RetryAfter =
Math.Max(1, (int)Math.Ceiling(waitSeconds.Value)).ToString(System.Globalization.CultureInfo.InvariantCulture);
- return ValueTask.CompletedTask;
+
+ // Machine-readable body with only the standard type/title/status: nothing about the limiter, the policy or the caller.
+ await context.HttpContext.Response.WriteAsJsonAsync(
+ new Microsoft.AspNetCore.Mvc.ProblemDetails
+ {
+ Type = "https://www.rfc-editor.org/rfc/rfc6585#section-4",
+ Title = "Too many requests",
+ Status = StatusCodes.Status429TooManyRequests,
+ },
+ options: null,
+ contentType: "application/problem+json",
+ cancellationToken: cancellationToken);
};
// Every named policy is partitioned per client address (ClientPartitionKey). Behind a
diff --git a/src/SlpModularCms.Core/Hosting/StaticContentExtensions.cs b/src/SlpModularCms.Core/Hosting/StaticContentExtensions.cs
index 779a7a2..65a1e2d 100644
--- a/src/SlpModularCms.Core/Hosting/StaticContentExtensions.cs
+++ b/src/SlpModularCms.Core/Hosting/StaticContentExtensions.cs
@@ -1,9 +1,12 @@
+using SlpModularCms.Core.Texts;
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Options;
+using SlpModularCms.Core.Hosting.Website;
namespace SlpModularCms.Core.Hosting;
@@ -136,7 +139,28 @@ public static class StaticContentExtensions
{
if (File.Exists(websiteIndex))
{
+ // Website:KnownPaths (optional): only those paths are real pages; the rest is a real 404, still
+ // with the SPA shell as body so the app can render its own not-found page.
+ var known = context.RequestServices.GetService>()?.Value.KnownPaths;
+ if (known is { Count: > 0 }
+ && !known.Select(SpaSeoExtensions.NormalizePath).Contains(SpaSeoExtensions.NormalizePath(context.Request.Path.Value ?? "/")))
+ {
+ context.Response.StatusCode = StatusCodes.Status404NotFound;
+ }
+
context.Response.ContentType = "text/html; charset=utf-8";
+
+ // Modules fill marker comments in index.html (e.g. the current offerings); cached, with an ETag.
+ var injector = context.RequestServices.GetService();
+ var page = injector is null
+ ? null
+ : await injector.GetAsync(websiteIndex, context.Request, context.RequestAborted);
+ if (page is not null)
+ {
+ await InjectedPageWriter.WriteAsync(context, page, "text/html; charset=utf-8");
+ return;
+ }
+
await context.Response.SendFileAsync(websiteIndex);
return;
}
@@ -187,14 +211,24 @@ public static class StaticContentExtensions
await using var stream = typeof(StaticContentExtensions).Assembly
.GetManifestResourceStream(PlaceholderResourceName);
+ var texts = HttpTexts.From(context);
+
if (stream is null)
{
- await context.Response.WriteAsync("Nog geen website geplaatst" +
- "