Author SHA1 Message Date
remco c9130ecd2d chore(deps): update All dependencies
CI / check (pull_request) Successful in 24s
CI / release (pull_request) Skipped
CI / deploy (pull_request) Skipped
2026-08-03 00:00:47 +00:00
1603 changed files with 30642 additions and 269115 deletions

No files matched your search

View File
Whitespace-only changes.
-46
View File
@@ -1,46 +0,0 @@
.git
.gitignore
.next
node_modules
coverage
storage
prod.log
update.log
.pm2
# Only the pnpm lockfile is used. Ignore other lockfile formats and stray
# package managers so they never taint the build context by accident.
package-lock.json
yarn.lock
bun.lockb
.npmrc.bak
# Installation secrets must never enter any image layer (including migrations).
.env
.env.*
**/.env
**/.env.*
!.env.example
*.pem
*.key
*.tsbuildinfo
# Runtime write targets; bound as RW volumes at runtime (see docker-compose.yml)
public/nitro-assets
public/swf
.deploy.lock
logs
# Other installation data and local tool artifacts
public/cache
public/tmp
db_backup_*.sql
*.log
.codex
.agents
.docker-install
.docker-install.tmp.*
.env.install.*
build-reports
test-results
playwright-report
blob-report
-14
View File
@@ -1,14 +0,0 @@
# http://editorconfig.org
root = true
[*]
indent_style = tab
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.{js,ts,tsx,jsx,json,md}]
indent_style = space
indent_size = 2
+7 -57
View File
@@ -11,72 +11,30 @@ DATABASE_CONNECT_TIMEOUT_MS=5000
# --- REDIS (Lightning Fast Caching & Sessions) ---
REDIS_URL=redis://127.0.0.1:6379?connect_timeout=2
REDIS_CACHE_TTL_DEFAULT=7200
# In-process cache entries kept per instance, evicted least-recently-used. Raise
# it if hot keys are evicted while memory headroom remains (default 2000).
CACHE_MEMORY_MAX_ENTRIES=2000
# Renders kept per imaging cache directory, counted as .img/.json pairs. A sweep
# every 5 minutes brings an over-budget directory back to 90% of this (default 20000).
IMAGING_CACHE_MAX_ENTRIES=20000
# --- CORE RUNTIME & PERFORMANCE FLAGS ---
NODE_ENV=production
PORT=3002
NEXT_TELEMETRY_DISABLED=1
UV_THREADPOOL_SIZE=16
# Production requires this kill switch plus housekeeping.preview.access.
HOUSEKEEPING_NEXT_PREVIEW_ENABLED=false
# --- HOTEL & URLS ---
HOTEL_NAME=EPIC WEB CONTROL
APP_URL=http://localhost:3002
NEXT_PUBLIC_APP_URL=http://localhost:3002
AUTH_URL=http://localhost:3002
# --- IMAGER ---
# Avatar imager: Polaris-imager (avatar-imaging-pixinode) serves /avatarimage on 8082.
IMAGING_UPSTREAM_URL=http://127.0.0.1:8082/avatarimage
# Runtime values: changing these only requires recreating the container.
IMAGER_URL=http://127.0.0.1:8082/avatarimage
BADGE_URL=/swf/c_images/album1584
# Legacy NEXT_PUBLIC_IMAGER_URL / NEXT_PUBLIC_BADGE_URL are still read at runtime.
IMAGING_UPSTREAM_URL=http://127.0.0.1:3030/imaging
NEXT_PUBLIC_IMAGER_URL=http://localhost:3002/imaging
# --- SECURITY & HASHING ---
AUTH_SECRET=your-super-secret-auth-key-change-this-min-32-chars
APP_KEY=base64:your-app-key-here=
# Bcrypt cost factor for new password hashes.
BCRYPT_COST=12
# --- ANTI-DDOS (app-layer gate, production only) ---
# On by default in production. Set to "false" to disable (not recommended).
ANTI_DDOS_ENABLED=true
# Per-category request thresholds over the given window (per client IP).
ANTI_DDOS_PAGES_LIMIT=300
ANTI_DDOS_PAGES_WINDOW_SEC=60
ANTI_DDOS_API_LIMIT=600
ANTI_DDOS_API_WINDOW_SEC=60
ANTI_DDOS_AUTH_LIMIT=20
ANTI_DDOS_AUTH_WINDOW_SEC=60
# Whole-site safety valve per window (sheds everything for global_halt_ms when hit).
ANTI_DDOS_GLOBAL_LIMIT=18000
ANTI_DDOS_GLOBAL_WINDOW_SEC=60
ANTI_DDOS_GLOBAL_HALT_MS=10000
# Violations accumulate inside this window before an IP is hard-blocked.
ANTI_DDOS_VIOLATION_WINDOW_SEC=600
ANTI_DDOS_MAX_VIOLATIONS=10
# Escalation tiers "minViolations:ttlSeconds" — how long an offender stays blocked.
ANTI_DDOS_BLOCK_TIERS=5:600,20:3600,50:86400
# --- CLOUDFLARE API (automatic edge blocks, optional) ---
# When set, the anti-DDoS gate automatically mirrors hard-blocked IPs to the
# zone's IP Access Rules so repeat offenders are dropped at the Cloudflare
# edge (works on every plan, incl. Free). Token permissions required:
# Zone > Zone > Read and Zone > Firewall > Edit
CLOUDFLARE_API_TOKEN=
CLOUDFLARE_ZONE_ID=
# Runtime toggle; leave true to auto-create Cloudflare blocks at the block
# threshold. Also overridable live from the admin panel.
CLOUDFLARE_AUTO_BLOCK_ENABLED=true
# Override for tests/staging (production uses the public endpoint by default).
CLOUDFLARE_API_BASE_URL=https://api.cloudflare.com/client/v4
CONVERT_PASSWORDS=true
ARGON2_MEMORY_KB=65536
ARGON2_ITERATIONS=4
ARGON2_PARALLELISM=1
# --- PATHS ---
BADGE_UPLOAD_DIR=./public/assets/images/badges
@@ -114,11 +72,3 @@ PAYPAL_API=https://api-m.sandbox.paypal.com
# --- LOGGING ---
LOG_LEVEL=error
# --- BYPARR (Cloudflare bypass for clone sources) ---
BYPARR_URL=http://localhost:8191
# Catalog Studio export: dedicated clean clone on Beta-3 with Git push credentials.
CATALOG_GIT_CHECKOUT=
# Persistent directory shared by CMS and worker, outside the catalog clone.
CATALOG_GIT_STATE_DIR=
-2
View File
@@ -1,2 +0,0 @@
.husky/* text eol=lf
*.sh text eol=lf
+513 -185
View File
@@ -1,201 +1,529 @@
name: CI
on:
push:
branches: [main, master, "codex/**"]
tags: ["v*"]
branches:
- main
tags:
- "v*"
pull_request:
branches: [main, master]
branches:
- main
workflow_dispatch:
# Reuse the Playwright browsers that ship with the host runner (snapped to
# the root HOME cache instead of a fresh per-job HOME) so `playwright install`
# is a near-instant no-op instead of a ~100s CDN download on every run.
env:
PLAYWRIGHT_BROWSERS_PATH: /opt/ms-playwright
jobs:
# ─────────────────────────────────────────────
# Fast quality gate: toolchain, install, dependabot audit,
# lint, i18n contracts & typecheck. No heavy test suites here.
# Draait op de host (self-hosted) waar Node 26 + pnpm 11
# geïnstalleerd zijn en internet beschikbaar is.
# ─────────────────────────────────────────────
check:
runs-on: self-hosted
if: startsWith(gitea.ref_name, 'v') == false
runs-on: shell
steps:
- name: Checkout
uses: actions/checkout@v4
with:
repository: ${{ gitea.repository }}
token: ${{ gitea.token }}
- name: Toolchain check
run: node scripts/check-node-toolchain.mjs
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Dependency security audit
run: pnpm deps:audit
- name: Lint
run: pnpm biome:lint
- name: CMS translation contracts
run: pnpm i18n:check
- name: Typecheck
run: pnpm typecheck
# ─────────────────────────────────────────────
# Test suites. Parallel jobs (host runner capacity >= 3) so unit,
# integration and UI tests each get a worker instead of running
# back-to-back inside the check job (~2min wall-time saving).
# ─────────────────────────────────────────────
tests-unit:
needs: check
runs-on: self-hosted
steps:
- name: Checkout
uses: actions/checkout@v4
with:
repository: ${{ gitea.repository }}
token: ${{ gitea.token }}
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Unit & coverage tests
env:
SKIP_ENV_VALIDATION: 1
NODE_ENV: test
DATABASE_URL: "mysql://test:test@localhost:3306/test?charset=utf8mb4"
REDIS_URL: "redis://127.0.0.1:6379?connect_timeout=2"
AUTH_SECRET: "ci-test-secret-key-that-is-long-enough"
BCRYPT_ROUNDS: 4
- name: Typecheck, lint, and test
run: |
if [ -x /usr/bin/time ]; then
/usr/bin/time -f 'Tests: %e seconds; peak process RSS: %M KiB' pnpm test:coverage --maxWorkers=4
else
time pnpm test:coverage --maxWorkers=4
set -e
WORK="$(mktemp -d /var/tmp/epicnext-ci.XXXXXX)"
cleanup() { rm -rf "${WORK}"; }
trap cleanup EXIT
echo "--- CI checks (${WORK}) ---"
git clone --depth 50 \
/docker/gitea/gitea/git/repositories/remco/epicnext-cms.git \
"${WORK}"
cd "${WORK}"
REF="${{ gitea.sha }}"
if [ -z "${REF}" ]; then
echo "ERROR: missing gitea.sha" >&2
exit 1
fi
git fetch --depth 50 origin "${REF}"
git checkout -f "${REF}"
export SKIP_ENV_VALIDATION=1
export NODE_ENV=test
export DATABASE_URL="mysql://test:test@localhost:3306/test?charset=utf8mb4"
export AUTH_SECRET="ci-test-secret-key-that-is-long-enough"
export REDIS_URL="redis://127.0.0.1:6379?connect_timeout=1"
export BCRYPT_ROUNDS=4
pnpm install --frozen-lockfile
# Types come from the committed Drizzle schema (src/db/schema.ts).
pnpm biome:lint
pnpm typecheck
pnpm test
echo "--- CI checks passed ---"
deploy:
needs: check
if: gitea.event_name == 'push' && gitea.ref_name == 'main'
runs-on: shell
steps:
- name: Deploy
run: |
set -e
exec 9>/var/tmp/epic_web_control_deploy.lock
flock -n 9 || { echo "ERROR: Another deployment is already running! Cancelling."; exit 1; }
echo "--- Deploying ---"
LIVE="/var/www/atom-nexst"
STAGE=""
CUTOVER_STARTED=0
error_handler() {
cd /var/www/atom-nexst 2>/dev/null || cd / || true
echo "!!! DEPLOYMENT FAILED on line $1 !!!" >&2
# Leave the healthy current process untouched when staging fails.
# Restart only when cutover has already stopped or replaced it.
if [ "${CUTOVER_STARTED}" = "1" ]; then
if [ -d "${LIVE}/.next.prev" ]; then
echo "Rolling back .next to previous artifact..." >&2
rm -rf "${LIVE}/.next" || true
mv "${LIVE}/.next.prev" "${LIVE}/.next" || true
fi
if [ -d "${LIVE}/node_modules.prev" ]; then
echo "Rolling back node_modules to previous artifact..." >&2
rm -rf "${LIVE}/node_modules" || true
mv "${LIVE}/node_modules.prev" "${LIVE}/node_modules" || true
fi
pm2 restart next --update-env 2>/dev/null || pm2 start pnpm --name "next" -- start 2>/dev/null || true
fi
if [ -n "${STAGE}" ] && [ -d "${STAGE}" ]; then
git -C "${LIVE}" worktree remove --force "${STAGE}" 2>/dev/null || rm -rf "${STAGE}" || true
fi
exit 1
}
trap 'error_handler $LINENO' ERR
docker image prune -f
DEPLOY_USER="$(id -un)"
DEPLOY_GROUP="$(id -gn)"
sudo chown -R "${DEPLOY_USER}:${DEPLOY_GROUP}" "${LIVE}" 2>/dev/null || true
git config --global --add safe.directory "${LIVE}"
git -C "${LIVE}" remote set-url origin /docker/gitea/gitea/git/repositories/remco/epicnext-cms.git/
echo "Fetching origin/main..."
git -C "${LIVE}" fetch origin --prune
echo "Clearing sticky git index bits (if any)..."
STICKY_LIST="$(git -C "${LIVE}" ls-files -v | awk '/^[a-zS]/ {print substr($0,3)}' || true)"
if [ -n "${STICKY_LIST}" ]; then
echo "${STICKY_LIST}" | while IFS= read -r f; do
[ -n "$f" ] || continue
git -C "${LIVE}" update-index --no-skip-worktree --no-assume-unchanged -- "$f" 2>/dev/null || true
done
fi
tests-integration:
needs: check
runs-on: self-hosted
export APP_VERSION="$(git -C "${LIVE}" rev-parse --short origin/main)"
echo "APP_VERSION=${APP_VERSION}"
STAGE="/var/tmp/atom-nexst-stage-${APP_VERSION}"
echo "Preparing stage worktree at ${STAGE} (live site stays up)..."
git -C "${LIVE}" worktree remove --force "${STAGE}" 2>/dev/null || rm -rf "${STAGE}" || true
git -C "${LIVE}" worktree add --detach "${STAGE}" origin/main
# Production env stays on the live tree; stage only needs a symlink for build/migrate.
ln -sfn "${LIVE}/.env" "${STAGE}/.env"
if ! grep -qE '^[[:space:]]*REDIS_URL=.+' "${LIVE}/.env" 2>/dev/null; then
echo "WARNING: REDIS_URL is unset in ${LIVE}/.env" >&2
echo "WARNING: Rate limits, site-settings cache, and JWT invalidation cache will be in-process only." >&2
fi
cd "${STAGE}"
rm -f tsconfig.tsbuildinfo .tsbuildinfo
find . -maxdepth 3 -name '*.tsbuildinfo' -delete 2>/dev/null || true
rm -rf .output dist .next .next/types .next/dev
# Restore build cache from last deploy so Turbopack can do
# incremental compilation (much faster rebuilds).
if [ -d "${LIVE}/.next/cache" ]; then
mkdir -p .next/cache
cp -r "${LIVE}/.next/cache/." .next/cache/
fi
# Stage shares MySQL with the live app + emulator. Keep the stage pool
# tiny so install/test/build cannot exhaust max_connections.
export DATABASE_POOL_SIZE="${DEPLOY_DATABASE_POOL_SIZE:-5}"
echo "STAGE DATABASE_POOL_SIZE=${DATABASE_POOL_SIZE}"
pnpm install --frozen-lockfile
# Types come from the committed Drizzle schema (src/db/schema.ts).
export BCRYPT_ROUNDS=4
pnpm typecheck
# Validate production env (AUTH_SECRET, DATABASE_URL, …) during build.
# Do not set SKIP_ENV_VALIDATION here — that flag is for tests/tooling only.
pnpm build
if [ ! -d "${STAGE}/.next" ]; then
echo "ERROR: stage build produced no .next/" >&2
exit 1
fi
echo "Migrating staged release while the current app stays online..."
cd "${STAGE}"
MIGRATE_OK=0
for i in $(seq 1 10); do
if pnpm db:migrate; then
MIGRATE_OK=1
break
fi
echo "migrate attempt ${i}/10 failed (likely DB connections), retrying..."
sleep 5
done
if [ "${MIGRATE_OK}" != "1" ]; then
echo "ERROR: db:migrate failed after retries" >&2
exit 1
fi
cd "${LIVE}"
echo "Hard reset live tree to origin/main (no nuclear src wipe)..."
git reset --hard origin/main
# Keep env, uploads, runtime-imported furni assets, and deps we are
# about to replace from stage. The app can write furni files while it
# remains online during staging, so cleaning those paths races with
# active imports and can fail with "Directory not empty".
git clean -fd \
-e .env -e .env.local -e .env.production -e .env*.local \
-e storage -e public/cache \
-e public/swf/dcr/hof_furni \
-e public/nitro-assets/bundled/furniture \
-e node_modules -e node_modules.prev -e .next -e .next.prev
if ! git diff --exit-code HEAD -- src >/dev/null; then
echo "ERROR: live src/ still differs from HEAD after reset:" >&2
git diff --stat HEAD -- src >&2 || true
exit 1
fi
echo "Verified live src/ matches HEAD"
# Next.js prefers an already-set process PORT over .env. PM2 may still
# have PORT=3000 from an older start, while .env (and nginx) expect 3002.
# Export PORT before start so the process matches health checks.
DEPLOY_PORT="$(grep -E '^[[:space:]]*PORT=' "${LIVE}/.env" 2>/dev/null | tail -1 | cut -d= -f2- || true)"
DEPLOY_PORT="$(printf '%s' "${DEPLOY_PORT}" | tr -cd '0-9')"
DEPLOY_PORT="${DEPLOY_PORT:-3002}"
export PORT="${DEPLOY_PORT}"
echo "PM2/health PORT=${PORT}"
free_tcp_port() {
local port="$1"
[ -n "${port}" ] || return 0
if command -v fuser >/dev/null 2>&1; then
fuser -k "${port}/tcp" 2>/dev/null || true
elif command -v lsof >/dev/null 2>&1; then
# Portable fallback when fuser is unavailable.
lsof -tiTCP:"${port}" -sTCP:LISTEN 2>/dev/null | xargs -r kill -9 2>/dev/null || true
fi
}
echo "Cutover: atomically swap artifacts and restart on PORT=${PORT}..."
CUTOVER_STARTED=1
pm2 stop next --kill-timeout 10000 || true
cd "${LIVE}"
# Rename both current artifacts so cutover and rollback stay fast.
if [ -d .next ]; then
mv .next .next.prev
fi
mv "${STAGE}/.next" .next
if [ -d node_modules ]; then
mv node_modules node_modules.prev
fi
mv "${STAGE}/node_modules" node_modules
free_tcp_port "${PORT}"
free_tcp_port 3000
echo "Starting PM2 with a clean PORT=${PORT} listener..."
pm2 delete next 2>/dev/null || true
PORT="${PORT}" pm2 start pnpm --name next -- start
pm2 save 2>/dev/null || true
sleep 3
if ! pm2 show next 2>/dev/null | grep -q 'online'; then
echo "ERROR: PM2 next failed to start!" >&2
pm2 logs next --lines 20 --nostream >&2 || true
exit 1
fi
echo "Waiting for HTTP health check on port ${PORT}..."
HEALTH_URL="${DEPLOY_HEALTH_URL:-http://127.0.0.1:${PORT}/api/health}"
HEALTH_OK=0
for i in $(seq 1 20); do
BODY="$(curl -sf --max-time 5 "${HEALTH_URL}" 2>/dev/null || true)"
if echo "${BODY}" | grep -q '"database":true'; then
echo "Health OK (${HEALTH_URL})"
HEALTH_OK=1
break
fi
echo "Health attempt ${i}/20 failed (body=${BODY:-<empty>}), retrying..."
sleep 2
done
if [ "${HEALTH_OK}" != "1" ]; then
echo "ERROR: Health check failed after deploy (${HEALTH_URL})" >&2
echo "Last body: ${BODY:-<empty>}" >&2
echo "Listeners on PORT ${PORT}:" >&2
ss -tlnp 2>/dev/null | grep ":${PORT} " >&2 || netstat -tlnp 2>/dev/null | grep ":${PORT} " >&2 || true
pm2 env 0 2>/dev/null | grep -E '^PORT=' >&2 || true
pm2 logs next --lines 40 --nostream >&2 || true
exit 1
fi
echo "Cleaning stage worktree and previous artifact backups..."
rm -rf "${LIVE}/.next.prev" "${LIVE}/node_modules.prev"
git -C "${LIVE}" worktree remove --force "${STAGE}" 2>/dev/null || rm -rf "${STAGE}" || true
STAGE=""
echo "--- Deployed successfully ---"
release:
if: startsWith(gitea.ref_name, 'v')
runs-on: shell
steps:
- name: Checkout
uses: actions/checkout@v4
with:
repository: ${{ gitea.repository }}
token: ${{ gitea.token }}
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: MariaDB and Redis integration tests
run: pnpm test:integration
tests-ui:
needs: check
runs-on: self-hosted
steps:
- name: Checkout
uses: actions/checkout@v4
with:
repository: ${{ gitea.repository }}
token: ${{ gitea.token }}
- name: Install dependencies
run: pnpm install --frozen-lockfile
# Compare against reviewed Linux references; updates are explicit.
- name: Install UI test browser
run: pnpm exec playwright install chromium
- name: Accessibility and UI regression checks
run: pnpm test:ui
- name: Upload UI results
if: always()
uses: https://gitea.com/actions/gitea-upload-artifact@62ac910c5d3dfa85c7cb2df15afe2e342b2407c2
with:
name: ui-results
path: |
e2e/ui/__screenshots__/linux/
playwright-report/ui/
test-results/ui/
retention-days: 14
# Validate branch/PR Docker images before integration into a deployment branch.
preflight:
needs: [tests-unit, tests-integration, tests-ui]
if: gitea.event_name == 'pull_request' || (gitea.event_name == 'push' && startsWith(gitea.ref, 'refs/heads/codex/'))
runs-on: self-hosted
steps:
- name: Checkout
uses: actions/checkout@v4
with:
repository: ${{ gitea.repository }}
token: ${{ gitea.token }}
- name: Toolchain check
run: node scripts/check-node-toolchain.mjs
- name: Build and verify isolated candidate
shell: bash
run: bash scripts/ci-preflight.sh
- name: Upload preflight news browser results
if: always()
uses: https://gitea.com/actions/gitea-upload-artifact@62ac910c5d3dfa85c7cb2df15afe2e342b2407c2
with:
name: preflight-news-browser-results
path: |
test-results/news-real/
playwright-report/news-real/
if-no-files-found: warn
retention-days: 14
# ─────────────────────────────────────────────
# Docker build & deploy
# Draait op de host (self-hosted) zodat Docker
# toegang heeft tot de daemon en volumes.
# ─────────────────────────────────────────────
deploy:
needs: [tests-unit, tests-integration, tests-ui]
if: gitea.event_name == 'push' && (gitea.ref_name == 'main' || gitea.ref_name == 'master')
runs-on: self-hosted
steps:
- name: Checkout
uses: actions/checkout@v4
with:
repository: ${{ gitea.repository }}
token: ${{ gitea.token }}
- name: Build, deploy and smoke test
shell: bash
- name: Build and deploy
env:
DEPLOY_BRANCH: ${{ gitea.ref_name }}
run: bash scripts/ci-deploy.sh
VERSION: ${{ gitea.ref_name }}
run: |
set -e
exec 2>&1
WORK="$(mktemp -d /var/tmp/epicnext-deploy.XXXXXX)"
cleanup() { rm -rf "${WORK}"; }
trap cleanup EXIT
echo "=== Deploying ${VERSION} ==="
git clone --depth 50 \
/docker/gitea/gitea/git/repositories/remco/epicnext-cms.git \
"${WORK}"
cd "${WORK}"
git checkout "${VERSION}"
export NODE_ENV=production
export SKIP_ENV_VALIDATION=1
pnpm install --frozen-lockfile
# Types come from the committed Drizzle schema (src/db/schema.ts).
# Tag releases must apply CMS SQL migrations against the live DB
# (same path as push-to-main deploy), using the production .env.
LIVE="/var/www/atom-nexst"
ln -sfn "${LIVE}/.env" "${WORK}/.env"
MIGRATE_OK=0
for i in $(seq 1 10); do
if pnpm db:migrate; then
MIGRATE_OK=1
break
fi
echo "migrate attempt ${i}/10 failed (likely DB connections), retrying..."
sleep 5
done
if [ "${MIGRATE_OK}" != "1" ]; then
echo "ERROR: db:migrate failed after retries" >&2
exit 1
fi
pnpm build
pm2 restart next --update-env
pm2 save
echo "=== Deploy complete ==="
- name: Create Release
env:
VERSION: ${{ gitea.ref_name }}
GITEA_API: ${{ gitea.api_url }}
GITEA_REPO: ${{ gitea.repository }}
run: |
set -e
exec 2>&1
BARE="/docker/gitea/gitea/git/repositories/remco/epicnext-cms.git"
echo "=== Creating release for ${VERSION} ==="
- name: Upload isolated news browser results
if: always()
uses: https://gitea.com/actions/gitea-upload-artifact@62ac910c5d3dfa85c7cb2df15afe2e342b2407c2
with:
name: news-browser-results
path: |
test-results/news-real/
playwright-report/news-real/
if-no-files-found: warn
retention-days: 14
PREV_TAG="$(git -C "$BARE" tag --sort=-creatordate | head -2 | tail -1 || echo '')"
- name: Upload JavaScript size report
if: always()
uses: https://gitea.com/actions/gitea-upload-artifact@62ac910c5d3dfa85c7cb2df15afe2e342b2407c2
with:
name: javascript-size-report
path: build-reports/
if-no-files-found: warn
retention-days: 14
if [ -n "$PREV_TAG" ] && [ "$PREV_TAG" != "$VERSION" ]; then
CHANGELOG="$(git -C "$BARE" log --oneline --no-decorate --max-count=50 "${PREV_TAG}..${VERSION}")"
[ -z "$CHANGELOG" ] && CHANGELOG="No commit changes since ${PREV_TAG}"
else
TOTAL="$(git -C "$BARE" rev-list --count "${VERSION}" 2>/dev/null || echo '?')"
CHANGELOG="Initial release of EpicNext-CMS (${TOTAL} commits)."
fi
[ -z "$CHANGELOG" ] && CHANGELOG="Initial release"
# Pin the other components at their current commits so the release is reproducible.
CAT_REF="$(git ls-remote https://gitlab.epicnabbo.nl/remco/Epicnabbo-Catalogus-Updated-Daily.git Beta-3 2>/dev/null | awk '{print $1}')"
NITRO_REF="$(git ls-remote https://github.com/duckietm/Nitro-V3.git main 2>/dev/null | awk '{print $1}')"
RENDER_REF="$(git ls-remote https://github.com/duckietm/Nitro_Render_V3.git main 2>/dev/null | awk '{print $1}')"
EMU_REF="$(git ls-remote https://github.com/duckietm/Polaris-Emulator.git main 2>/dev/null | awk '{print $1}')"
{
echo "# EpicNext-CMS ${VERSION}"
echo ""
echo "> Modern, high-performance CMS for Habbo hotel emulators — built on Next.js 16, React 19 and Drizzle ORM. Integrates with Polaris / Arcturus Morningstar databases."
echo ""
echo "## Menu"
echo "- [What is EpicNext-CMS?](#what-is-epicnext-cms)"
echo "- [System Requirements](#system-requirements)"
echo "- [Installation Wizard](#installation-wizard)"
echo "- [How it is used](#how-it-is-used)"
echo "- [Changes](#changes)"
echo "- [Linked repositories](#linked-repositories)"
echo ""
echo '<a id="what-is-epicnext-cms"></a>'
echo "## What is EpicNext-CMS?"
echo ""
echo "EpicNext-CMS is a full public-facing hotel website plus an administrative panel. It features NextAuth authentication (bcrypt with MD5 upgrade), real-time RCON communication with the emulator, Server-Sent Events for live radio, smooth page transitions and extensive extensibility. Full documentation: https://gitlab.epicnabbo.nl/remco/EpicNext-Cms/src/branch/main/README.md"
echo ""
echo '<a id="system-requirements"></a>'
echo "## System Requirements"
echo ""
echo "What you need to install before running the CMS:"
echo ""
echo "| Component | Version | Notes |"
echo "| --------- | ------- | ----- |"
echo "| Node.js | >= 22 | Required by Next.js 16 |"
echo "| pnpm | >= 10.33.4 | Package manager (npm/yarn not supported) |"
echo "| MySQL / MariaDB | 8.0+ / 10.6+ | Shared with the emulator |"
echo "| Redis | 7.x+ | Optional — caching, rate limiting, SSE |"
echo "| Java | 17+ | Only if building the emulator |"
echo "| Maven | 3.9+ | Only if building the emulator |"
echo ""
echo "The CMS shares its database with the Polaris / Arcturus emulator. It only reads/writes emulator-owned tables and never alters them."
echo ""
echo '<a id="installation-wizard"></a>'
echo "## Installation Wizard"
echo ""
echo "A complete hotel stack = **EpicNext-CMS** (this repo) + **Polaris Emulator** + **Nitro V3 client** + **Catalogus** data. Follow the steps in order."
echo ""
echo "**Quick links:** [Full setup guide](https://github.com/duckietm/Complete-Retro-on-Ubuntu) · [EpicNext-CMS repo](https://gitlab.epicnabbo.nl/remco/EpicNext-Cms) · [Reference configs in this repo](https://gitlab.epicnabbo.nl/remco/EpicNext-Cms/src/branch/main/setup)"
echo ""
echo "### 1. Clone & Install the CMS"
echo '```bash'
echo "git clone https://gitlab.epicnabbo.nl/remco/EpicNext-Cms.git"
echo "cd EpicNext-Cms"
echo "pnpm install"
echo '```'
echo ""
echo "### 2. Database Setup"
echo ""
echo "The CMS shares the emulator database. Import the Polaris/Arcturus database first, then create the CMS schema:"
echo '```sql'
echo "CREATE DATABASE IF NOT EXISTS epicnext_cms CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
echo '```'
echo ""
echo "### 3. Configure Environment"
echo '```bash'
echo "cp .env.example .env"
echo '```'
echo ""
echo "Edit .env with at minimum: DATABASE_URL, AUTH_SECRET, HOTEL_NAME and APP_URL. See .env.example for RCON, email, Redis, OAuth and PayPal options."
echo ""
echo "### 4. Run CMS Migrations"
echo '```bash'
echo "pnpm db:migrate"
echo '```'
echo ""
echo "Creates all CMS-owned tables (website_*, radio_*, acl_*, admin_audit_log). Emulator tables are never touched. Check status with pnpm db:migrate:status. Runtime types come from the committed Drizzle schema (src/db/schema.ts) via '@/lib/db'."
echo ""
echo "### 5. Polaris Emulator"
echo ""
echo "Clone and build the emulator (requires Java 17+ and Maven 3.9+):"
echo '```bash'
echo "git clone https://github.com/duckietm/Polaris-Emulator.git /var/www/emulator"
echo "cd /var/www/emulator/Emulator"
echo "mvn clean package"
echo '```'
echo ""
echo "Place the built Habbo-*-jar-with-dependencies.jar next to **config.ini** (see [setup/emulator/config.ini](https://gitlab.epicnabbo.nl/remco/EpicNext-Cms/src/branch/main/setup/emulator/config.ini)), then create a systemd unit from [setup/emulator/emulator.service](https://gitlab.epicnabbo.nl/remco/EpicNext-Cms/src/branch/main/setup/emulator/emulator.service) with the [emulator](https://gitlab.epicnabbo.nl/remco/EpicNext-Cms/src/branch/main/setup/emulator/emulator) launcher so it starts on boot. The bundled update-Nitrov3.sh in this repo automates cloning, building and updating the emulator and Nitro — run it any time to pull the latest commits and rebuild:"
echo '```bash'
echo "./update-Nitrov3.sh"
echo '```'
echo ""
echo "### 6. Nitro V3 & Renderer"
echo ""
echo "Clone both Nitro repos and build the client:"
echo '```bash'
echo "git clone https://github.com/duckietm/Nitro_Render_V3.git /var/www/Nitro_Render_V3"
echo "git clone https://github.com/duckietm/Nitro-V3.git /var/www/Nitro-V3"
echo "cd /var/www/Nitro_Render_V3 && yarn install && yarn link"
echo "cd /var/www/Nitro-V3 && yarn install && yarn link \"@nitrots/nitro-renderer\" && yarn build"
echo '```'
echo ""
echo "Copy the reference configs from [setup/nitro/](https://gitlab.epicnabbo.nl/remco/EpicNext-Cms/src/branch/main/setup/nitro) into /var/www/Nitro-V3/public/configuration, keep them as *.json, and replace **MY_DOMAIN** with your domain, API URL and gamedata paths (see the Full setup guide, NitroV3_And_Emulator.md)."
echo ""
echo "### 7. Catalogus (catalog & gamedata)"
echo ""
echo "Catalogus holds the daily-updated catalog/gamedata. Clone the Beta-3 branch alongside the other components:"
echo '```bash'
echo "git clone -b Beta-3 https://gitlab.epicnabbo.nl/remco/Epicnabbo-Catalogus-Updated-Daily.git /var/www/catalogus"
echo '```'
echo ""
echo "### 8. Build & Start the CMS"
echo '```bash'
echo "# Development (hot reload)"
echo "pnpm dev"
echo ""
echo "# Production"
echo "pnpm build && pnpm start"
echo '```'
echo ""
echo "Open http://localhost:3000 in your browser."
echo ""
echo "### 9. First Login"
echo ""
echo "1. Register at /register, or log in with an existing emulator account."
echo "2. Grant admin access: UPDATE users SET rank = 7 WHERE username = 'yourname';"
echo "3. Visit /admin and configure your hotel via Admin -> CMS Settings."
echo ""
echo '<a id="how-it-is-used"></a>'
echo "## How it is used"
echo ""
echo "- Public site: browse the hotel, news, radio and the Nitro client at /client."
echo "- Admin panel: /admin for CMS settings, theming (12 presets), users, radio and more."
echo "- Background jobs: run pnpm jobs:worker for daily backups and cleanup."
echo "- Optional: Cloudflare Turnstile / reCAPTCHA, OpenAI moderation and email/PayPal via .env."
echo ""
echo '<a id="changes"></a>'
echo "## Changes"
echo '```'
echo "${CHANGELOG}"
echo '```'
echo ""
echo '<a id="linked-repositories"></a>'
echo "## Linked repositories (exact commits)"
echo ""
echo "The game components below are pinned to the exact commits used by this release and are deployed alongside the CMS:"
echo ""
echo "| Component | Repository | Commit |"
echo "|-----------|------------|--------|"
echo "| Catalogus | https://gitlab.epicnabbo.nl/remco/Epicnabbo-Catalogus-Updated-Daily | ${CAT_REF:-?} |"
echo "| Nitro-V3 | https://github.com/duckietm/Nitro-V3 | ${NITRO_REF:-?} |"
echo "| Nitro-Render-V3 | https://github.com/duckietm/Nitro_Render_V3 | ${RENDER_REF:-?} |"
echo "| Polaris Emulator | https://github.com/duckietm/Polaris-Emulator | ${EMU_REF:-?} |"
echo ""
echo "**[Nitro-V3](https://github.com/duckietm/Nitro-V3)** · **[Nitro Renderer](https://github.com/duckietm/Nitro_Render_V3)** · **[Polaris Emulator](https://github.com/duckietm/Polaris-Emulator)** · **[Catalogus](https://gitlab.epicnabbo.nl/remco/Epicnabbo-Catalogus-Updated-Daily)**"
echo ""
echo "---"
echo "*Automated release from Gitea Actions*"
} > /tmp/release-body.md
PAYLOAD="$(jq -Rs --arg v "${VERSION}" '{tag_name: $v, name: $v, body: ., draft: false, prerelease: false}' < /tmp/release-body.md)"
TOKEN="${GITEA_TOKEN:-${{ secrets.GITEA_TOKEN }}}"
HTTP_CODE="$(curl -s -w '%{http_code}' -o /tmp/release-resp.json \
-X POST "${GITEA_API}/repos/${GITEA_REPO}/releases" \
-H "Authorization: token ${TOKEN}" \
-H "Content-Type: application/json" \
-d "$PAYLOAD")"
if [ "${HTTP_CODE}" = "409" ]; then
RELEASES="$(curl -sf "${GITEA_API}/repos/${GITEA_REPO}/releases" \
-H "Authorization: token ${TOKEN}")"
REL_ID="$(echo "$RELEASES" | jq -r ".[] | select(.tag_name==\"${VERSION}\") | .id")"
HTTP_CODE="$(curl -s -w '%{http_code}' -o /tmp/release-resp.json \
-X PATCH "${GITEA_API}/repos/${GITEA_REPO}/releases/${REL_ID}" \
-H "Authorization: token ${TOKEN}" \
-H "Content-Type: application/json" \
-d "$PAYLOAD")"
fi
if [ "${HTTP_CODE:-0}" -ge 200 ] && [ "${HTTP_CODE:-0}" -lt 300 ]; then
echo "SUCCESS: Release ${VERSION} created/updated"
cat /tmp/release-resp.json | jq -r '.html_url // .id'
else
echo "FAILED HTTP ${HTTP_CODE}"
cat /tmp/release-resp.json
exit 1
fi
+27
View File
@@ -0,0 +1,27 @@
name: Renovate
on:
schedule:
- cron: "0 5 * * *" # Every day at 05:00 UTC
workflow_dispatch: # Manual trigger
jobs:
renovate:
runs-on: shell
steps:
- name: Self-hosted Renovate
run: |
set -e
# Ensure cache dir exists before Docker starts
mkdir -p /var/tmp/renovate-cache
docker run --rm \
--user "$(id -u):$(id -g)" \
-e RENOVATE_TOKEN="${{ secrets.RENOVATE_TOKEN }}" \
-e RENOVATE_AUTODISCOVER=false \
-e RENOVATE_REPOSITORIES="${{ gitea.repository }}" \
-e RENOVATE_ONBOARDING=false \
-e RENOVATE_CONFIG_FILE='{"extends":["config:recommended"]}' \
-e LOG_LEVEL=info \
-v /var/tmp/renovate-cache:/tmp/renovate-cache \
ghcr.io/renovatebot/renovate:latest
-17
View File
@@ -1,17 +0,0 @@
name: Gitea Actions Runner Test
on: [push]
jobs:
test-job:
runs-on: self-hosted
steps:
- name: Check Host Environment
run: |
echo "The v3.5.0 runner works!"
echo "Current date/time on VPS:"
date
echo "Running kernel version:"
uname -a
- name: Test Bash Command
run: echo "Greetings from the host runner!"
+1 -28
View File
@@ -1,13 +1,9 @@
node_modules/
node_modules.prev/
.turbo/
.next/
.next.prev/
.next-staging/
next-env.d.ts
.env
.env.local
.env.*.local
*.tsbuildinfo
src/generated/
# Runtime avatar/badge imaging disk cache
@@ -20,8 +16,7 @@ prod.log
db_backup_*.sql
# Local project documentation
/docs/*
!/docs/cms-upgrade-2026-09.md
/docs/
# Local gitea binary symlink
gitea
@@ -36,25 +31,3 @@ public/tmp/
# Test coverage reports
coverage/
.aider*
/public/vendor/tinymce/
# Shared deployment lock (never application source)
.deploy.lock
# Browser verification artifacts
test-results/
playwright-report/
blob-report/
# Local Docker installation metadata
.docker-install
.docker-install.tmp.*
.env.install.*
build-reports/
!/docs/performance-budgets.md
# One-off local snapshots (o.a. catalog-integrity/pre-fix.json): runtime-werk,
# geen bron. Per map opgeslagen om een incident terug te kunnen lezen.
backups/
-33
View File
@@ -1,33 +0,0 @@
image: node:26
stages:
- test
- build
cache:
paths:
- node_modules/
before_script:
- corepack enable
- pnpm install --frozen-lockfile
lint:
stage: test
script:
- pnpm run lint
typecheck:
stage: test
script:
- pnpm run typecheck
test:
stage: test
script:
- pnpm run test
build:
stage: build
script:
- pnpm run build
+1
View File
@@ -0,0 +1 @@
pnpm exec lint-staged
+2
View File
@@ -0,0 +1,2 @@
pnpm typecheck
pnpm test
-1
View File
@@ -1 +0,0 @@
strict-peer-dependencies=false
+1 -1
View File
@@ -1 +1 @@
26.10.0
22
-73
View File
@@ -1,73 +0,0 @@
# Catalog Studio repository export
Studio mutations automatically queue an export to
`https://gitlab.epicnabbo.nl/remco/Epicnabbo-Catalogus-Updated-Daily.git`, branch
`Beta-3`. The jobs worker processes pending exports every minute. Streaming
imports stay active until their stream completes. Server actions for catalog
pages, offers, deletion and maintenance are covered as well.
## Server setup
1. Create a **dedicated clean clone** of the repository on `Beta-3`, outside the
CMS directory. Configure non-interactive Git push authentication for the
worker OS account using its credential helper. Do not put tokens in URLs.
2. Set `CATALOG_GIT_CHECKOUT` to that absolute clone directory in the CMS and
worker environments. Set `CATALOG_GIT_STATE_DIR` to a persistent, writable
directory outside the clone, shared by both processes on the same host.
3. Run `pnpm jobs:worker` alongside the CMS under your process supervisor.
Both processes must have access to the configured asset directories and DB.
The worker command enables the React server condition for server-only modules.
4. Restart the CMS after setting the environment. In **Studio → Sync**, use
**Export now / retry** for the initial export. Subsequent mutations queue
automatically. Status shows pending/active operations and the last commit.
Leaving `CATALOG_GIT_CHECKOUT` empty disables export. No credentials are shipped.
This source change alone does not configure or deploy the production service.
## Exported content
| Source | Repository destination |
| --- | --- |
| Configured Nitro bundles, including furniture, figures, effects and pets | `Gamedata/bundled` |
| Configured furni icons | `Gamedata/icons` |
| Existing badge/catalog images | `Gamedata/c_images` |
| FurnitureData and supported public game-data JSON files | `Gamedata/config` |
| Existing localized FurnitureData files | `catalogue version 2 ( Final (Dev)/langs furnidata` |
| `items_base`, `catalog_pages`, `catalog_items` | `catalogue version 2 ( Final (Dev)/sqls` |
| `catalog_pages_bc`, `catalog_items_bc`, when present | Same SQL directory |
SQL is read in one consistent, read-only InnoDB transaction. Dumps contain table
definitions and deterministic upserts with hexadecimal UTF-8 string literals.
Import `items_base.sql`, then `catalog_pages.sql`, then `catalog_items.sql`.
Existing schemas are not migrated by these dumps. Rows absent from the source
are omitted; importing an upsert dump into another existing database does not
delete that database's extra rows. No user, session or credential tables are exported.
Only existing local assets are exported. Translation generation follows Studio's
existing setting; export does not generate missing languages or download assets.
Public JSON is explicitly allowlisted so translation caches and private runtime
files cannot enter the repository. Invalid JSON or concurrent Studio changes
prevent publication of that snapshot.
## Failure and concurrency behavior
- Pending events survive process restarts; events added during publication remain
pending for the next run. Partial imports are exported as their settled local
state, including successful items from a batch containing failures.
- A single filesystem lock serializes the worker. Dead local process markers are
recovered on the next run. For an unreadable marker or a marker from another
host, stop the CMS and worker before repairing the queue directory.
- A failed push retains the local commit and pending events for retry. Concurrent
upstream commits are rebased; a conflict aborts the rebase and leaves the event
pending. Resolve conflicts in the dedicated clone, then retry.
- The checkout must be clean before each run. Unrelated files are preserved and
no force push is used. Missing local files do not cause remote deletions.
- Status errors omit raw Git output to avoid exposing authentication material.
## Verification
Run the `catalog-git-*` service tests and `src/lib/catalog-export-api.test.ts` with
Vitest. The integration test creates a temporary bare remote and verifies push,
failed-push recovery, no-op export and preservation of unrelated files. SQL
snapshot tests mock the database; production DB import and production push need
verification in the deployed environment.
-30
View File
@@ -1,30 +0,0 @@
# CMS translation audit and editor
The CMS editor at `/admin/translations/cms` now uses the same bundled catalogs as the request-time translator. Runtime changes are stored separately in `storage/cms-translations/<locale>.json`, inside the existing persistent `/app/storage` mount. No source-file write, environment-variable change or rebuild is required to apply an edit.
Only overrides are saved. Unchanged messages continue to receive updates from Git. Saves use a file lock, an atomic replacement and a revision check; a stale editor cannot overwrite another operator's changes. ICU syntax, argument names, rich-text tags and allowed keys are checked server-side. Invalid or obsolete overrides are excluded when reading a new release. Storage read errors are reported to the CMS error monitor and public pages fall back to bundled text.
The page starts in the operator's language. It shows all English reference keys, including missing translations, and supports search by key, translated text or English source. Filters separate missing, identical and modified text. Drafts survive language switches and failed saves. Users without `SETTINGS_EDIT` can review and export but cannot save.
## Audit outcome, 6 September 2026
- Scanned 25 JSON catalogs; 22 languages are selectable. The small Arabic, Finnish and Japanese catalogs are legacy files and remain outside the supported locale list.
- Repaired 66 malformed ICU messages across the 22 active catalogs, including HTML fragments and unescaped JSON examples.
- Added 199 missing English reference keys used by page components, with Italian translations, and fixed the incorrect navigation namespace in the admin error page.
- Completed the 31 previously missing Italian reference keys.
- Repaired missing `count` and `preset` variables in other locales.
- Final checks: zero malformed messages, zero argument/tag mismatches and zero missing references among the statically resolved translation calls.
- English contains 3,423 reference keys. Italian covers all of them; 629 values match English. Dutch is missing 524 reference keys and has 618 identical values. Matching English can be intentional for names and technical labels; this is not proof of translation quality.
- Found 1,577 literal JSX text candidates outside translation calls. These include labels, technical strings and names; they are an editorial inventory, not 1,577 confirmed bugs. The largest concentrations are the catalog item table (118), Studio main component (79), import audit (53), sound management (50) and permission editor (42).
## Repeatable checks
- `pnpm i18n:check`: fails on malformed messages, incompatible variables/tags, empty messages, source parsing errors or missing statically referenced keys. Runs in Gitea CI.
- `pnpm i18n:audit`: prints coverage and findings.
- `node scripts/audit-cms-translations.mjs --json`: full machine-readable inventory, including file and line references for literal JSX candidates.
Static analysis resolves literal translator namespaces and literal message keys. Dynamic key construction, prose embedded in arbitrary JavaScript strings, and the linguistic accuracy of all 22 translations still require targeted review. English fallback remains explicit; copying English into other catalogs would hide untranslated entries and is intentionally avoided.
## Validation
Automated tests exercise message syntax, actual translator output, persistent overrides, invalid-message rejection, revision conflicts and reset behavior. A browser fixture mounts the real editor and verifies missing-key editing, validation, failed-save preservation, language switching, successful saves, read-only access and mobile layout. Server actions are simulated in that fixture; authenticated production editing requires a staff session.
-63
View File
@@ -1,63 +0,0 @@
# syntax=docker/dockerfile:1
FROM node:26.10.0-alpine AS migrations
WORKDIR /app
ENV NEXT_TELEMETRY_DISABLED=1
# Installeer git en pnpm v12
RUN --mount=type=cache,target=/var/cache/apk \
apk add --no-cache git \
&& npm install -g [email protected]
# Stel het PATH zo in dat Alpine pnpm gegarandeerd overal herkent
ENV PNPM_HOME="/usr/local/share/pnpm"
ENV PATH="$PNPM_HOME:/usr/local/bin:$PATH"
COPY package.json pnpm-lock.yaml* pnpm-workspace.yaml* .npmrc* ./
# Voer de installatie uit met de pnpm v12 store cache-mount
RUN --mount=type=cache,target=/root/.local/share/pnpm/store \
pnpm install --frozen-lockfile --ignore-scripts
COPY . .
ARG NEXT_DEPLOYMENT_ID="unknown"
LABEL org.opencontainers.image.revision="$NEXT_DEPLOYMENT_ID"
FROM migrations AS builder
ARG NEXT_DEPLOYMENT_ID="unknown"
ENV NEXT_DEPLOYMENT_ID="$NEXT_DEPLOYMENT_ID"
# Fix voor OOM Killer: dwing de Node-compiler om agressief op te ruimen bij 4GB RAM
ENV NODE_OPTIONS="--max-old-space-size=4096"
# Bouw de Next.js applicatie met caching
RUN --mount=type=cache,target=/app/.next/cache \
DATABASE_URL="mysql://build:[email protected]:9/build" \
HOTEL_NAME="Build fixture" APP_URL="http://localhost:3002" \
AUTH_SECRET="build-fixture-not-for-runtime-use-000000000000" \
pnpm run build \
&& PERFORMANCE_COMMIT_SHA="$NEXT_DEPLOYMENT_ID" node scripts/performance-report.mjs --output-dir build-reports
FROM node:26.10.0-alpine AS runner
ARG NEXT_DEPLOYMENT_ID="unknown"
LABEL org.opencontainers.image.revision="$NEXT_DEPLOYMENT_ID"
WORKDIR /app
ENV NODE_ENV=production \
NEXT_TELEMETRY_DISABLED=1 \
PORT=3002 \
HOSTNAME=0.0.0.0
RUN apk add --no-cache tini curl \
&& addgroup -g 33 -S nextjs && adduser -u 33 -S -G nextjs nextjs \
&& mkdir -p /app/storage /app/public/nitro-assets /app/public/swf /var/www/Gamedata \
&& chown -R 33:33 /app/storage /app/public /var/www/Gamedata
COPY --from=builder --chown=nextjs:nextjs /app/public ./public
COPY --from=builder --chown=nextjs:nextjs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nextjs /app/.next/static ./.next/static
COPY --from=builder --chown=nextjs:nextjs /app/build-reports ./build-reports
COPY --from=builder --chown=nextjs:nextjs /app/drizzle/migrations ./drizzle/migrations
COPY --chown=nextjs:nextjs scripts/docker-start.mjs ./docker-start.mjs
USER nextjs
EXPOSE 3002
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
CMD ["node", "-e", "fetch('http://127.0.0.1:'+(process.env.PORT||'3002')+'/api/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
ENTRYPOINT ["/sbin/tini", "--"]
CMD ["node", "docker-start.mjs"]
+281 -838
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,205 +0,0 @@
[
{
"id": 132,
"sprite_id": 132,
"item_name": "floortile",
"public_name": "Floor Tile",
"type": "s",
"width": 1,
"length": 1,
"stack_height": 0,
"allow_stack": 1,
"allow_sit": 0,
"allow_lay": 0,
"allow_walk": 1,
"allow_gift": 1,
"allow_trade": 1,
"allow_recycle": 0,
"allow_marketplace_sell": 0,
"allow_inventory_stack": 1,
"interaction_type": "default",
"interaction_modes_count": 0,
"vending_ids": "0",
"multiheight": "",
"customparams": "",
"effect_id_male": 0,
"effect_id_female": 0,
"clothing_on_walk": "",
"page_id": "429",
"rare": "0"
},
{
"id": 420,
"sprite_id": 420,
"item_name": "soft_jaggara_norja",
"public_name": "Norja-pehmojakkara",
"type": "s",
"width": 1,
"length": 3,
"stack_height": 1.7,
"allow_stack": 1,
"allow_sit": 1,
"allow_lay": 0,
"allow_walk": 0,
"allow_gift": 1,
"allow_trade": 1,
"allow_recycle": 0,
"allow_marketplace_sell": 0,
"allow_inventory_stack": 1,
"interaction_type": "default",
"interaction_modes_count": 1,
"vending_ids": "0",
"multiheight": "",
"customparams": "",
"effect_id_male": 0,
"effect_id_female": 0,
"clothing_on_walk": "",
"page_id": "429",
"rare": "0"
},
{
"id": 1001,
"sprite_id": 1001,
"item_name": "Chess",
"public_name": "",
"type": "i",
"width": 1,
"length": 1,
"stack_height": 1,
"allow_stack": 1,
"allow_sit": 0,
"allow_lay": 0,
"allow_walk": 0,
"allow_gift": 1,
"allow_trade": 1,
"allow_recycle": 0,
"allow_marketplace_sell": 0,
"allow_inventory_stack": 1,
"interaction_type": "default",
"interaction_modes_count": 0,
"vending_ids": "0",
"multiheight": "",
"customparams": "",
"effect_id_male": 0,
"effect_id_female": 0,
"clothing_on_walk": "",
"page_id": "429",
"rare": "0"
},
{
"id": 1011,
"sprite_id": 1011,
"item_name": "TicTacToe",
"public_name": "",
"type": "i",
"width": 1,
"length": 1,
"stack_height": 1,
"allow_stack": 1,
"allow_sit": 0,
"allow_lay": 0,
"allow_walk": 0,
"allow_gift": 1,
"allow_trade": 1,
"allow_recycle": 0,
"allow_marketplace_sell": 0,
"allow_inventory_stack": 1,
"interaction_type": "default",
"interaction_modes_count": 0,
"vending_ids": "0",
"multiheight": "",
"customparams": "",
"effect_id_male": 0,
"effect_id_female": 0,
"clothing_on_walk": "",
"page_id": "429",
"rare": "0"
},
{
"id": 1021,
"sprite_id": 1021,
"item_name": "BattleShip",
"public_name": "",
"type": "i",
"width": 1,
"length": 1,
"stack_height": 1,
"allow_stack": 1,
"allow_sit": 0,
"allow_lay": 0,
"allow_walk": 0,
"allow_gift": 1,
"allow_trade": 1,
"allow_recycle": 0,
"allow_marketplace_sell": 0,
"allow_inventory_stack": 1,
"interaction_type": "default",
"interaction_modes_count": 0,
"vending_ids": "0",
"multiheight": "",
"customparams": "",
"effect_id_male": 0,
"effect_id_female": 0,
"clothing_on_walk": "",
"page_id": "429",
"rare": "0"
},
{
"id": 1659,
"sprite_id": 1659,
"item_name": "ticket",
"public_name": "Big Ticket Bundle",
"type": "s",
"width": 1,
"length": 1,
"stack_height": 1,
"allow_stack": 1,
"allow_sit": 0,
"allow_lay": 0,
"allow_walk": 0,
"allow_gift": 1,
"allow_trade": 1,
"allow_recycle": 0,
"allow_marketplace_sell": 0,
"allow_inventory_stack": 1,
"interaction_type": "default",
"interaction_modes_count": 0,
"vending_ids": "0",
"multiheight": "",
"customparams": "",
"effect_id_male": 0,
"effect_id_female": 0,
"clothing_on_walk": "",
"page_id": "429",
"rare": "0"
},
{
"id": 10056,
"sprite_id": 10056,
"item_name": "Vacuum",
"public_name": "laundry_r18_vacuum",
"type": "s",
"width": 1,
"length": 1,
"stack_height": 0,
"allow_stack": 0,
"allow_sit": 0,
"allow_lay": 0,
"allow_walk": 0,
"allow_gift": 1,
"allow_trade": 1,
"allow_recycle": 0,
"allow_marketplace_sell": 0,
"allow_inventory_stack": 1,
"interaction_type": "default",
"interaction_modes_count": 0,
"vending_ids": "0",
"multiheight": "",
"customparams": "",
"effect_id_male": 0,
"effect_id_female": 0,
"clothing_on_walk": "",
"page_id": "9966",
"rare": "0"
}
]
+1 -13
View File
@@ -7,7 +7,7 @@
},
"files": {
"ignoreUnknown": false,
"includes": ["**", "!setup", "!*.cjs", "!coverage", "!drizzle/drafts/meta"]
"includes": ["**", "!setup", "!*.cjs", "!coverage"]
},
"formatter": {
"enabled": true,
@@ -28,18 +28,6 @@
}
}
},
"overrides": [
{
"includes": ["**/*.test.ts", "**/*.test.tsx"],
"linter": {
"rules": {
"suspicious": {
"noExplicitAny": "off"
}
}
}
}
],
"css": {
"parser": {
"tailwindDirectives": true
-9
View File
@@ -1,9 +0,0 @@
#!/usr/bin/env bash
set -Eeuo pipefail
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
case "${1:-help}" in
install) shift; exec bash "$DIR/scripts/docker-install.sh" "$@" ;;
update) shift; exec bash "$DIR/scripts/docker-update.sh" "$@" ;;
help|--help|-h) printf '%s\n' 'bash cms install Configure and install on a Linux Docker host' 'bash cms update Update using saved settings; --skip-pull uses checked-out release' ;;
*) echo "Unknown command. Use: bash cms install | update" >&2; exit 1 ;;
esac
-31
View File
@@ -1,31 +0,0 @@
#!/usr/bin/env bash
# Handmatige release uitvoeren.
#
# Dit script is bewust een dunne wrapper. Het echte werk zit in
# `scripts/ci-deploy.sh`, want dat is wat Gitea Actions ook draait. Eén deploypad
# betekent dat een handmatige release niet anders kan werken dan een release uit
# CI, dus er is geen tweede, slechter onderhouden pad meer.
#
# Waarom dit niet meer zelf doet wat het deed:
# - `fuser -k 3002/tcp` sloopte de live release bij elke mislukte build;
# - `docker compose down` haalde de site omlaag vóórdat er iets nieuws stond;
# - de container draait via `docker run` uit ci-deploy.sh, niet via compose, dus
# compose beheerde hier nooit de release die er echt draaide.
#
# `scripts/ci-deploy.sh` start nu blue/green: de nieuwe release komt op de vrije
# poort terwijl de live release door blijft draaien, en nginx gaat pas om nadat
# de kandidaat gezond is en de e2e-test heeft gewonnen.
set -Eeuo pipefail
deploy_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$deploy_dir"
if [ "${1:-}" = "--help" ] || [ "${1:-}" = "-h" ]; then
sed -n '2,20p' "$deploy_dir/deploy.sh" | sed 's/^# \{0,1\}//'
exit 0
fi
# De branch-guard in ci-deploy.sh accepteert alleen main/master, en controleert
# daarna of de HEAD-commit nog de nieuwste op de remote is. Deployen vanuit een
# feature-branch kan dus niet per ongeluk; dat was eerder wél mogelijk.
exec bash "$deploy_dir/scripts/ci-deploy.sh" "$@"
-81
View File
@@ -1,81 +0,0 @@
# Trusted edge networks + live Cloudflare CDN ranges.
# Managed/regenerated by scripts/cf-ips-sync.sh - do not hand-edit the ranges.
# Topology: Cloudflare -> Traefik (:443, docker bridge proxy_traefik-proxy) ->
# nginx (:9443) -> CMS. nginx ALSO receives direct connections on :9443 from
# Cloudflare edges and from the game client (ws.epicnabbo.nl is not proxied).
# nginx only trusts the peers listed here as a source of $remote_addr
# (via CF-Connecting-IP). Anyone else presenting a CF-Connecting-IP or
# CF-ray header is spoofing and is rejected in nginx-cms.conf.
# 1 = peer is a trusted edge or internal network (keyed on the raw peer,
# unaffected by real_ip rewrites).
geo $realip_remote_addr $cms_trusted_edge {
default 0;
127.0.0.0/8 1; # localhost (health checks, admin)
::1 1; # localhost v6
172.22.0.0/16 1; # Traefik (proxyserver_traefik-proxy)
# --- Cloudflare IPv4 ranges (live from cloudflare.com/ips-v4) ---
173.245.48.0/20 1;
103.21.244.0/22 1;
103.22.200.0/22 1;
103.31.4.0/22 1;
141.101.64.0/18 1;
108.162.192.0/18 1;
190.93.240.0/20 1;
188.114.96.0/20 1;
197.234.240.0/22 1;
198.41.128.0/17 1;
162.158.0.0/15 1;
104.16.0.0/13 1;
104.24.0.0/14 1;
172.64.0.0/13 1;
131.0.72.0/22 1;
# --- Cloudflare IPv6 ranges (live from cloudflare.com/ips-v6) ---
2400:cb00::/32 1;
2606:4700::/32 1;
2803:f800::/32 1;
2405:b500::/32 1;
2405:8100::/32 1;
2a06:98c0::/29 1;
2c0f:f248::/32 1;
}
# 1 when an UNTRUSTED peer still presents a CF-Connecting-IP header: that is a
# spoof attempt (only real Cloudflare edges or Traefik may do that lawfully).
map "$cms_trusted_edge:$http_cf_connecting_ip" $cms_disallow_forwarding {
default 0;
"~^0:.+" 1;
}
# Rewrite $remote_addr from CF-Connecting-IP but ONLY for the trusted peers
# above. Direct game clients (untrusted) keep their real peer address.
set_real_ip_from 127.0.0.0/8;
set_real_ip_from ::1;
set_real_ip_from 172.22.0.0/16;
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 103.21.244.0/22;
set_real_ip_from 103.22.200.0/22;
set_real_ip_from 103.31.4.0/22;
set_real_ip_from 141.101.64.0/18;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 104.16.0.0/13;
set_real_ip_from 104.24.0.0/14;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 131.0.72.0/22;
set_real_ip_from 2400:cb00::/32;
set_real_ip_from 2606:4700::/32;
set_real_ip_from 2803:f800::/32;
set_real_ip_from 2405:b500::/32;
set_real_ip_from 2405:8100::/32;
set_real_ip_from 2a06:98c0::/29;
set_real_ip_from 2c0f:f248::/32;
real_ip_header CF-Connecting-IP;
real_ip_recursive off;
@@ -1,2 +0,0 @@
# Default; ci-deploy.sh (blue/green) herschrijft dit bestand bij elke switch.
server 127.0.0.1:3002;
-9
View File
@@ -1,9 +0,0 @@
# Opt in through COMPOSE_FILE in the clone's .env; see docs/operations/docker-installation.md.
# The base service uses Linux host networking: bind the process, do not add ports.
services:
cms:
environment:
HOSTNAME: 127.0.0.1
PORT: "3002"
healthcheck:
test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:3002/api/health').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"]
-528
View File
@@ -1,528 +0,0 @@
# ─── EpicNabbo CMS — nginx site config ───
# Source of truth: deployment/proxy/nginx-cms.conf in the EpicNext-Cms repo.
# Installed at /etc/nginx/sites-available/cms.conf by scripts/nginx-sync.sh.
#
# Ingeladen binnen http{} uit /etc/nginx/sites-enabled/*.conf.
#
# PRINCIPE — één eigenaar per URL-klasse:
# * Alleen nginx (dit bestand) mag Cache-Control toevoegen voor routes die
# een publieke, gedeelde cache toestaan.
# * Alles wat de app zelf (src/proxy.ts) als no-store stuurt, blijft no-store.
# * Er is GEEN byte-cache meer (geen proxy_cache_*): de app deed ooit zelf
# al single-flight/stale-while-revalidate in src/lib/cache.ts. Daarmee is
# "dubbele cache" (nginx HIT naast de app) structureel onmogelijk.
# * De headers die hieronder staan zijn de enige Cache-Control die een
# client/CDN te zien krijgt; er wordt nooit een tweede toegevoegd.
# ─── Maps (moeten op http level staan) ───
map $request_method $cors_headers {
OPTIONS 1;
default 0;
}
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
# ─── Cachebeleid: één plek die beslist of een antwoord gedeeld mag worden ───
#
# Waarom op nginx: Next.js overschrijft `Cache-Control` op dynamische route
# handlers (next/dist/server/send-response.js weigert een al aanwezige header
# te overschrijven) en src/proxy.ts zet die paden bovendien op no-store. Deze
# maps nemen de publieke beslissing daarom expliciet over van de app, zodat
# browser + CDN daadwerkelijk cachen — met één enkele header.
# Nooit als "publiek" aankondigen als er een sessie aan hangt. NextAuth v5
# zet `__Secure-authjs.session-token` (en `authjs.*` zonder prefix); de
# Nitro-client gebruikt een eigen cookie. Elke cookie waarvan de naam op
# session-token eindigt of met authjs. begint telt als "ingelogd", plus elk
# Authorization-header. Zo kan een persoonlijke variant nooit publiek worden.
map $http_cookie $cms_sess_cookie {
default 0;
"~*session-token=" 1;
"~*authjs\." 1;
}
map $http_authorization $cms_authz_header {
default 1;
"" 0;
}
# "1" zodra er ook maar één auth-signaal aanwezig is.
map "$cms_sess_cookie$cms_authz_header" $cms_skip_cache {
default 1;
"~^00$" 0;
}
# Cacheklasse per endpoint. De TTL's komen overeen met wat de app zelf al
# aangeeft (publicCacheControl in src/lib/api.ts) zodat de edge niets
# verscherper maakt dan de applicatie toestaat. Klasse 0 = no-store.
map $uri $cms_cc_class {
default 0;
# online count wordt door elke pagina en de SSE-stream gepolld
~^/api/online(/count)?$ 1;
# snel verouderende, maar publieke lijsten
~^/api/(photos|leaderboard|radio/current-dj|radio/points/leaderboard)$ 2;
# stabiele catalogus- en rosterdata
~^/api/(staff|teams|guilds|shop|values)(/categories|/[0-9]+)?$ 3;
}
# Eén bron van waarheid: klasse + al dan niet ingelogd. De `|`-scheiding is
# nginx' string-samenvoeging; `~^1\|0` leest "klasse 1 en niet ingelogd".
map "$cms_cc_class|$cms_skip_cache" $cms_public_cc {
default "private, no-cache, no-store, max-age=0, must-revalidate";
"~^1\|0" "public, max-age=10, s-maxage=10, stale-while-revalidate=30";
"~^2\|0" "public, max-age=60, s-maxage=60, stale-while-revalidate=180";
"~^3\|0" "public, max-age=300, s-maxage=300, stale-while-revalidate=600";
}
# ─── Mime fix ───
types {
application/json jsonc;
}
# ==========================================
# REDIRECT HTTP -> HTTPS (Poort 9444)
# ==========================================
server {
listen 9444 default_server;
listen [::]:9444 default_server;
server_name _;
location / {
return 301 https://$host$request_uri;
}
}
# ==========================================
# WEBSOCKET GAME SERVER (ws.epicnabbo.nl)
# ==========================================
server {
listen 9443 ssl;
listen [::]:9443 ssl;
server_name ws.epicnabbo.nl;
ssl_certificate /etc/ssl/epicnabbo-backend.pem;
ssl_certificate_key /etc/ssl/epicnabbo-backend.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers off;
# ─── Trusted Edge Gate ───
# Real Cloudflare edges and Traefik are the only peers trusted to supply a
# CF-Connecting-IP (see cloudflare-ips.conf). Any other peer that does is
# spoofing and is rejected before it reaches the CMS. Legitimate direct
# visitors (game client, :9443) never carry that header and pass through
# with their real peer address.
if ($cms_disallow_forwarding) {
return 403;
}
location /health {
access_log off;
return 200 "OK";
add_header Content-Type text/plain;
}
location / {
proxy_pass http://127.0.0.1:2096;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
# Echt client IP (trusted peers via real_ip, directe clients = eigen peer)
proxy_set_header CF-Connecting-IP "";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 86400s;
proxy_send_timeout 86400s;
}
}
# ==========================================
# MAIN HTTPS SERVER (Poort 9443)
# ==========================================
server {
listen 9443 ssl reuseport default_server;
listen [::]:9443 ssl reuseport default_server;
listen 9443 quic reuseport;
listen [::]:9443 quic reuseport;
http2 on;
server_name epicnabbo.nl www.epicnabbo.nl;
ssl_certificate /etc/ssl/epicnabbo-backend.pem;
ssl_certificate_key /etc/ssl/epicnabbo-backend.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers off;
ssl_early_data on;
add_header Alt-Svc 'h3=":9443"; ma=86400' always;
index index.html;
# ─── Security Headers ───
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
# ─── Trusted Edge Gate ───
# Real Cloudflare edges / Traefik are the only peers allowed to supply a
# CF-Connecting-IP (see cloudflare-ips.conf). Any other peer presenting one
# is spoofing (direct :9443 traffic), and is rejected before it reaches the
# CMS. Legitimate direct visitors never carry that header and pass through
# with their real peer address.
if ($cms_disallow_forwarding) {
return 403;
}
# ─── Client Limits & Timeouts ───
client_max_body_size 20m;
client_body_buffer_size 16k;
client_header_buffer_size 1k;
large_client_header_buffers 4 8k;
client_body_timeout 12s;
client_header_timeout 12s;
keepalive_timeout 30s;
send_timeout 10s;
# Abuse limits. Deliberately NOT set at server scope: a room load and a page
# load are not the same request profile, so each location picks its own zone.
# /gamedata/* has no request limit at all — it is a disk cache, so limiting
# it only cost players their icons. The page routes carry the budget.
limit_conn cms_conn_per_ip 30;
# Traefik health-check route herstellen
location = /health {
access_log off;
return 200 "OK";
add_header Content-Type text/plain;
}
# ─── Statische Bestanden & Assets ───
location ^~ /client/ {
alias /var/www/Octane/dist/;
try_files $uri $uri/ =404;
limit_req zone=cms_static_per_ip burst=1000 nodelay;
location ~* \.(js|json|css|html|wasm|ttf|woff|woff2|gif|webp|png|jpg|jpeg|svg|dat)$ {
add_header Cache-Control "public, max-age=2592000";
access_log off;
add_header Cache-Tag "cms-client";
add_header Access-Control-Allow-Origin $http_origin always;
add_header Access-Control-Allow-Methods "GET, OPTIONS" always;
}
}
location ^~ /nitro-client/ {
alias /var/www/Octane/dist/;
try_files $uri $uri/ =404;
limit_req zone=cms_static_per_ip burst=1000 nodelay;
location ~* \.(js|json|css|html|wasm|ttf|woff|woff2|gif|webp|png|jpg|jpeg|svg|dat)$ {
add_header Cache-Control "public, max-age=2592000";
access_log off;
add_header Cache-Tag "cms-client";
add_header Access-Control-Allow-Origin $http_origin always;
add_header Access-Control-Allow-Methods "GET, OPTIONS" always;
if ($cors_headers) {
add_header Access-Control-Max-Age 1728000;
add_header Content-Type "text/plain; charset=utf-8";
return 204;
}
}
}
location = /gamedata { return 301 /gamedata/config/; }
location = /gamedata/ { return 301 /gamedata/config/; }
# ─── Gamedata: vier cache-klassen, want niet alles onder /gamedata/ is
# even veranderlijk.
#
# Dit pad had één regel voor de hele boom: `max-age=604800` (7 dagen). De
# Habbo-client haalt FurnitureData.json hier op, dus na een import bleef het
# client-side dagenlang de oude versie tonen — een nieuw geïmporteerd
# meubel was gewoon onzichtbaar. De purge van de `cms-gamedata`-tag
# (edge-cache.ts) raakt alleen de Cloudflare-kopie, niet de browser.
#
# 1. config/ — FurnitureData.json + de vertaalde bestanden. Verandert
# bij elke import. Kort, en `must-revalidate` sluit de
# "stuur uit de cache"-route uit zodat de client na de
# TTL een 304 vraagt in plaats van de oude body te hergebruiken.
# 2. bundled/ — nitro-bundles per sprite. De inhoud kan veranderen zonder
# dat de bestandsnaam verandert (schalen, repareren), dus
# ook revalideren, maar minder vaak: ze worden veel vaker
# opgehaald dan ze worden geschreven.
# 3. icons/ — `{classname}_icon.png`. Wordt wél herschreven onder
# dezelfde naam (repair-icons.ts, herimport), dus ook
# klasse 4's "nooit herschreven" geldt hier niet. Wel
# minder vaak dan 2: per uur een must-revalidate is één
# 304 per icon per uur, en een gerepareerd icon is zo
# binnen een uur zichtbaar in plaats van dagenlang oud.
# 4. alles wat overblijft (c_images, album*, clothes, …) — content-addressed
# of per item uniek, nooit herschreven onder dezelfde naam. Blijft lang.
location ^~ /gamedata/config/ {
alias /var/www/Gamedata/config/;
add_header Cache-Control "public, max-age=300, must-revalidate";
access_log off;
add_header Cache-Tag "cms-gamedata";
add_header Access-Control-Allow-Origin $http_origin always;
add_header Access-Control-Allow-Methods "GET, OPTIONS" always;
if ($cors_headers) {
add_header Access-Control-Max-Age 1728000;
add_header Content-Type "text/plain; charset=utf-8";
return 204;
}
error_page 404 = @gamedata_missing;
}
location ^~ /gamedata/bundled/ {
alias /var/www/Gamedata/bundled/;
add_header Cache-Control "public, max-age=3600, must-revalidate";
access_log off;
add_header Cache-Tag "cms-gamedata";
add_header Access-Control-Allow-Origin $http_origin always;
add_header Access-Control-Allow-Methods "GET, OPTIONS" always;
if ($cors_headers) {
add_header Access-Control-Max-Age 1728000;
add_header Content-Type "text/plain; charset=utf-8";
return 204;
}
error_page 404 = @gamedata_missing;
}
location ^~ /gamedata/icons/ {
alias /var/www/Gamedata/icons/;
add_header Cache-Control "public, max-age=3600, must-revalidate";
access_log off;
add_header Cache-Tag "cms-gamedata";
# Geen limit_req: gamedata is schijf-cache, geen CMS-backend. Een
# kamerladen vuurt honderden bestanden in één burst af en elke limiet
# hier leidde alleen tot zichtbaar gemiste icons.
add_header Access-Control-Allow-Origin $http_origin always;
add_header Access-Control-Allow-Methods "GET, OPTIONS" always;
if ($cors_headers) {
add_header Access-Control-Max-Age 1728000;
add_header Content-Type "text/plain; charset=utf-8";
return 204;
}
error_page 404 = @gamedata_missing;
}
location /gamedata/ {
alias /var/www/Gamedata/;
add_header Cache-Control "public, max-age=604800";
access_log off;
add_header Cache-Tag "cms-gamedata";
add_header Access-Control-Allow-Origin $http_origin always;
add_header Access-Control-Allow-Methods "GET, OPTIONS" always;
if ($cors_headers) {
add_header Access-Control-Max-Age 1728000;
add_header Content-Type "text/plain; charset=utf-8";
return 204;
}
error_page 404 = @gamedata_missing;
}
# Een ONTBREKEND gamedata-bestand mag nooit gecacht worden, en daarom
# krijgt elke 404 hier een eigen handler.
#
# Zonder deze handler stuurde nginx op een 404 helemaal geen Cache-Control:
# `add_header` geldt zonder `always` alleen voor 2xx/3xx. Cloudflare vond
# dan geen expliciete cache-instructie en nam de zone-instelling over:
# "Browser Cache TTL = 1 jaar". Gevolg: de 404 kwam terug als
# `cache-control: max-age=31536000` met `cf-cache-status: HIT` — dus
# vastgezet in de browser van de bezoeker én op de edge. Een icon dat één
# keer te vroeg werd opgevraagd (import nog bezig) bleef daarom het hele
# jaar een 404, ook nadat het bestand er wél stond. Dat was de "sommige
# icons laden wel, sommige niet"-klacht.
#
# `no-store` (niet een korte TTL): het bestand kan elk moment verschijnen,
# dus er is geen enkel venster waarin we een 404 willen vasthouden. De
# Cache-Tag blijft meegegeven zodat een al gecachte 404 alsnog te purgen is
# via `scripts/cf-purge.sh cms-gamedata`.
location @gamedata_missing {
add_header Cache-Control "no-store" always;
add_header Cache-Tag "cms-gamedata" always;
add_header Access-Control-Allow-Origin $http_origin always;
add_header Access-Control-Allow-Methods "GET, OPTIONS" always;
return 404;
}
location /camera/ {
alias /var/www/Camera/;
add_header Cache-Control "public, max-age=31536000, immutable";
add_header Cache-Tag "cms-camera";
}
location = /favicon.ico { expires 1y; access_log off; log_not_found off; try_files $uri =404; }
location = /robots.txt { expires 1d; access_log off; log_not_found off; try_files $uri =404; }
# ─── Static Next.js Assets ───
location /_next/static/ {
proxy_pass http://cms_app;
proxy_set_header Connection "";
proxy_http_version 1.1;
# Enige eigenaar: een enkele immutable header; de app-header wordt
# altijd verwisseld zodat er nooit twee tegensprekende ontstaan
# (ook op 404's).
proxy_hide_header Cache-Control;
add_header Cache-Control "public, max-age=31536000, immutable";
}
location /_next/data/ {
proxy_pass http://cms_app;
proxy_set_header Connection "";
proxy_http_version 1.1;
proxy_hide_header Cache-Control;
add_header Cache-Control "public, max-age=0, must-revalidate";
}
# ─── API Proxy's ───
location /api/auth/ {
proxy_pass http://cms_app;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header CF-Connecting-IP "";
proxy_set_header Connection "";
# Auth is per sessie: nooit cachen, en de app-header onderdrukken zodat
# er precies één Cache-Control overblijft.
proxy_hide_header Cache-Control;
add_header Cache-Control "private, no-cache, no-store, max-age=0, must-revalidate" always;
}
# ─── Publieke API: één gedeelde Cache-Control, geen byte-cache ───
#
# nginx is de enige plek die hier cacheverantwoordelijkheid heeft: de app
# zet dit op no-store (Next-force) en Traefik + Cloudflare voegen niets
# toe, dus er is geen tweede laag die met deze header concurreert. De
# body zelf wordt NIET tussen-gecachet (geen proxy_cache_*): stampede-
# bescherming doet src/lib/cache.ts (in-process single-flight + Redis).
# De header zet de TTL voor browser + CDN (10/60/300s + SWR).
location ~ ^/api/(?:staff|teams|guilds|photos|leaderboard|online|online/count|shop|shop/categories|values|values/categories|values/[0-9]+|radio/current-dj|radio/points/leaderboard)$ {
proxy_pass http://cms_app;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header CF-Connecting-IP "";
proxy_set_header Connection "";
proxy_hide_header Cache-Control;
add_header Cache-Control $cms_public_cc;
# Cloudflare cache-tag: laat de edge precies deze publieke API's cachen
# (via een cache-rule) en purge alleen deze tag na een CMS-wijziging.
add_header Cache-Tag "cms-public";
}
# ─── SSE / lange streams ───
#
# Drie dingen moeten kloppen of een EventSource-stroom knapt af:
# 1. proxy_buffering off — anders houdt nginx het antwoord vast tot de
# verbinding sluit, dus de browser ziet de stream pas als een blok.
# 2. proxy_read_timeout — de default van 60s beëindigt een stroom die
# tijdens een batch-job even stilvalt, waarna de client reconnectt en
# opnieuw 504 krijgt: een reconnect-loop die de app juist belast.
# 3. send_timeout — de server-level 10s meet de pauze tussen twee writes.
# Een stream die 25s pingt, of een batch die minuten niets doet, wordt
# daar dus losgekapt. Daarom hier een eigen, ruime waarde.
location ~ ^/api/(?:online/count/stream|radio/stream|admin/import/.*|admin/studio/nitro-cleanup.*)$ {
proxy_pass http://cms_app;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header CF-Connecting-IP "";
proxy_set_header Connection "";
proxy_buffering off;
gzip off;
chunked_transfer_encoding on;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
send_timeout 3600s;
proxy_hide_header Cache-Control;
add_header Cache-Control "private, no-cache, no-store, max-age=0, must-revalidate" always;
# Vrijwel elke SSE-route miste dit; zonder de header blijft nginx
# alsnog bufferen, ook met proxy_buffering off.
add_header X-Accel-Buffering "no" always;
}
location /api/badges/custom {
proxy_pass http://127.0.0.1:2096;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header CF-Connecting-IP "";
proxy_set_header Connection "";
# De emulator levert zelf geen Cache-Control; zonder proxy_hide_header
# zou de app-header hier een tweede keer worden toegevoegd.
proxy_hide_header Cache-Control;
add_header Cache-Control "private, no-cache, no-store, max-age=0, must-revalidate" always;
}
# ─── Imaging & media: de app levert de eigen Cache-Control ───
# De catch-all hieronder forceert no-store; avatars en uploads zijn
# onveranderlijk per sleutel en moeten door de browser gecachet worden.
location /api/imaging/ {
proxy_pass http://cms_app;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header CF-Connecting-IP "";
proxy_set_header Connection "";
proxy_read_timeout 30s;
}
location /api/media/ {
proxy_pass http://cms_app;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header CF-Connecting-IP "";
proxy_set_header Connection "";
}
# ─── Hoofd-routering ───
location / {
proxy_pass http://cms_app;
limit_req zone=cms_req_per_ip burst=60 nodelay;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header CF-Connecting-IP "";
proxy_set_header Connection "";
# De HTML is per sessie: `auth()` in de homepage-layout stuurt
# ingelogde bezoekers door naar /me, en de CSP-nonce is per request.
# Dus nooit cachen — maar wel als één enkele, expliciete header.
# Zonder proxy_hide_header voeg je hier een tweede, tegensprekende
# Cache-Control toe aan degene die Next al meestuurt.
proxy_hide_header Cache-Control;
add_header Cache-Control "private, no-cache, no-store, max-age=0, must-revalidate" always;
}
}
@@ -1,43 +0,0 @@
# Include at nginx http scope (for example /etc/nginx/conf.d/cms.conf).
# Mode: browsers connect directly to this nginx, on the CMS Docker host.
# Replace EVERY hotel.example and both certificate paths before nginx -t.
# Requires ngx_http_realip_module: $realip_remote_addr keeps the socket peer
# even when an unrelated global real_ip configuration rewrites $remote_addr.
server {
listen 80;
listen [::]:80;
server_name hotel.example;
if ($host != hotel.example) { return 444; }
return 308 https://hotel.example$request_uri;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name hotel.example;
if ($host != hotel.example) { return 444; }
ssl_certificate /etc/letsencrypt/live/hotel.example/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/hotel.example/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
# Studio's authenticated attachment endpoints accept at most 52 MiB.
# This ingress allowance includes multipart overhead; application caps remain.
client_max_body_size 64m;
location / {
proxy_pass http://127.0.0.1:3002;
proxy_http_version 1.1;
proxy_set_header Host hotel.example;
proxy_set_header X-Forwarded-Host hotel.example;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header X-Forwarded-Port 443;
proxy_set_header X-Forwarded-For $realip_remote_addr;
proxy_set_header X-Real-IP $realip_remote_addr;
proxy_set_header CF-Connecting-IP "";
proxy_set_header X-Real-Client-IP "";
proxy_set_header Forwarded "";
proxy_set_header Connection "";
proxy_buffering off;
proxy_read_timeout 300s;
proxy_cache off;
}
}
-34
View File
@@ -1,34 +0,0 @@
types {
text/html html htm shtml;
text/css css;
text/xml xml;
text/plain txt;
application/javascript js mjs;
application/json json map;
application/ld+json jsonld;
application/rss+xml rss;
application/wasm wasm;
application/xml xsd xsl;
font/ttf ttf;
font/otf otf;
font/woff woff;
font/woff2 woff2;
image/svg+xml svg svgz;
image/bmp bmp;
image/gif gif;
image/jpeg jpeg jpg;
image/png png;
image/webp webp;
image/avif avif;
image/x-icon ico cur;
video/mp4 mp4 m4v;
video/webm webm;
audio/mpeg mp3;
audio/ogg ogg;
audio/wav wav;
application/octet-stream dat bin swf;
application/zip zip;
application/gzip gz;
application/pdf pdf;
application/vnd.apple.mpegurl m3u8;
}
@@ -1,51 +0,0 @@
# ALTERNATIVE to nginx-direct.example.conf; never enable both for the same host.
# Remote edge -> TLS -> this nginx on the CMS host -> loopback CMS.
# Replace hotel.example/certificate paths and BOTH occurrences of 203.0.113.10/32.
# The example peer is reserved documentation space, so it permits no real edge.
# Requires ngx_http_realip_module. The remote edge MUST overwrite X-Forwarded-For
# with one verified client IP and enforce the public HTTPS/Host configuration.
geo $realip_remote_addr $cms_trusted_edge {
default 0;
203.0.113.10/32 1;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name hotel.example;
if ($host != hotel.example) { return 444; }
if ($cms_trusted_edge = 0) { return 403; }
ssl_certificate /etc/letsencrypt/live/hotel.example/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/hotel.example/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
client_max_body_size 64m;
set_real_ip_from 203.0.113.10/32;
real_ip_header X-Forwarded-For;
real_ip_recursive off;
location / {
proxy_pass http://127.0.0.1:3002;
proxy_http_version 1.1;
proxy_set_header Host hotel.example;
proxy_set_header X-Forwarded-Host hotel.example;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header X-Forwarded-Port 443;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header CF-Connecting-IP "";
proxy_set_header X-Real-Client-IP "";
proxy_set_header Forwarded "";
proxy_set_header Connection "";
proxy_buffering off;
proxy_read_timeout 300s;
proxy_cache off;
}
}
# Cloudflare variant: use this same restricted-edge mode, NOT the direct mode.
# Replace the documentation peer in BOTH geo/set_real_ip_from lists with the
# current verified Cloudflare IPv4 AND IPv6 CIDRs, then change real_ip_header to
# CF-Connecting-IP. Use Full (strict) TLS and review authenticated origin pulls.
# CF-Connecting-IP is still removed before forwarding to the CMS: nginx sends
# only its normalized, trusted result in X-Forwarded-For and X-Real-IP.
-73
View File
@@ -1,73 +0,0 @@
# Canonical nginx config for the EpicNabbo CMS edge.
# Source of truth: repository deployment/proxy/nginx-cms.conf (the site block)
# and this file. Installed/synced by scripts/nginx-sync.sh so it cannot be
# lost again while nginx keeps running on an in-memory copy.
#
# Traffic path: Cloudflare -> Traefik (:443) -> nginx (:9443) -> CMS (:3002),
# with direct Cloudflare-origin and game-client (ws.epicnabbo.nl) connections
# also terminating on :9443.
# nginx is the last layer that can still rewrite Cache-Control, so it owns the
# headers it adds explicitly; everything proxied to the CMS is passed through
# untouched unless this file says otherwise.
user www-data;
worker_processes auto;
# Raise the file-descriptor rlimit for the workers. Must stay <= the master's
# RLIMIT_NOFILE *hard* limit, otherwise nginx refuses to start with
# "setrlimit(RLIMIT_NOFILE) failed". Bounded from above by the systemd drop-in
# /etc/systemd/system/nginx.service.d/override.conf (LimitNOFILE=65536).
worker_rlimit_nofile 65536;
pid /run/nginx.pid;
error_log /var/log/nginx/error.log warn;
events {
worker_connections 2048;
use epoll;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Compression is done once, at the edge (Traefik / Cloudflare). Enabling
# gzip here too would double-compress proxied responses and fight Vary.
gzip off;
sendfile on;
tcp_nopush on;
server_tokens off;
keepalive_timeout 30s;
client_max_body_size 64m;
client_body_buffer_size 16k;
client_header_buffer_size 1k;
large_client_header_buffers 4 8k;
# Rate limiting per client IP.
#
# Two zones, because a room load and a page load are not the same thing.
# Loading a Nitro room fires several hundred gamedata icons in one burst;
# at the page rate that produced 503s on real players. Static assets
# therefore get their own, much higher allowance. These are small immutable
# files, so a request rate is not what protects them anyway — nginx already
# serves them with must-revalidate, and the CMS upstream stays behind
# cms_req_per_ip for the expensive routes.
limit_req_zone $binary_remote_addr zone=cms_req_per_ip:10m rate=30r/s;
limit_req_zone $binary_remote_addr zone=cms_static_per_ip:10m rate=1000r/s;
limit_conn_zone $binary_remote_addr zone=cms_conn_per_ip:10m;
# Blue/green cutover: ci-deploy.sh writes the active upstream here, and
# `proxy_pass http://cms_app` below follows it via graceful nginx -s reload.
upstream cms_app {
include /etc/nginx/snippets/cms_upstream_servers.conf;
}
# Cache policy maps and server blocks live in the site file so they are
# synced together and can never drift apart.
include /etc/nginx/sites-enabled/*.conf;
# Trusted edge / real-IP handling (regenerated by scripts/cf-ips-sync.sh
# from the live Cloudflare ranges; installed via scripts/nginx-sync.sh).
include /etc/nginx/conf.d/cloudflare-ips.conf;
}
-65
View File
@@ -1,65 +0,0 @@
# ─────────────────────────────────────────────────────────────────────────────
# Next.js CMS — blue/green
# ─────────────────────────────────────────────────────────────────────────────
x-cms: &cms
image: epicnext-cms:${CMS_RELEASE:-local}
build:
context: .
dockerfile: Dockerfile
args:
NEXT_DEPLOYMENT_ID: ${CMS_RELEASE:-unknown}
network: host
network_mode: host
stop_grace_period: 15s
restart: unless-stopped
env_file:
- .env
volumes:
- ./public/nitro-assets:/app/public/nitro-assets
- ./public/swf:/app/public/swf
- ./storage:/app/storage
- /var/www/Gamedata:/var/www/Gamedata
# ── Resource limits ──
mem_limit: 6g
memswap_limit: 7g
cpus: 2.0
pids_limit: 512
healthcheck:
test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:'+(process.env.PORT||'3002')+'/api/health').then(r=>{process.exit(r.ok?0:1)}).catch(()=>process.exit(1))"]
interval: 15s
timeout: 5s
retries: 3
start_period: 40s
services:
cms:
<<: *cms
container_name: epicnext-cms
environment:
- HOSTNAME=0.0.0.0
- PORT=3002
cms-green:
<<: *cms
container_name: epicnext-cms-green
profiles: ["green"]
environment:
- HOSTNAME=0.0.0.0
- PORT=3003
byparr:
image: ghcr.io/thephaseless/byparr:latest
container_name: byparr
network_mode: host
restart: unless-stopped
environment:
- LOG_LEVEL=INFO
pids_limit: 256
healthcheck:
test: ["CMD", "curl", "http://localhost:8191/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 30s
-1
View File
@@ -1 +0,0 @@
gitlab.epicnabbo.nl/simo/epicnext-cms
-118
View File
@@ -1,118 +0,0 @@
# Refactor del catalogo HK — analisi e programma
Data: 6 settembre 2026. Base verificata: main, commit 9b0ea2fb. Documento di proposta, non implementazione approvata. Il sito /admin/catalog reindirizza al login senza sessione staff: nessuna prova delle mutazioni sul database di produzione. Le criticità indicate sono percorsi verificati nel codice; gli effetti concorrenti richiedono riproduzione controllata.
## Obiettivo e perimetro
Un catalogo HK con un solo ambiente di lavoro, regole coerenti e operazioni recuperabili. Conservare stile HK, icone reali, salvataggio diretto, catalogo normale e Builder Club. Nessun ritorno dei Preferiti.
Inclusi: albero, categorie, offerte, prezzi, bundle, disponibilità, proprietà condivise dei furni, traduzioni, ricerca, anteprima, operazioni massive, manutenzione, collegamenti a Catalog Studio e sincronizzazione Git/hotel.
Catalog Studio conserva la responsabilità di importare, convertire e riparare .nitro, icone e furnidata. Il refactor collega questi strumenti alla selezione del catalogo; non comporta riscrivere il convertitore, cambiare protocollo dell'emulatore o sostituire il sistema Git/Gitea già esistente.
## Inventario verificato
Sono già presenti virtualizzazione dell'albero, trascinamento, multiselezione, griglia/tabella, editor dei prezzi, anteprima negozio, import massivo, traduzioni, manutenzione e coda di export Git. Vanno riutilizzati.
| File | Righe attuali | Responsabilità da separare |
|---|---:|---|
| src/app/admin/catalog/[id]/catalog-items-table/catalog-items-table.tsx | 2342 | Rendering, selezione, editor offerta/furno, prezzi massivi, drag and drop, dialoghi |
| src/components/admin/catalog-manager/sortable-tree.tsx | 1135 | Lettura albero, mutazioni, ricerca, trascinamento, comandi |
| src/components/admin/catalog-manager/inline-editor.tsx | 775 | Fetch, stato modifiche, schede, salvataggio, anteprima |
| src/app/admin/catalog/[id]/catalog-page-form.tsx | 738 | Campi, layout, media, salvataggio |
| src/app/admin/catalog/[id]/catalog-translate-tab.tsx | 617 | Selezione, proposta traduzioni, applicazione |
| src/app/admin/catalog/builder-club/bc-manager.tsx | 608 | Gestione parallela BC |
| src/app/admin/catalog/page.tsx | 526 | Query, conteggi, varianti normale/BC, composizione UI |
Le dimensioni aiutano a trovare i punti di intervento: l'obiettivo non è un limite arbitrario di righe, ma responsabilità verificabili e riutilizzabili.
## Problemi e interventi
| Priorità | Evidenza | Intervento |
|---|---|---|
| P0 | sortable-tree.tsx invia il riordino dei fratelli con Promise.allSettled, una action per riga; catalog.ts aggiorna RCON per ciascuna | Un comando batch con lista completa, validazione, transazione e un solo evento di aggiornamento |
| P0 | catalog-items.ts riordina le offerte con update sequenziali fuori transazione | Stesso contratto atomico per l'ordine delle offerte |
| P0 | updateCatalogPage accetta parentId direttamente; il controllo cicli è separato in movePage | Validazione comune per creazione, form, spostamento e API; controllare destinazioni inesistenti e concorrenza |
| P0 | deletePage normale sposta figli, elimina offerte e pagina separatamente | Transazione, analisi dell'impatto e snapshot ripristinabile |
| P0 | updateCatalogItem modifica pagina, offerta e items_base con scritture separate | Transazione e verifica che il furno appartenga all'offerta; scope distinto per proprietà condivise |
| P1 | cascadeDelete non mantiene un insieme di nodi visitati; il calcolo profondità BC è ricorsivo senza guardia ai cicli | Lettura tollerante di dati incoerenti, diagnostica e arresto sicuro delle traversate |
| P1 | handleEditTab modifica lo stato prima della conferma; chiusura X bypassa la protezione | Un unico controllo delle modifiche per cambio pagina, offerta, scheda, uscita e navigazione |
| P1 | loadPage/loadItemsData non annullano o identificano la richiesta precedente | AbortController e identità della selezione; solo la risposta corrente può aggiornare l'editor |
| P1 | Il salvataggio ignora il booleano restituito da RCON; Git opera in coda | Distinguere DB salvato, invio hotel riuscito/fallito e stato Git; retry senza risalvare i dati |
| P1 | loadCatalogItemsData usa Number(value) || fallback per order_number, offer_id e amount | Definire semantica di zero/null per campo e testare il round trip prima di cambiare i fallback |
| P2 | Tutte le offerte e metadati sono caricati insieme; filtro con CAST(page_id AS CHAR) | Misurare query/payload, separare elenco e dettagli, paginazione e adapter compatibile INT/VARCHAR |
| P2 | Editor normale/BC e form condividono solo parte delle regole; testi anche letterali | Contratti comuni, differenze BC esplicite, traduzioni e permessi coerenti |
Riferimenti principali: src/actions/catalog.ts, src/actions/catalog-items.ts, src/actions/catalog-bc.ts, src/lib/services/catalog-tree.ts, src/lib/services/catalog-items-loader.ts, src/app/api/admin/catalog/tree/route.ts, src/components/admin/catalog-manager/catalog-manager-dialog.tsx, src/components/admin/catalog-manager/inline-editor.tsx.
## Alternative
1. **Pulizia dei file mantenendo tutti gli editor:** rischio iniziale basso, ma conserva duplicazioni e differenze operative. Utile solo come passaggio iniziale.
2. **Refactor progressivo con un editor principale — consigliato:** servizi comuni prima, poi promozione del Visual Manager a pagina. Permette piccoli rilasci e confronti tra vecchio e nuovo percorso.
3. **Riscrittura completa:** libertà maggiore, ma più rischio di perdere casi speciali, compatibilità DB e funzioni già presenti. Non giustificata dall'inventario attuale.
## Architettura proposta
Modulo src/features/catalog con confini chiari:
- domain/: tipi Page, Offer, FurnitureReference, CatalogKind; validazione gerarchie, prezzi, bundle e disponibilità; nessuna dipendenza React/DB.
- server/queries/: letture albero, elenco offerte, dettaglio e ricerca; output serializzabile esplicito.
- server/commands/: create/update/move/reorder/delete; autorizzazione, validazione, transazioni, controllo revisione e audit.
- server/repositories/: accesso Drizzle e compatibilità delle colonne; adapter normale/BC senza fingere che tutti i campi coincidano.
- client/: stato selezione, modifiche locali, operazioni in corso, caricamento e gestione conflitti.
- components/: albero, elenco offerte, editor categoria, editor offerta, dettagli furno, diagnostica, stato sincronizzazione.
Le route e le action attuali rimangono inizialmente adapter sottili. Un unico risultato di operazione include ID operazione, revisione, elementi modificati, eventuali errori di campo e stato sincronizzazione. Non introdurre nuove librerie prima di verificare i limiti degli strumenti già installati.
Flusso di scrittura: permesso → validazione → verifica revisione → transazione DB con audit → risposta di salvataggio → aggiornamento hotel/export Git. La durabilità del passaggio DB→coda va garantita con un evento persistito nella transazione o meccanismo equivalente verificato. Un fallimento Git/RCON non deve far ripetere una creazione già committata. Riutilizzare il worker e la coda esistenti, aggiungendo idempotenza dove manca.
## UX proposta
Pagina /admin/catalog con barra: Normale/BC, ricerca, nuova categoria, aggiungi furni, stato operazioni. Sotto: categorie a sinistra, offerte al centro, dettagli a destra. Il pannello dettagli si richiude; su schermi piccoli diventa una vista dedicata. Un solo scorrimento per ciascuna area, azioni di salvataggio sempre raggiungibili.
La URL conserva catalogo, categoria, offerta, vista e ricerca; i campi non salvati restano nello stato locale. Indietro/avanti e ricaricamento devono riaprire il contesto corretto. I vecchi URL dei dettagli continuano a funzionare.
Tre oggetti riconoscibili:
- Categoria: percorso, titolo, icona, layout, visibilità e requisiti.
- Offerta: prezzo, valuta, quantità, componenti bundle, disponibilità e ordine.
- Furno condiviso: classname, sprite, dimensioni e interazioni; mostrare quante offerte lo referenziano prima di una modifica globale.
Idee operative:
- Ricerca trasversale per nome, classname, ID pagina/offerta/furno e sprite ID, con percorso nei risultati.
- Selettore visuale di categoria e layout; proprietà tecniche nelle Avanzate.
- Prezzi con icone reali delle valute; mostrare il prima/dopo delle operazioni massive, arrotondamenti ed elementi esclusi.
- Multiselezione con riepilogo di spostamento/eliminazione; dopo un errore mantenere selezionati i falliti.
- Anteprima del negozio già esistente integrata nel contesto; non presentarla come prova completa del comportamento del client hotel.
- Diagnostica su richiesta: offerta, SQL, furnidata, Nitro e icona separati. Collegamento a Catalog Studio sul furno esatto; nessuna scansione pesante a ogni apertura.
- Storico di chi/cosa/quando con differenze e ripristino. Il ripristino controlla revisioni successive: non sovrascrive in silenzio modifiche di altri operatori e non annulla acquisti già avvenuti.
- Riepilogo visibile: salvato, invio hotel, Git. Gli errori hanno riferimento al monitor CMS.
- Stati vuoti, errori, caricamento e sola lettura distinti; traduzioni complete e uso da tastiera.
## Programma di lavoro e criteri di uscita
| Lotto | Consegna | Criterio per proseguire |
|---|---|---|
| 1. Baseline | Matrice funzioni/route/permessi normale e BC; fixture con bundle, LTD, offerte speciali, zeri/null, alberi incoerenti; misure query e rete | Tutti i flussi esistenti hanno una destinazione nel piano, senza omissioni |
| 2. Integrità | Validatori, transazioni di riordino/spostamento/eliminazione, gerarchie sicure, revisioni | Un fallimento intermedio non lascia dati parziali; due operatori non si sovrascrivono |
| 3. Servizi condivisi | Query/command/repository e risultato comune; vecchie route come adapter | Vecchie UI superano le stesse prove con il nuovo backend |
| 4. Stato editor | Unica gestione delle modifiche, richieste annullabili, risposta coerente con selezione | Annullare l'uscita conserva tutto; cambi rapidi mostrano sempre l'ultima selezione |
| 5. Pagina unificata | Visual Manager nella pagina, griglia/tabella condivise, URL, layout adattivo | Parità normale/BC e vecchi link conservati; niente perdita di scroll o azioni nascoste |
| 6. Operazioni avanzate | Ricerca, editor bundle, prezzi massivi con differenze, storico e diagnosi contestuale | Gli effetti sono spiegati prima dell'applicazione; retry applica solo ciò che manca |
| 7. Sincronizzazione | Stato DB/hotel/Git, operazioni persistenti, retry/idempotenza | Guasto dopo commit e riavvio worker non duplicano né perdono l'operazione |
| 8. Prestazioni e rimozione duplicati | Paginazione, caricamento progressivo, accessibilità, eliminazione vecchi componenti | Confronto misurato e prove finali; nessuna route o funzione rimasta senza equivalente |
I lotti 2 e 7 condividono il contratto delle operazioni: progettare subito evento persistente e idempotenza, anche se la UI di stato arriva dopo. Nessuna stima in giorni finché non sono note dimensioni reali del catalogo, varianti DB e casi speciali attivi. Ogni lotto può richiedere più PR piccole; niente sostituzione monolitica.
## Verifica e rilascio
Test unitari delle regole; integrazione su MariaDB per rollback, concorrenza e varianti INT/VARCHAR; browser con permessi lettura/modifica, desktop e schermo ridotto. Simulare doppio submit, timeout, risposta fuori ordine, fallimento RCON, Git non raggiungibile, riavvio dopo commit. Conservare test e componenti esistenti finché la parità non è dimostrata.
Registrare baseline e risultati per categorie grandi/piccole: richieste per riordino, tempo DB, payload, tempo fino a editor utilizzabile, risposte fallite. Non promettere percentuali senza dati.
Rilascio progressivo con selezione reversibile del nuovo editor. Il ritorno alla UI precedente deve usare gli stessi servizi corretti. Migrazioni additive e compatibili; il rollback dell'app non deve richiedere la cancellazione di dati. Eliminare le vecchie UI solo dopo parità verificata. Confermare CI, deploy, health e prove staff prima di dichiarare risolto il flusso live.
## Primo passo consigliato
Lotti 1 e 2: inventario di compatibilità e correzione delle operazioni a rischio, mantenendo inizialmente l'aspetto corrente. Poi estrarre i servizi e unificare l'editor. È la sequenza che permette di migliorare UX senza portare avanti gli stessi difetti dentro una nuova schermata.
-156
View File
@@ -1,156 +0,0 @@
# CMS upgrade — September 2026
## Operator changes
| Area | Behavior and location |
| --- | --- |
| Release | Deployment checks HTTP health, release identity and Chromium pages before marking the running image verified. Registry publication reuses that verified digest on the shared runner; independent hosts build and verify their own image. |
| Shared HK | Dialogs scroll within the available viewport. Table column preferences persist per page in the current browser session; filters already remain in the URL. No favorites added. |
| Catalog Studio | Dedicated detail drawer and five separate completeness states: SQL, offers, furnidata, icon and Nitro. Sprite/type conflicts are consistently excluded from import and linked to audit. Missing source files are never represented as available. |
| Operations | Command center includes permission-filtered error groups, personal import failures, open support tickets and news drafts. A failed source is shown separately from an empty source. |
| Error center | Retained occurrence counts, first/last times, identified users, release counts, self-assignment and recognized local links. Assignment requires edit permission and is audited. |
| News | Private server-backed autosave, recover/discard/retry, prior saved revisions restored as a draft, and concurrent-edit detection. New status/search filters and pagination make older drafts reachable. |
| Jobs | Cancellation finishes the current item and stops pending items. Completed work stays completed. Uncertain interrupted mutations are excluded from retry. Live lease checks stop known stale worker writes. |
| Installation | `/admin/devops/installation` shows release, DB latency, Redis, emulator, storage permissions, migration history and worker heartbeat. Renderer defaults are recognized. Registry access is explicitly unverified from the web process. |
| Public dashboard | Current/next published event, clearer unread-message action, useful empty/error states and mobile layout refinements. |
| Audit | Exact actor/action and UTC date filters, readable recorded before/after values and permission-protected CSV of the filtered page, capped at 100 rows. |
| Performance | Active import polling remains 5 seconds; idle polling is 30 seconds and pauses in hidden tabs. History returns at most 30 owned jobs and initially renders 50 items per job. Health probes are deduplicated within a render; diagnostics report observed probe duration. |
| Text | New messages are translated in English, Italian and Dutch. Other locales have explicit English fallback strings. Existing translation debt is not reported as resolved. |
## Deployment requirements
- Apply migration `0026_article_editor_recovery.sql` through `pnpm db:migrate` before enabling the new news editor. It adds private drafts and revision tables without modifying existing articles.
- Keep `storage` persistent and writable. Error assignments and import cancellation markers use the existing shared storage.
- Run the existing `pnpm jobs:worker` process with the installation configuration. It now publishes a heartbeat to Redis every minute. A web process alone does not establish that scheduled-news jobs are running.
- The deploy runner installs Chromium before cutover. Browser checks visit only public login/news/staff pages; they do not create production content or authenticate staff. The host must satisfy Chromium system-library requirements.
- Use the existing Gitea registry secrets. The CMS does not read or display those credentials.
## Boundaries
- Operations is a bounded operational summary: errors use at most 1,000 retained events and imports use the latest 30 owned jobs. Empty checked records do not prove that all historical work is resolved.
- Import history bounds payloads and concurrent file reads. Directory metadata scanning and worker enumeration still scale with stored history.
- Redis lease checks and file saves are separate operations. They reduce stale writes but do not provide atomic fencing across Redis, SQL and filesystem operations. An import interrupted after SQL may require local-data inspection.
- Revision history displays the latest 20 saved versions; revisions are retained in the database. New-article recovery has one private slot per staff account.
- The database connection probe is a measurement, not a performance benchmark. No throughput or latency improvement is claimed without production measurements.
- A rollback restores an application image; it does not reverse database migrations. The new tables are additive.
## Verification
Local verification on 2026-09-09:
- Production build succeeded with fixture configuration and an intentionally unavailable database. Build-time fallback logs are expected in this check.
- Full Vitest run: 254 files passed, 4 skipped; 1,466 tests passed, 6 skipped. Coverage thresholds passed (19.89% lines); this does not imply exhaustive coverage.
- Global Biome rules/import checks passed across 1,328 files; modified source/locales were formatted separately to avoid unrelated Windows line-ending changes.
- Translation audit: no invalid ICU messages, variable mismatches or missing static references. Existing locale gaps and 1,560 hardcoded-text candidates still need editorial work; they are not silently marked translated.
- Headless Edge verification of actual shared components with compiled CSS and the CMS theme at widths 1,280 and 390 pixels: the switch changes state and thumb position, the dialog stays within the 720px viewport, the final button is reachable, and the background page does not scroll. This isolated fixture does not establish full authenticated-page parity.
- Deployment rollback, verified-digest publication, ownership/cancellation and concurrent news edit behavior have focused regression tests.
Docker runtime, database migration execution and authenticated browser flows still require an integration environment. Check the Gitea pipeline and live release identifier after publication. A successful local build is not production verification.
## Catalog packages
The normal catalog toolbar now opens a dedicated Catalog packages dialog.
Create a named draft from selected categories and their descendants, either to
update those categories or copy them under a chosen parent. Drafts are shared
with authorized staff; saving a draft does not modify the live catalog.
Edit category metadata and offer prices, or review bulk price changes before
applying them to the draft. The catalog preview supports category navigation,
search, real local furniture icons and rank/Club/VIP access simulation. It does
not render the game client or evaluate ancestors outside the selected package;
special layouts and that access limitation are disclosed in the preview.
Publication requires a saved draft and a fresh review. Concurrent source changes
block publication; version checks prevent one editor overwriting another.
Copying preserves the underlying category and offer fields and remaps internal
references while retaining furniture IDs and assets. The catalog writes and
published result are committed together; retrying the same published package
does not copy it again. Failures in hotel notifications, audit or Git export
scheduling after commit are reported as warnings rather than failed publication.
Apply additive migration `0027_catalog_packages.sql` before opening this tool.
Existing migration automation discovers the file. Limits are 200 categories,
500 offers and 8 MB of package data. Package source checks inspect at most 20,000
catalog categories. Publication briefly locks category rows while validating and
writing changes, so large live catalogs should be checked under realistic load.
English, Italian and Dutch copy is provided; other locales use the new English
strings pending translation. No new dependency is required.
Validation: 1,506 tests passed (six skipped), type checking, lint, translation
contracts and a production build with fixture configuration. A browser fixture
verified the real dialog at 1280 and 390 pixels; server actions were simulated.
The new database migration and package publication have not run in production.
## Housekeeping search and user overview
The existing global search now includes furniture, normal/Club catalog categories
and both ticket sources. Results respect module permissions, accept single-digit
IDs, and remain usable when one source fails. Keyboard navigation and cancellation
prevent stale search responses from replacing newer results.
User details open on an operational overview with up to five records from each
authorized source: bans, active mute, support tickets, help tickets, reports,
payments, catalog purchases and audit activity. Failed sources are distinguished
from empty results. User detail and edit pages also apply log permissions before
loading activity and exposing counters.
Italian and Dutch navigation, user management, news and support labels were
reviewed. The new search and overview copy has English, Italian and Dutch text;
other locales receive English fallback strings. This is a focused editorial pass,
not a full translation of every CMS page. No database migration or dependency
change is required. Browser checks use real components with simulated data at
1280 and 390 pixels; production database behavior still needs deployment validation.
## Operational reliability and recovery
- Audit history now records category settings (normal/Club), individual/bulk offer prices, update-mode package publication and news edits inside the write transaction. The audit screen previews and restores individual changes after locking and comparing the current recorded fields. Deleted records, hierarchy changes, LTD counters, imports and historical entries without complete snapshots cannot be restored. Restores create their own history entry. Apply migration `0028_history_snapshots.sql` before running this version: it widens audit snapshots to MEDIUMTEXT without deleting existing data.
- `/admin/operations` reuses durable import jobs, stable history pagination and owner-scoped failed-item retries. A deterministic child ID prevents duplicate retries. The shared Git export queue displays actual pending/running state and latest result; synchronous/SSE synchronization remains linked rather than represented as a durable job history.
- Catalog maintenance includes a read-only integrity report for normal/Club categories, offers, furniture references and local icons. Known sentinel IDs are preserved. Only categories pointing to a missing positive parent have an automated repair: preview lists every affected category and apply compares the locked graph before reattaching those categories at the root. No records are deleted. Other issues require an explicit manual edit. Reports display up to 200 issues with complete counts; unavailable icon storage is distinguished from missing assets.
- CMS errors support exact release and time filters plus frequency sorting. Counts refer to retained matching events, while group resolution remains current across releases.
- User/settings forms now protect unsaved edits and preserve failed submissions. User/news validation errors appear at the affected fields; settings show returned validation errors inline. Existing submission locking is retained and tested in a browser.
- `/admin/permissions/preview` shows one role's section access and known CMS grants using live ACL and the existing highest-rank policy. It never changes sessions. Additional user roles, navigation customization and record-specific authorization remain explicit limits of the preview.
New UI copy is supplied in English, Italian and Dutch; other locales receive English fallback strings. No new runtime dependencies. Browser fixtures use real UI components with simulated server responses; the database migration and production behavior have not been exercised on the live hotel.
Validation for this increment: 1,589 tests passed, six skipped; TypeScript, Biome, translation contracts and fixture production build passed. Browser checks covered user/settings/news forms, permission preview, CMS errors, integrity preview and history restore at 1280 and 390 pixels. Double submission, stale preview, blocked navigation, field focus and horizontal overflow were checked with simulated server actions. No live database writes or deployment were performed.
## September 11: public pages and staff workflows
- Docker stages now follow the exact `.nvmrc` release, enforced by the toolchain check.
- `/news` supports search, ordering by effective publication date and real pagination.
- `/events` supports upcoming/ongoing/completed filters, explicit UTC week windows, local displayed times and personal registrations.
- `/search` searches users, open rooms, published news and events with independent pagination and partial failure states.
- `/me` shows support replies, incoming friend requests, the next registered event and available referral rewards. Reply availability does not claim unread status.
- Profile privacy is managed in `/settings`. Wallet values are private by default; visitors do not receive hidden sections in HTML. Photo galleries initially show six photos and can expand to the loaded limit of 24.
- Ticket desks support waiting-for-staff and assignment filters, with elapsed time since the latest reply.
- HK table views save filters, order and visible columns per account and table (maximum 20). Existing session column preferences remain available until a named view is applied.
- Official and clone synchronization run through the existing durable import queue. Reloading restores history; interrupted uncertain writes still require inspection before repair. Successful items are not repeated.
- Publication preflight validates URL syntax/protocols and schedules, shows affected page links and keeps existing article previews. It does not claim remote URLs are reachable. Drafts remain savable. Partial event updates preserve omitted fields.
- Admin APIs return `x-operation-id`; server errors, staff audit records and import jobs share correlation context. Error and audit screens link to each other. Older records without this context remain readable.
- Public reads distinguish unavailability from empty results and real 404s, preserving independently available sections on home, dashboard, staff, photos, rankings and groups/forums.
### Data and verification
Additive migrations `0029_admin_table_views.sql` and `0030_profile_privacy.sql` run through the existing deployment migration runner. They create CMS-owned tables and do not change emulator user settings. Keep the existing shared storage volume and background jobs worker for durable imports.
Browser verification used real components with controlled data fixtures at 1280 and 390 pixels, including failure and partial-result cases. Production compilation and full lint were checked locally. No production content was created during those checks; real authenticated content and external source availability remain environment-dependent.
## Original furniture bundle recovery and progress
Catalog Studio queued imports and repairs now search other enabled Nitro sources when their initial downloads/conversion produce no local bundle. Recovery checks an exact classname, floor/wall type and positive revision against the source furnidata, then validates the bundle filename, internal name and PNG texture before writing it. It does not copy the alternative source's prices, IDs or descriptive metadata.
The recovery pass checks at most eight eligible sources, excludes the selected source, and has a 20-second network budget with four-second request limits. Catalog downloads are capped at 20 MiB; bundle downloads and attachment decompression are capped at 50 MiB. A bounded catalog cache avoids downloading full furnidata for every item. Blocked or incompatible sources can still require the original bundle to be attached manually.
Import history displays the current phase and elapsed time, the last phase on failure/interruption, and the source/revision of a recovered bundle. Phases are persisted under the existing worker lease; a retry clears old phase/provenance fields. Synchronization jobs also report their existing importer phases, but their clone-specific asset strategy is unchanged.
No additional secrets or environment variables are needed. Source definitions remain managed through the existing source configuration.
## Catalog workflow and public diagnostics
- Bulk offer edits retain the existing preview and now record complete price/category snapshots. The success notification offers an atomic batch Undo for 15 seconds; individual changes remain restorable from audit history afterward. Undo rejects changed records or missing categories rather than overwriting newer edits. No additional migration is needed beyond the existing history snapshot migration.
- Catalog Studio preserves the existing in-place search/filter/selection flow and now restores list scroll and focus after closing furniture details. Escape closes details before clearing selection. Obsolete list responses cannot replace a newer search; switching source invalidates pending review preparation.
- Import review groups furniture needing completion, conflicting records and unverified components. Each row lists missing or unknown components and suggests the next action. These are inspection recommendations; final import validation remains authoritative.
- DevOps performance has separate HK API and public-page groups, each limited to 200 recent samples for one hour. Public instrumentation measures root server page invocations on /me, news, profiles, events and search, including measured database/external work. It excludes metadata, separately rendered children, cached responses that do not invoke the page, network transfer and browser rendering. Static build invocations are excluded. Routes use fixed labels without usernames or search terms; component outcomes are distinct from HTTP status codes.
- Shared unsaved-change protection now coordinates dirty forms and protects global-search navigation. Prefix, badge and room-furniture editors protect explicit dismissal and remain open after failed saves. Browser Back is intercepted when the cancellable Navigation API is available; reload/close and links retain their existing protection. Prefix saving now waits for the real server action result before closing.
@@ -1,93 +0,0 @@
# Backup and isolated restore drill
This opt-in operator tool creates one MariaDB logical dump and copies explicitly selected persistent files. It never runs during install, update or CI deployment. The only restore operation is a **disposable drill**: there is no production restore command, database target, destination directory or overwrite option.
## Scope and prerequisites
Use the existing project Node toolchain and Docker CLI/Engine on a Linux host. Creation uses a short-lived `mariadb:11.4.5` client on the Docker host network, so `127.0.0.1` means that host. Use a local Docker Engine/context with the same filesystem; remote Docker daemons and Docker Desktop are not supported for creation. The image must already be available or downloadable through the operator's normal image policy. No packages are installed by this tool.
Choose the single application database explicitly. Its tables must use InnoDB; empty databases, system schemas and unsupported engines are rejected. The backup account needs access to every application table, view, trigger, routine and event being exported. Account/grant provisioning belongs to the operator; the tool does not change privileges. Restore compatibility is checked with the pinned MariaDB image, not guaranteed across arbitrary server versions, plugins, collations or external schema dependencies.
Before starting, pause **every database/file writer** and schema changer for the whole creation command: CMS requests that write, workers, schedulers, emulator processes, MariaDB events, import jobs and other tools using these resources. Keep them paused until the command exits. `--writers-quiesced` records your acknowledgement; it does not stop services or prove that they are stopped. No DDL may run while dumping. InnoDB's transaction snapshot alone cannot make independently copied files consistent with rows or coordinate other services. The before/after table inventory and second source-file hash pass detect many concurrent changes, but cannot replace quiescing.
The dump explicitly uses `--single-transaction --quick --skip-lock-tables --routines --events --triggers --hex-blob --tz-utc`. It retains schema/data and named SQL objects while streaming rows. See [MariaDB dump snapshot and object options](https://mariadb.com/docs/server/clients-and-utilities/backup-restore-and-import-clients/mariadb-dump). This is a logical application backup, not point-in-time recovery: binlogs, server accounts/grants, server configuration, Redis state and unrelated databases are outside its scope.
## Private configuration
Create a private JSON file **outside the clone and every selected source directory**, for example `/etc/epicnext/backup.json`. Use a directory accessible only to the operator and file mode `0600`. Edit it with the host's normal private configuration workflow; do not put a password in a shell command or commit the file.
```json
{
"database": {
"host": "127.0.0.1",
"port": 3306,
"user": "REPLACE_WITH_BACKUP_ACCOUNT",
"password": "REPLACE_PRIVATELY",
"database": "REPLACE_WITH_APPLICATION_DATABASE"
},
"roots": {
"storage": "/srv/epicnext/storage",
"nitro": "/srv/epicnext/public/nitro-assets",
"swf": "/srv/epicnext/public/swf",
"gamedata": "/var/www/Gamedata"
}
}
```
Replace the example clone path and database settings. `storage`, `nitro` and `swf` are required existing directories, including when empty. `gamedata` is optional; omit its key only when those files are independently backed up or not used. All paths must be absolute, distinct, non-overlapping and free of `..` and symlink/junction components. Links, hardlinked files, special files and secret configuration filenames such as `.env`, `.docker-install` and `persistent.path` inside a selected root cause rejection. The configuration itself may not be inside any source root. Keep writers and directory ownership controlled for the duration; this is not a filesystem snapshot resistant to hostile concurrent renames.
The tool reads only this explicit JSON. It does not source `.env`, inspect a running application's environment or inherit its secrets into Docker. The MariaDB password is written to a random private temporary directory/file (`0700`/`0600`) and read through a read-only container mount with `--defaults-file` as the first client option. It is absent from process arguments and tool logs; source configuration and absolute source paths are absent from the manifest. Temporary credentials are removed on ordinary success/failure. See [MariaDB option-file handling](https://mariadb.com/docs/server/clients-and-utilities/backup-restore-and-import-clients/mariadb-dump#defaults-file-name).
Only Docker connection/runtime environment variables are passed to child processes. Do not point `DOCKER_HOST`/`DOCKER_CONTEXT` at another host or enable shell tracing around private configuration work.
## Create and verify
Provision a private backup parent directory, with adequate free space, outside all source roots. Choose a **new** absolute artifact directory for each run. After pausing the writers described above, run from the clone root:
```sh
node scripts/backup/cli.mjs create \
--config /etc/epicnext/backup.json \
--output /srv/epicnext-backups/2026-09-13T200000Z \
--writers-quiesced
```
The date is an example; use a new name for the actual run. Existing directories are refused, including earlier incomplete attempts. A successful artifact contains:
```text
manifest.json
database.sql
files/storage/...
files/nitro/...
files/swf/...
files/gamedata/... (only when selected)
```
`manifest.json` is written last and marks the format complete. It records each relative file path, byte count and SHA-256, empty directories, selected logical roots, creation time and database inventory. The inventory includes table row counts and MariaDB extended table checksums plus names/types of views, triggers, routines and events. These checksums validate restored table contents; they are not cryptographic signatures or a substitute for application-level checks. See [MariaDB CHECKSUM TABLE semantics and version limits](https://mariadb.com/docs/server/reference/sql-statements/table-statements/checksum-table).
On a caught failure the newly created artifact is removed; an interrupted process can leave an incomplete directory, which verification refuses. Source roots and existing backup directories are never overwritten. Files are copied and hashed as streams, then source hashes are checked again across the dump interval. This performs multiple full reads of the assets and table data; allow sufficient time and disk capacity during the maintenance window.
After creation you may resume writers. Copy the completed artifact to the designated protected backup location according to the operator's retention/encryption policy. SQL and uploaded files contain application data and may themselves contain sensitive values. Hashes detect corruption against the manifest, not an attacker who can replace both. Keep the manifest and artifact under trusted access control. Secrets, TLS material and deployment configuration excluded from this artifact need their separate recovery procedure.
## Isolated restore drill
Run the drill against a trusted completed artifact:
```sh
node scripts/backup/cli.mjs drill \
--artifact /srv/epicnext-backups/2026-09-13T200000Z
```
The drill first rejects missing, extra, changed or unsafe paths/files. It copies the persistent files into a new private temporary directory and verifies their contents. It creates a randomly named MariaDB container with **no network and no published ports**, a fresh password supplied by file, and a disposable database volume. SQL is imported through the container's standard input; there is no connection to the source database. The event scheduler stays off. The resulting table counts/checksums and object inventory must match the manifest. This proves dump importability and the recorded contents, not a full CMS/emulator startup or external-service recovery.
On ordinary completion/failure it removes the container, its anonymous volume and temporary files. Cleanup failure makes the drill fail. A host crash or forced process termination can interrupt cleanup; inspect only resources labeled `cms.backup-drill=true` and private `cms-backup-private-*` temporary directories from that run, and review their ownership before manual removal. Never substitute an existing database/container into this procedure.
A real production recovery remains a separate, reviewed procedure with its own deployment configuration, credentials, downtime and application checks. This tool deliberately cannot perform it.
## Repository verification
```sh
pnpm exec vitest run --coverage.enabled=false scripts/backup
pnpm exec vitest run --config vitest.integration.config.ts integration/backup.test.ts
```
The local suite exercises real file copies, empty directories, SQL/file tampering, manifest traversal, links, secret-file rejection, overwrites, cleanup and changes during backup. The integration suite requires Docker: failure to start MariaDB fails the suite. It uses a real database with Unicode text, large unsigned identifiers, a foreign key, view, trigger, procedure and event; it creates an artifact, restores it to a second disposable server and checks both byte corruption and a SQL content change with a recomputed file hash. A passing local file suite alone is not evidence that the MariaDB drill ran.
-17
View File
@@ -1,17 +0,0 @@
# Docker and news checks before merging
Push work to a `codex/**` branch and open a pull request targeting `main` or `master`. CI runs the existing `check` job first. After it passes, the new `preflight` job builds the production Dockerfile and runs the isolated news browser suite against that exact image. Review both results before merging; repository branch protection can require `check` and `preflight` for pull requests.
Each execution uses `epicnext-cms:preflight-<commit>-<random suffix>`, including retries and separate push/PR runs of the same commit. The full checked-out commit is passed as `NEXT_DEPLOYMENT_ID` and `NEWS_E2E_RELEASE`; `NEWS_E2E_IMAGE` identifies that execution's image. Failures in dependency/browser setup, Docker build, news tests or cleanup fail the job. News browser artifacts are uploaded even when the gate fails.
The script installs dependencies with the frozen lockfile and installs Chromium on the CI runner. The real Docker build uses the existing Dockerfile's fixture build settings. It never copies or sources a deployment `.env`, connects to a VPS, runs live migrations, updates live containers, publishes a registry image or changes release tags. The existing isolated news runner owns its disposable MariaDB, Redis and application containers. Cleanup removes only the preflight tag and its empty private temporary directory; it does not prune Docker resources.
The `deploy` and `publish-container` conditions remain restricted to pushes on `main`/`master`. Deployment still runs its own news gate before live migrations/cutover. A successful branch preflight supplies earlier evidence; the deployed commit is independently checked again.
On a Linux development or CI host with the project toolchain, Docker Engine and normal browser prerequisites, the same gate can be run from a clean checkout:
```sh
bash scripts/ci-preflight.sh
```
Shell orchestration is covered by `pnpm exec vitest run --coverage.enabled=false src/lib/ci-preflight.test.ts`. Those tests execute the real shell script with external command boundaries simulated; they prove ordering, failure propagation, unique tags and cleanup scope. They do not build an image or run the news browser suite. The branch/PR CI job provides that Docker/browser evidence.
-85
View File
@@ -1,85 +0,0 @@
# CMS error center and dependency maintenance
Open **HK > DevOps > CMS error center** (`/admin/devops/cms-errors`).
The previous `/admin/devops/errors` page still displays emulator errors.
## Access and workflow
- Read: existing `admin.devops.view` permission, checked on the server.
- Mark resolved: `admin.devops.edit`, checked again in the server action; recorded in the staff audit log.
- Search by event reference, Next.js digest, route, message or deployment version.
- Expand a group for its latest stack, sanitized context and occurrence references.
- Marking a group resolved does not delete evidence. A later occurrence reopens it.
- Refresh is manual so inspecting an expanded error is not interrupted by polling.
## What is collected
Pino `logger.error`, `logServerError`, unexpected action errors, Next.js request
failures, React error boundaries, uncaught browser errors and unhandled browser
promise rejections. API wrapper failures return an `errorId`; Next.js boundary
errors can be correlated by their digest. Release identifiers come from the build.
Browser reports retain their own client release separately from the receiving server.
Reports are stored in `storage/cms-errors`, using the existing persistent storage
mount. No third-party service, token or new database table is required.
Storage does not depend on database availability; viewing the HK and its permission
checks still require authentication/database availability. Server console logs
remain the fallback when the CMS itself cannot serve requests.
Retention: seven days; approximately 10 MB/day, 100 queued server writes, and the
latest 1,000 events in the viewer. Limits are per CMS process/storage volume;
this is intended for the existing single-instance deployment. Daily expiry runs
on the next write. The browser endpoint is same-origin, body-size bounded and
rate-limited. Browser reports are untrusted observations and cannot grant access.
Known credential patterns and URL parameters are redacted; arbitrary object
metadata and request bodies are excluded. Avoid putting personal data in error
messages: this is pattern-based redaction, not a universal data-loss filter.
This does not collect historical console logs, process crashes before framework
startup, nginx failures, all `console.error` calls, or every handled business
validation error. A browser stack may point at minified chunks; private source-map
symbolication and distributed traces are not part of this local viewer. A recorded
stack is diagnostic evidence, not an automatic root-cause determination.
## Dependencies
`pnpm install --frozen-lockfile`, `pnpm deps:audit`, `pnpm typecheck`, `pnpm test`,
`pnpm biome:lint`, and `pnpm build` are the verification sequence.
`pnpm analyze --output` writes a Next.js bundle analysis (not an application build).
TinyMCE 8.9 is pinned in pnpm. `pnpm assets:editor` copies its runtime files and
license notices to ignored `public/vendor/tinymce`; dev/build run this first.
The Docker build includes the generated assets. The editor retains its existing
HTML fields and toolbar; validate saved content and preview when upgrading it.
Lenis has been removed; the public site now uses native scrolling. Other used
runtime libraries remain. Vitest and its coverage provider are upgraded together;
`clearMocks: false` preserves initialization-time permission contract assertions.
Dependency updates are manual: Renovate has been removed, so there is no bot
opening upgrade pull requests. Node/pnpm upgrades remain coordinated with
Docker and the runner toolchain.
Obsolete global overrides were removed; a scoped esbuild override remains because
Drizzle Kit's loader still resolves a vulnerable legacy development-server build.
The two deprecated esbuild-kit packages remain upstream dependencies of Drizzle
Kit; replacing the ORM is not warranted for this tooling issue.
## HK request performance
Open **DevOps → Request performance** (`/admin/devops/performance`). Access requires `DEVOPS_VIEW`; collection only retains requests that passed authentication and permission checks through `withAdmin`.
The view shows recent requests, their server duration, completed database query count/time/errors, monitored curl download count/time/errors, HTTP status and the existing operation ID. Search by route or operation ID, sort by duration or recency, and filter requests taking at least one second.
### Measurement boundaries
- Duration ends when the handler returns its response. Streaming completion, background jobs, browser rendering and public pages are not measured.
- Database spans wrap the shared mysql2 promise pool and transaction connection query/execute calls. Query parameters and SQL are never collected. Explicit transaction connection acquisition and transaction control methods are not separate spans.
- External spans currently cover `curlFetchText` and `curlDownload`; ordinary fetch calls and other integrations are not covered.
- Concurrent dependency durations can exceed wall-clock request duration. Do not subtract the sums to infer application CPU time.
- Dynamic route values and query strings are removed. No request bodies, headers, usernames, download URLs or SQL text are stored.
### Storage and operation
No new environment variables or packages are required. Redis stores at most 200 recent samples under `cms:performance:v1`, with one-hour retention. Writes are best effort, restricted to an already-ready connection and at most four pending batches; the request never waits for persistence. The view reads at most 200 entries and falls back after one second if shared storage is unavailable.
An in-process buffer preserves up to 200 samples during outages. The page explicitly labels this local mode; it is per instance and disappears on restart. Filtering applies to the retained samples, not complete traffic history. Under load or during storage outages, some shared samples may be omitted.
-120
View File
@@ -1,120 +0,0 @@
# Install a clone and choose an update
## Requirements and first installation
Use a Linux host with Docker Engine, the Compose plugin, Git and `flock`. This Compose file uses host networking and port 3002. Provide an existing compatible Habbo MariaDB database, reachable Redis, persistent storage and an HTTP(S) reverse proxy. The installer does not provision the emulator, a database, TLS, or a registry account.
Clone this repository from the Gitea URL supplied by your administrator, enter the clone, then run:
```sh
bash cms install
```
The wizard asks for the public URL and delivery mode. **Source** (the default for a new installation) builds the locked source locally and only needs repository access plus access to public build dependencies. **Prebuilt** downloads the application and migrations from the repository's `docker-image.txt`; a private package needs a separate registry login with package-read permission. Git access alone may not grant package access. Existing saved mode and `.env` are preserved. `bash cms install --configure-only` saves configuration without starting containers.
Credentials are entered on the host, never in the dashboard. Do not paste `.env` into support tickets. Installation prepares `public/nitro-assets`, `public/swf`, `storage`, and `/var/www/Gamedata` for UID/GID 33 without recursively taking ownership of existing files. Existing nested assets may still need operator permission repair. The updater tests access to those mounts as the candidate container user before migrations; this checks directory access, not every nested file or filesystem capacity.
After startup, visit `/admin/devops/installation` with the appropriate permission. Verify database, Redis, storage and migration status. Worker heartbeat is a separate runtime signal: a healthy HTTP endpoint does not prove an import worker is processing jobs. Check the worker status and investigate a missing/stale heartbeat before scheduling imports. The dashboard is read-only and cannot start Docker, upgrade the host or grant registry access.
## Client IP trust at the reverse proxy
The application validates and normalizes client addresses from `cf-connecting-ip`, the first `x-forwarded-for` entry, then `x-real-ip`. It never accepts `x-real-client-ip`; that legacy derived header is also stripped by the Next.js proxy. Missing or invalid addresses resolve to `0.0.0.0` for rate limits and audit records. API routes use the same resolver even though they do not run through the Next.js proxy.
These headers are trustworthy only when the ingress sanitizes them. Configure the reverse proxy to discard client-supplied forwarding/derived headers and replace the accepted address from a verified connection or a specifically trusted upstream proxy. Do not append an untrusted incoming `x-forwarded-for` chain and then treat its first entry as authoritative. Forward `cf-connecting-ip` only after verifying that it came through your trusted CDN path; otherwise remove it.
Restrict direct access to the application port so requests must pass through that ingress. The provided Compose file uses host networking with `HOSTNAME=0.0.0.0`; it does not enforce this restriction or provision nginx/Traefik trust rules. Verify the host firewall and actual reverse-proxy configuration before relying on client IPs for blocking, auditing or abuse limits. Repository tests prove rejection of the derived-header bypass and malformed addresses; they do not certify the deployed forwarding trust chain.
## Opt-in profile: Nginx on the same host
Use this profile for a new Linux Compose clone whose public HTTPS endpoint is Nginx on that same host. It leaves `docker-compose.yml` and CI-managed production deployments unchanged. Nginx must include `ngx_http_realip_module`; check `nginx -V` before using the templates. The CMS remains on the existing host network for database/Redis connectivity, but its HTTP process listens on `127.0.0.1:3002`. Host networking shares the host network namespace; a `ports:` mapping would not provide the restriction. See [Docker host networking](https://docs.docker.com/engine/network/drivers/host/).
1. Run `bash cms install --configure-only` and choose the intended public HTTPS URL. Obtain a valid certificate for that hostname using the host's existing certificate-management process. The templates do not issue certificates or configure renewal.
2. In the clone's existing `.env`, add or replace this single setting, preserving all other values:
```dotenv
COMPOSE_FILE=docker-compose.yml:deployment/proxy/compose.loopback.yml
```
Keep `APP_URL`, `AUTH_URL` and the saved installer public URL on the same canonical `https://` hostname. The profile pins the existing port 3002 as well as the loopback address. Do not place `COMPOSE_FILE` in `.docker-install`; that file accepts only `MODE` and `PUBLIC_URL`.
3. Copy [nginx-direct.example.conf](../../deployment/proxy/nginx-direct.example.conf) into the host's Nginx configuration directory, outside this Git clone. Replace **every** `hotel.example` and both certificate paths. Load it at `http` scope, for example through `/etc/nginx/conf.d/cms.conf`. Review any existing virtual host for that hostname to avoid two competing configurations. The example handles only CMS HTTP traffic; emulator WebSocket and other hotel services need their own reviewed ingress.
4. Validate the effective Nginx configuration with `nginx -t`, then enable/reload it through the host's normal service-management procedure. Prepare this endpoint before starting the installer, because installation verifies the saved public URL. It can return an upstream-unavailable response until the CMS starts.
5. From the clone root, remove conflicting Compose overrides from the deployment shell and validate the model:
```sh
unset COMPOSE_FILE COMPOSE_PATH_SEPARATOR COMPOSE_ENV_FILES COMPOSE_DISABLE_ENV_FILE
docker compose config --quiet
bash cms install
```
These `unset` commands remove shell overrides; they do not remove the `COMPOSE_FILE` line in `.env`. Do not set `COMPOSE_DISABLE_ENV_FILE=1`, use an alternate `--env-file`, or supply a competing shell `COMPOSE_FILE` for this workflow. Environment values can override `.env` selection. Do not print or paste the full rendered Compose configuration, because it contains runtime credentials. See [Compose predefined variables and precedence](https://docs.docker.com/compose/how-tos/environment-variables/envvars/).
6. Confirm the running configuration without dumping the environment:
```sh
docker compose exec -T cms node -e 'if(process.env.HOSTNAME!=="127.0.0.1"||process.env.PORT!=="3002")process.exit(1);console.log("CMS configured for 127.0.0.1:3002")'
ss -lnt '( sport = :3002 )'
curl --fail --silent --show-error https://hotel.example/api/health
```
The listener must be `127.0.0.1:3002`, not `0.0.0.0:3002` or `[::]:3002`. From another machine, the host's public IP on port 3002 must be unreachable. Check both address families when the host has IPv6. Loopback isolation covers the CMS process only: other containers and host services, including Byparr, retain their existing bindings.
The direct template uses the original socket peer (`$realip_remote_addr`), overwrites the two accepted forwarding headers, and removes incoming `CF-Connecting-IP`, `X-Real-Client-IP` and `Forwarded`. It fixes forwarded host/protocol to the configured HTTPS origin. An unrelated inherited real-IP rule cannot turn a caller-supplied header into the forwarded client address in this mode. See [Nginx original-peer variables](https://nginx.org/en/docs/http/ngx_http_realip_module.html) and [header replacement/removal](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_set_header).
Response buffering is disabled for progress streams, and this example adds no proxy response cache or CORS policy. Its 64 MiB ingress body cap accommodates the existing 52 MiB Studio attachment limit; route and Server Action limits remain authoritative and may be lower. TLS 1.2/1.3 are configured explicitly. See [Nginx buffering](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffering) and [TLS protocols](https://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_protocols).
### Why the profile survives an update
The installer preserves an existing `.env`. The installer invokes `docker-update.sh`, and the updater's config, build, candidate run, cutover and rollback paths all call **bare `docker compose` from the clone root**, without `-f`. Compose therefore reads the saved file list on each invocation. The base file appears first so its relative mount/build paths remain rooted in the clone; the later profile overrides only the CMS environment and healthcheck. No installer/updater patch is required for this selection. See [Compose merge order and relative paths](https://docs.docker.com/compose/how-tos/multiple-compose-files/merge/).
Keep the profile selected for every routine `bash cms update` and selected-release update. A one-off `docker compose -f ... up` does not persist selection for later installer/updater commands. Do not add an untracked `docker-compose.override.yml`: it makes the clone dirty unless separately excluded and is bypassed when `COMPOSE_FILE` selects an explicit list. Before selecting an older release, verify that `deployment/proxy/compose.loopback.yml` exists in that release; a missing selected file fails configuration rather than silently using the public bind.
This profile does not change `scripts/ci-deploy.sh`, which owns a separate `docker run` deployment and currently sets its own public binding. Do not use the clone installer to take over a host managed by CI. Restricting that deployment's listener requires a separate compatibility review and rollout.
### Separate mode: verified remote edge or Cloudflare
A remote proxy cannot connect to the CMS loopback listener directly. The supported topology here is **remote edge → TLS → Nginx on the CMS host → loopback CMS**, retaining the same Compose profile. Use [nginx-trusted-proxy.example.conf](../../deployment/proxy/nginx-trusted-proxy.example.conf) instead of the direct template. Do not enable both templates for one hostname.
For your own remote edge, replace `203.0.113.10/32` in both the `geo` peer allowlist and `set_real_ip_from` with the exact approved connection source addresses. The reserved example address deliberately permits no real edge. Require the edge to overwrite `X-Forwarded-For` with one verified client IP, use the configured hostname, enforce public HTTPS, and validate this origin's TLS certificate. The origin checks the original socket peer before accepting the rewritten address. Never use `0.0.0.0/0`, `::/0` or arbitrary client networks as trusted proxies. See [Nginx real-IP trust configuration](https://nginx.org/en/docs/http/ngx_http_realip_module.html).
For Cloudflare, use that same restricted-edge mode and replace both peer lists with the **current verified IPv4 and IPv6 Cloudflare ranges**, maintained by the operator; use `real_ip_header CF-Connecting-IP` instead of `X-Forwarded-For`. Configure Full (strict) TLS and review authenticated origin pulls. Obtain ranges from [Cloudflare's official IP list](https://www.cloudflare.com/ips/) and follow its [visitor-IP restoration guidance](https://developers.cloudflare.com/support/troubleshooting/restoring-visitor-ips/restoring-original-visitor-ips/). Do not copy a historical range list from a support ticket or trust `CF-Connecting-IP` merely because it is present. This setup still removes the CF header before the CMS and forwards only Nginx's normalized result in XFF/X-Real-IP.
The direct template intentionally records the CDN/edge socket address when placed behind an unconfigured CDN; it does not silently trust an upstream header. After configuring the restricted-edge mode, verify with requests from an allowed edge and a disallowed direct client, including forged CF/XFF headers, and check the recorded client address. Neither the repository nor the installer changes the host firewall or certifies another proxy's header behavior.
### Local verification and deployment boundary
`pnpm exec vitest run --coverage.enabled=false scripts/proxy-config.test.mjs` runs the installed Docker Compose CLI against a disposable clone configuration, without contacting Docker Engine, building images or reading the real `.env`. It verifies selection through `.env`, loopback/port override precedence, the IPv4 healthcheck and preservation of mounts, release selection and host networking. It explicitly skips when Compose is unavailable. This is not a container-start or network-isolation test.
`pnpm test:integration` additionally starts disposable Nginx containers from the actual templates, supplies a temporary test certificate, and sends real HTTPS requests with forged identity headers. It checks direct-mode replacement even with an inherited real-IP rule, rejection of untrusted peers, and acceptance through an explicitly trusted peer. This requires Docker Engine and the OpenSSL CLI and does not read deployment credentials. The templates must still pass `nginx -t` on the intended host after its hostname/certificate substitution, then the listener and trusted-header checks above; the disposable fixture cannot certify that host or its firewall.
## Routine and selected-release updates
```sh
bash cms update
```
This requires a clean clone and fast-forwards its configured Git upstream, then builds/pulls artifacts for that exact commit. It validates the application and migration revision labels, validates runtime configuration and storage, runs migrations and verifies the recreated CMS locally and through the saved public URL.
To install a specific published version, fetch it and select its commit on the host first:
```sh
git fetch origin
git switch --detach <reviewed-commit-or-tag>
bash cms update --skip-pull
```
`--skip-pull` deliberately uses the checked-out commit, including detached HEAD. For routine updates again, switch back to your tracked deployment branch. The script does not invent version-to-schema compatibility or automatically change branches.
In prebuilt mode you can additionally require immutable artifacts from the configured repository:
```sh
bash cms update --skip-pull --app-digest sha256:<64-lowercase-hex> --migrations-digest sha256:<64-lowercase-hex>
```
Replace both placeholders with publisher-provided digests. Both are mandatory together. Revision labels must match the checked-out commit; a digest alone does not establish schema compatibility. Older migration images without a revision label must be republished from matching source, or the same checkout can be installed in source mode. No migration runs when the artifact or candidate validation fails.
## Compatibility and recovery
Before upgrading, read the selected release's migration changes and take a database backup with a tested restore procedure. Preserve `.env`, persistent assets and the previous release identifier. The current tooling does not provide a validated matrix of supported source/target database versions. Pinning an old commit is therefore not a supported database downgrade procedure.
On a failure after container replacement, the updater attempts to restore the previous image and checks it locally. **Image rollback does not reverse database migrations.** A migration may partially apply or make the old application incompatible, including when migration fails before container replacement. Recover the database only through the reviewed backup/restore procedure and coordinate downtime; do not assume restarting the old image recovers it. First installation has no prior image to restore. Host logs remain in `logs/docker-update.log` and may contain application/database diagnostics; restrict access.
Local Git Bash tests cover selection validation and mocked failure paths. They do not establish Linux container startup, runtime filesystem permissions, registry availability or real MariaDB upgrade compatibility.
-26
View File
@@ -1,26 +0,0 @@
# Personal API token scopes
Public API bearer authentication accepts only tokens owned by the exact `App\Models\User` model. The owner ID must be a positive, safely representable user ID, and the token must satisfy its existing expiration check. Both plaintext tokens and the existing `{id}|{plaintext}` request format remain supported; only the SHA-256 hash is looked up in the database.
The `abilities` column must contain a non-empty JSON array of non-empty strings. Null, malformed JSON, non-array JSON, empty arrays, non-string entries, and entries with surrounding whitespace are rejected. A valid `"*"` entry grants access to all existing bearer-protected endpoints. Other permissions match exactly: there is no `tickets:*` expansion, implicit read/write inheritance, or fallback to unrestricted access.
| Ability | Endpoint access |
| --- | --- |
| `tickets:read` | `GET /api/tickets`, `GET /api/tickets/{id}` |
| `tickets:write` | `POST /api/tickets`, `POST /api/tickets/{id}/reply` |
| `articles:write` | `POST /api/articles/{slug}/comment` |
| `radio:read` | `GET /api/radio/points` |
| `radio:write` | `POST /api/radio/shouts` |
| `badges:read` | Personal viewer data in `GET /api/badges/leaderboard` |
For example, `["tickets:read","radio:read"]` allows reading the owner's tickets and radio points. It cannot create tickets, send replies, post article comments, or send radio shouts. Endpoint ownership checks and rate limits still apply after scope authorization.
Required-token endpoints return the existing generic `401 Unauthorized` response when authorization fails. The badge leaderboard remains public: a denied bearer token receives the anonymous view, without personal viewer data. When an Authorization header is present, this endpoint does not use a session cookie to bypass a denied token. Session-only requests continue to personalize the leaderboard normally.
## Compatibility and maintenance
Existing valid wildcard tokens remain compatible. The existing session-authenticated `POST /api/tokens` endpoint continues issuing `["*"]`; this change does not add token-creation options or alter stored tokens. Legacy null, malformed, empty, differently cased model names, and unrelated model tokens are intentionally denied. Review and replace affected tokens with explicit intended scopes, or reissue through the existing token endpoint when full access is appropriate.
Every new bearer-authenticated endpoint must pass its required abilities to `bearerUserId`. Multiple required abilities use AND semantics. Omitting the requirements, or passing an empty list, requires a wildcard token rather than granting arbitrary scoped tokens access.
No plaintext token or stored hash is added to error responses or logs by these checks. The existing issuance endpoint returns plaintext once by design.
@@ -1,31 +0,0 @@
# Security report verification — 2026-09-13
The supplied review describes commit `baeb54ae` plus a separate port for another hotel. Its “Fixed” labels were not evidence that the changes existed in EpicNext-Cms. This verification inspected canonical `main` at `52f6d149` and the corrective changes prepared here. No exploit or authenticated mutation was performed against production.
| Supplied finding | Verified state in baseline | Correction / remaining boundary |
| --- | --- | --- |
| 1. Logo authorization/upload | Confirmed missing action permission and per-file validation | Require settings edit before input or storage access; bounded decoded raster uploads |
| 2. Favicon authorization/delete | Confirmed missing action permission; SVG accepted | Same permission boundary for create/delete, bounded raster/ICO validation |
| 3. Active uploaded SVG | Confirmed SVG served inline without route CSP | Route CSP sandbox and nosniff on success/errors; existing SVG served as attachment |
| 4. Client IP spoofing | Confirmed direct trust in caller-controlled `x-real-client-ip` | Shared validated resolver ignores that header. Forwarded headers still require trusted ingress that overwrites them and prevents direct public origin access |
| 5. Email token action exports | Confirmed token helpers in a `use server` module | Move token creation/validation and delivery to a server-only module. Registration and verification call it internally |
| 6. Locale cookie | Confirmed missing allowlist | Supported locales only, validate before reading/writing cookies |
| 7. Email header injection | Confirmed unsanitized values in sendmail headers | Reject control characters before any mail transport or file fallback; includes configured sender |
| 8. Gateway CORS | Supplied gateway path is outside this repository | Read-only GET to our `/api/health` with an unrelated Origin returned a fixed `https://epicnabbo.nl` allow-origin and no allow-credentials. This does not reproduce the report on that route, nor certify every host/route |
| 9. Token abilities | Confirmed abilities and owner type not checked by bearer authentication | Enforce User owner type and explicit endpoint abilities; existing wildcard user tokens remain supported |
| 10. Broad script CDN | Confirmed unrestricted jsDelivr script source, without a source-code consumer | Remove the broad script source; retain required captcha/analytics sources and nonce |
The additional `withNitroStaff` code and its tests mentioned in the supplied port do not exist in this checkout; they were not assumed to have been reviewed or imported.
## Evidence and limits
- Regression tests exercise authorization before I/O, actual file decoding, SVG/error response headers, token-boundary exports, token abilities, forged derived-IP headers across consumers, locale values, and mail header control characters.
- An updated `pnpm audit --json` reported zero known advisories. This is a dependency database result, not proof that application code has no vulnerabilities.
- Next.js treats exported Server Actions as public endpoints; unused actions can also be removed by the compiler. The email refactor removes the action boundary entirely instead of relying on whether a specific build exports an unused helper. See [Next.js data security](https://nextjs.org/docs/app/guides/data-security).
- The framework also has its own Server Action body limit. The logo defect was absence of application-level file validation, not evidence of literally unlimited bytes through every deployment layer.
- No live database, user accounts, uploaded files, or gateway configuration were modified during verification. These changes do not constitute a penetration test or an audit of the emulator, host, or all CMS endpoints.
- No nginx/Traefik ingress configuration is versioned here. The deployment guide records the forwarding-header trust requirement. That external boundary remains unverified.
## Follow-up identified during verification
The separate comment review is now implemented: both the website form and REST API use one submission service, require a published article whose publication time is due, apply the same moderation, and share a five-attempt/30-second per-user quota. The publication check locks the current article in the insertion transaction. Regression tests cover both entrypoints; real MariaDB/Redis coverage includes publication eligibility, word filtering and alternating submissions. Moderation retains its existing fail-open behavior on service outages. Form input beyond 255 characters is now rejected instead of truncated, and temporary API storage failures return 503. Real integration execution remains a required CI check.
-39
View File
@@ -1,39 +0,0 @@
# Informational route JavaScript budgets
Run after the existing production build; no second build or server is needed:
```sh
node scripts/performance-report.mjs --next-dir .next --config scripts/performance-budgets.json --output-dir build-reports
```
The command writes `report.json` and `report.md` and prints the Markdown report. An optional `PERFORMANCE_COMMIT_SHA` environment variable records the commit declared by the build caller; the script does not infer that an existing build matches the current checkout. JSON also records `BUILD_ID`, Node/zlib versions, manifest provenance, exact file paths, sizes and source entries.
## What is measured
For each configured App Router route, resolve its exact app path using `app-path-routes-manifest.json` and `server/app-paths-manifest.json`. Read its generated `page_client-reference-manifest.js` as a JSON assignment **without executing JavaScript**. Use its sibling `page/build-manifest.json`, falling back to the root build manifest only if that sibling is absent.
The **initial entry envelope** is the union of route bootstrap `rootMainFilesTree[appPath]` (or `rootMainFiles`) and every `entryJSFiles` list in that route's client-reference manifest. This includes layout, page and boundary/loading entries. The definition follows the data exposed by the installed Next 16.3.4 Turbopack build and the `getLinkAndScriptTags` / `getRequiredScripts` renderer helpers; it is deliberately a build-artifact envelope, not a browser network trace. Conditional rendering, redirects, streaming and browser caches can change actual requests.
- Raw bytes are filesystem byte lengths of unique JavaScript assets in that envelope.
- Gzip bytes are the **sum of independent gzip level 9 compressions** of those files using the recorded Node/zlib runtime. They are not gzip of concatenated source, nor observed CDN transfer sizes.
- Deployment query strings and `/_next/` prefixes are normalized before deduplication. Shared files count once per route; each route is measured independently, with no misleading cross-route total.
- Legacy `nomodule` polyfills are measured separately, outside the modern initial budget. CSS, source maps, images, external scripts, HTML/RSC payloads and async-only chunks absent from `entryJSFiles` are excluded.
- This report makes no claims about execution cost, LCP, hydration time or real-user performance.
## Initial limits
The first limits are **baseline bytes × 1.15, rounded upward to the next 10 KiB (10,240 bytes)** independently for raw and gzip. They are provisional size alerts, not validated speed targets. Baseline: existing local production build `build-TfctsWXpff2fKS`, Next 16.3.4; its source commit was not inferred.
| Route | Baseline raw bytes | Baseline gzip bytes | Raw limit | Gzip limit |
| --- | ---: | ---: | ---: | ---: |
| `/me` | 767156 | 238571 | 890880 | 276480 |
| `/news` | 765367 | 237599 | 880640 | 276480 |
| `/events` | 765851 | 237964 | 890880 | 276480 |
| `/search` | 765851 | 237964 | 890880 | 276480 |
| `/admin/catalog` | 1654898 | 492619 | 1904640 | 573440 |
| `/admin/studio/furni` | 1241312 | 391541 | 1433600 | 450560 |
Configured limits are positive integer bytes; `null` explicitly means observe-only. `scripts/performance-budgets.json` remains `mode: informational`. Exceeding a limit produces `over-budget` and a warning, with exit code 0. Missing production `BUILD_ID`, unsupported manifests, missing routes or missing referenced assets produce `unavailable` with a reason and **no partial/zero total**, also exit code 0. Malformed budget configuration or an unwritable output directory fails the command. This keeps initial CI reporting non-blocking while preventing invalid configuration from quietly disabling limits.
Synthetic tests cover shared-chunk deduplication, exact byte/gzip calculations, route bootstrap selection, missing data, safe parsing and CLI exit behavior. Run `pnpm exec vitest run --coverage.enabled=false scripts/performance-report.test.mjs`.
File diff suppressed because it is too large. Load diff
@@ -1,21 +0,0 @@
# Catalog operations upgrade plan
User approved bulk editing and complete category duplication, keeping Visual Manager in its button-opened modal.
Use subagent-driven-development for the independent duplication task; root owns bulk operations and final review.
- [x] Duplicate category subtree and offers atomically for normal/BC; preview counts, destination/name, fresh IDs, preserve furniture references; fail on stale source, invalid destination, cycles and insert failure. Shared permissions, single export/RCON outcome. UI in Visual Manager.
- [x] Extend selected-offer operations to preview and atomically apply prices, currency, and destination. Visibility belongs to categories, so expose it separately with exact affected categories; no fictitious per-offer flag. Preserve unselected and unrelated fields; conflicts prevent overwriting concurrent changes.
- [x] Meaningful domain/transaction/action tests, browser fixtures for modal preview/confirm, typecheck/Biome/i18n/Knip; review limits and commit exact scope.
No production data mutations, added dependencies or schema migrations. Full category duplication shares existing items_base definitions and asset files. Repeated confirmations must be disabled while saving. Preview should be revalidated under locks before write. Existing direct save and permissions remain.
## Implementation notes
Bulk editing now works from selected normal-catalog offers and from selection across global searches. Only explicitly chosen prices/currency/destination fields change. Prices support set/add/percentage with integer rounding and range validation; 500 selected offers per transaction. Preview binds rows, changes and category names; concurrent changes reject confirmation. Category visibility remains on the existing category controls, not a fabricated offer property. BC has no offer pricing and does not expose that editor.
Duplication copies up to 500 categories and 5000 offers, preserving bundle and asset references. New root starts disabled and hidden. Includes and internal offer IDs are remapped. Explicit normal offer IDs use the existing allocator and do not require AUTO_INCREMENT; database collisions roll back the whole copy. Preview binds destination siblings as well as source data so confirmed preview replay is rejected. Dirty editor state blocks copying saved data until drafts are saved/reset.
No database migration or dependency added. Database transaction tests use mocks and do not prove live MariaDB locking behavior. Browser fixtures use real components with mocked actions, not production writes. Existing allocator is process-local; competing external imports may cause a safe rollback requiring a fresh preview. No automatic retry of uncertain copy commits.
Verification complete: 1339 unit tests passed, 5 skipped. Typecheck/Knip/i18n and changed-file Biome checked. Real-component browser fixtures passed bulk selection, preview, conflicts, pending guards, mobile bounds and table refresh without phantom drafts; duplication nested inside actual manager verified menus, picker, preview and dirty-state guards. Fixed manager portal layering and invalid menu-label nesting uncovered by those tests. Browser actions are mocked; no live data written or deployment claimed.
@@ -1,29 +0,0 @@
# Catalog refactor implementation plan
> For agentic workers: use superpowers:subagent-driven-development for independent changes and review each deliverable.
Goal: deliver the approved progressive catalog refactor while preserving current features.
Architecture: shared domain validation and transactional commands behind existing action contracts; unified editor reuses current views and tools.
Stack: Next, React, Drizzle/MariaDB, Zod, Vitest, Playwright; no added dependencies.
Spec: docs/CATALOG_REFACTOR_PLAN.md
Constraints: preserve normal/BC differences, direct save, real icons, permissions, existing routes, no favorites. No production data mutations for testing.
- [x] Characterize compatibility and command rules with tests; capture baseline source map.
- [x] Domain hierarchy/reorder validation and transactional page commands (normal/BC), deterministic locking, common updates/deletion.
- [x] Offer update/reorder atomicity and safe numeric normalization, shared mutation contracts.
- [x] Editor cancellation/dirty state protection (agent catalog_editor_state), review and browser verification.
- [x] Promote editor as an in-page view with reversible classic view, URL context, responsive panels and coherent tool access.
- [ ] Sync outcomes/diagnostics/history integration; safe retry and explicit limits.
- [ ] Verify unit tests, database integration if runtime available, browser, typecheck, lint/i18n, full suite; review final scope and remaining environment-only checks.
Execution notes: changes are progressive, no destructive migration. Existing UI adapters stay until functional parity is tested. Whole-program completion must not be claimed from the first deliverable.
## First implementation delivery (2026-09-06)
Completed: shared normal/BC page and offer commands; transactional page reorder/delete/move and offer create/update/reorder; hierarchy validation and optimistic page-save checks; embedded default manager with classic views retained; request cancellation, editor unsaved-change guards and URL selection; bounded global category/offer/furniture search; separate hotel/Git status and hotel retry; export-finalization failures no longer mask committed server actions. Existing permissions and direct-save behavior retained. No added dependency or DB migration.
Verification: full unit suite 1308 passed / 5 skipped before final retry-classification regression; final focused catalog suite 96 passed. TypeScript, i18n static validation, Knip and Biome on all 54 changed source files pass. Browser fixtures cover editor loading races, retry failures, unsaved changes, URL history, read-only, normal/BC, search and 375px layout. Database calls and mutations are mocked in those fixtures. Full-repository formatter check reports pre-existing Windows CRLF formatting differences; unrelated files were not reformatted.
Remaining roadmap: per-operation durable dispatch/outbox, category/offer snapshot history and conflict-aware undo, contextual maintenance diagnosis, pagination/performance measurement against representative real data, further decomposition of retained legacy views. Existing coarse audit/export infrastructure remains; the new status file is not a durable outbox and RCON socket success does not prove client application. External furni importer mutation internals remain outside shared editor commands.
Environment checks still required: real MariaDB locking/rollback integration, staff-authenticated end-to-end smoke test and pipeline/deployment health. No production mutations performed; no production deployment claimed.
@@ -1,16 +0,0 @@
# Security and operational reliability implementation plan
Goal: finish the five approved follow-ups with independently verified commits.
Architecture: share comment policy between session and bearer entrypoints; opt-in same-host proxy configuration; run real news browser checks against the already-built candidate in disposable services; correlate existing diagnostics with deliveries; verify database and persistent-file backup restoration in isolation.
Stack: existing Next, MariaDB, Redis, Playwright, Testcontainers and Docker; no new dependencies.
Design: user-approved numbered proposal in this task, 2026-09-13.
Global constraints: preserve current public/HK UX and ACL; no production test content or proxy/firewall changes; no credentials in output; root owns Git on canonical main. Complete each block's checks before an exact-file commit and push. Confirm final CI, container publication and live release.
1. Comments — src/actions/article-comments.ts, API comment route and shared policy/tests. Add regression cases for hidden/future articles, moderation, cross-channel limit and safe failures; reproduce them, implement, run focused and integration checks. Publicly available article predicate is checked on both entrypoints.
2. Proxy — deployment/proxy templates and installation guide/tests. Override must survive installer/update/rollback, force loopback and replace incoming identity headers. Validate the merged Compose config and Nginx syntax; do not apply to the host.
3. Real news — e2e/news-real runner/fixture plus ci-deploy gate and harness tests. Start only disposable MariaDB/Redis and the local candidate image; real staff login, draft, preview, publish and anonymous read. Fail before live migration/cutover on any error, clean all fixture resources. Require successful CI execution.
4. Diagnostics — carry persisted operation/delivery identifiers into error records; link filtered deliveries and diagnostics with permission checks. Preserve request correlation separately. Tests cover exact matching, hostile IDs, permissions and retry outcomes.
5. Recovery — backup creation and isolated restore drill for database plus explicit persistent directories. Keep credentials off argv/logs, reject unsafe paths and incomplete/tampered artifacts. Test real database restore and file checksums with disposable data, record limits for cross-service consistency. Never overwrite production during a drill.
Status: all five blocks implemented and locally checked. Required final gates: CI real database/proxy/backup suites, candidate news browser journey, deployment/container completion and live release verification. Extra scheduler deadlock discovered in the real concurrency test is fixed with bounded transaction retries. Evidence and boundaries accompany each delivered block.
@@ -1,69 +0,0 @@
# Public Avatar Thumbnail and Currency Icon Design
## Goal
Make avatar and currency presentation consistent across the public site:
- user thumbnails in lists and compact cards show only the avatar head at a fixed 40 x 40 pixel size;
- full-body avatars remain available on profile pages and deliberately large previews;
- currency amounts use the existing graphical currency icons instead of placeholder letters such as `c`, `cr`, `du`, or `di`.
## Scope
The change covers public-facing pages and shared public components. It includes rankings, leaderboards, shop and badge-purchase currency rows, plus every other compact user list or card that currently renders an avatar directly.
Admin-only screens are outside this visual cleanup unless they reuse a shared public component changed by this work. Profile hero avatars, the main current-user avatar, registration/login previews, and other intentionally large previews retain their full-avatar presentation.
## Avatar Design
Compact user representations will use one shared semantic thumbnail path rather than choosing imager options independently in each page.
The thumbnail contract is:
- request `headOnly: true` from the avatar imager;
- render at 40 x 40 CSS and image dimensions;
- preserve pixel-art rendering and contain the image without stretching;
- prevent the thumbnail container from shrinking into adjacent text;
- use the user's actual figure and the existing avatar URL fallback behavior;
- keep useful alternative text based on the displayed username where that context is available.
The existing shared avatar component will be extended with an explicit compact/head-thumbnail variant, or a narrowly focused wrapper will be added if that keeps call sites clearer. Public list and compact-card call sites will migrate to this shared contract. Large/profile call sites will remain explicit so they cannot be accidentally cropped by a global CSS rule.
## Currency Design
All public currency amount rows will use the existing `CurrencyIcon` component and the existing assets under `public/assets/images/icons/currency`.
The mapping is:
- credits: `credits.png`;
- duckets: `duckets.png`;
- diamonds/crystals: `diamonds.png`.
Icons will be decorative when the surrounding UI already names the currency, using an empty alternative text to avoid repeated screen-reader announcements. The numeric amount and existing pill/layout styling remain unchanged. Icon size will be fixed consistently for compact amount rows, with no textual placeholder left visible.
## Migration Strategy
1. Add the shared compact avatar contract and focused tests.
2. Inventory public avatar call sites and classify each as compact thumbnail or large/profile preview.
3. Migrate every compact call site to the shared head-only 40 x 40 rendering.
4. Replace textual and empty CSS currency markers in public amount rows with `CurrencyIcon` and the correct currency kind.
5. Remove CSS rules that exist only to draw obsolete letter-based or background-only markers, while retaining layout classes still used by the amount pills.
This semantic migration is preferred over a global CSS crop because it sends the correct head-only request to the imager and does not risk changing profile avatars.
## Verification
Verification will include:
- automated tests for the compact avatar contract (`headOnly`, fixed dimensions, actual figure propagation);
- source/component checks ensuring public currency rows use `CurrencyIcon` with the correct mapping and no placeholder letters remain;
- the existing test, type-check, and build commands relevant to the changed files;
- visual checks at desktop and narrow widths for rankings, leaderboard, shop, badge purchase, and representative user lists/cards;
- explicit checks that profile pages and large avatar previews still render full avatars.
## Non-goals
- changing balances or currency business logic;
- changing the avatar imager service itself;
- redesigning profile hero sections;
- modifying admin-only layouts that do not share the affected public components.
@@ -1,438 +0,0 @@
# Housekeeping modernization design
Date: 2026-08-24
Status: approved in design review; awaiting review of this written specification
## Purpose
Replace the current administration experience with one coherent, role-adaptive Housekeeping (HK) at `/admin`.
The new HK is a modular part of the existing Next.js application. It is built in parallel, validated against the current system, and exposed with one atomic cutover. It unifies the current `/admin` and `/mod` surfaces, removes duplicated workflows, and preserves reliable domain services without automatically preserving their current pages.
This document is the master architecture for the program. It is deliberately not one giant implementation plan. Delivery is split into independently specified and verified subprojects, beginning with **Inventory & Foundation**.
## Current-state findings
- The repository currently contains 124 `page.tsx` files below `src/app/admin` and 13 below `src/app/mod`: 137 administration pages in total.
- `src/lib/admin-nav.ts` currently exposes nine navigation groups and seven hub definitions.
- `/admin` and `/mod` provide overlapping moderation, ticket, ban, team, and user workflows with separate shells.
- `/admin/housekeeping` is a legacy permission archive/comparison/export surface, while `/admin/permissions` is the live permission-management surface.
- The current dashboard reports useful counts but is not an operational work queue.
- Page composition, localization, ACL checks, filtering, error handling, and action feedback are not yet uniform across the administration surface.
The migration must therefore classify every current page. A visual refresh without workflow and boundary changes is insufficient.
## Approved decisions
| Area | Decision |
| --- | --- |
| Audience | One role-adaptive HK. Effective capabilities, not rank names alone, determine what an operator sees and can do. |
| Entry point | `/admin` is the only administration entry point after cutover. `/mod` is removed. |
| Layout | Command Deck: compact domain rail, contextual navigation, global command palette, operational workspace. |
| Personalization | Hybrid: the system supplies mandatory capability-derived content; the operator may pin and reorder allowed shortcuts and optional widgets. |
| Compatibility | Clean break. Old subroute compatibility and legacy UX are not preserved through redirects. |
| Build strategy | Build the new HK in parallel, keep it unavailable to normal production operators, then switch atomically. |
| Work queue | “Da fare ora” is derived from existing sources. It is not a second task database and never owns workflow state. |
| Command palette | It navigates, searches entities, and executes only safe commands. Sensitive actions open a dedicated contextual flow. |
| Architecture | Modular hybrid replacement inside the current application: reuse sound services, rebuild weak UI/workflows, merge duplicates, and remove obsolete surfaces. |
## Goals
1. Give each operator one clear, capability-appropriate place to work.
2. Replace feature sprawl with six stable domains and consistent page contracts.
3. Make urgent work visible without copying or diverging from source workflow state.
4. Enforce authorization, validation, transaction boundaries, error semantics, and audit behavior server-side.
5. Remove `/mod`, the legacy HK archive page, duplicate hubs, and manual navigation concepts that the new foundation owns.
6. Reach explicit functional, authorization, audit, localization, accessibility, and data-parity gates before cutover.
7. Keep rollback practical without exposing a mixed legacy/new experience.
## Non-goals
- Creating a separate HK application, microservice, or deployment.
- Creating a new assignment/task system for the operational inbox.
- Preserving every current page, route, component, or interaction.
- Adding backward-compatible redirects for removed administration subroutes.
- Providing full sensitive-workflow parity on phones. The target is desktop-first with usable tablet layouts.
- Redesigning public CMS or game-client experiences as part of this program.
- Replacing sound domain logic solely for architectural uniformity.
## Architecture
### Modular monolith
The HK remains inside EpicNext CMS and uses the application's existing authentication, database, service, localization, and deployment infrastructure.
The target source organization separates composition from behavior:
```text
src/app/admin/ route composition only
src/features/housekeeping/
foundation/ shell, registry, ACL context, preferences
domains/
operations/ derived inbox, global search, recent work
people/
content/
economy/
hotel/
system/
src/lib/services/ existing and extracted domain services
```
The exact filenames are an implementation-plan concern, but the boundaries are mandatory:
- App Router files compose pages and bind route parameters; they do not own business rules.
- The foundation owns cross-cutting HK behavior and does not mutate domain data.
- Each domain owns its queries, commands, search providers, inbox providers, widgets, and page composition.
- Domains do not import another domain's UI internals. Cross-domain interaction uses registered contracts or links to the owning route.
- Existing reliable services are adapted behind domain contracts rather than copied into the new UI.
### Module manifest and registry
Every domain exports a manifest with stable identifiers for:
- domain metadata and localized labels;
- routes and contextual navigation;
- required capabilities;
- command-palette entries;
- entity-search providers;
- derived-inbox sources;
- mandatory and optional dashboard widgets.
The foundation composes these manifests into the rail, contextual navigation, palette, dashboard, and route metadata. Contract tests reject duplicate IDs, duplicate routes, missing localization keys, unknown capability slugs, and commands without an owner.
The manifest registry replaces hand-maintained duplication between the sidebar, hubs, search, and dashboards. It is code-owned and reviewable. Operator preferences can alter presentation only within what the registry and capability context permit.
### Capability context
The server creates one request-scoped capability context from the authenticated operator and the existing ACL source.
- Capability checks are based on effective permission slugs.
- Super-administrator behavior remains explicit and testable.
- Rank may help choose default presentation, but never grants access by itself.
- Navigation filtering is a usability feature, not an authorization boundary.
- Every query and command rechecks its capability on the server and defaults to deny.
## Functional domains
| Domain | Owns | Representative current areas |
| --- | --- | --- |
| Da fare & operations | Derived inbox, global search, recent work, favorites, operational summaries | Dashboard, selected alerts and cross-domain counts; projections only |
| People & community | Users, online state, accounts, guilds, applications, staff directory, moderation, support | Users, multi-accounts, guilds, applications, CFH, moderation actions, bans, IP/VPN, word filter, tickets, help tickets, `/mod/*` |
| Content & engagement | Public/editorial content and engagement workflows | Articles, photos, media, banners, ads, events, polls, help content, tags, prefixes, writable boxes, email content, branding/localization surfaces |
| Economy & catalog | Products, value, commercial assets, and economic history | Catalog, items, import/maintenance, shop, marketplace, transactions, vouchers, subscriptions, rare values, badges, achievements, sounds |
| Hotel & world | Live hotel surfaces and world-management tools | Rooms, navigator, radio, studio/runtime asset tools, contextual hotel actions |
| System, access & observability | Configuration, authorization, diagnostics, and privileged operations | Permissions, access audit, settings, maintenance, emulator, command center, logs, analytics, alerts, DevOps |
Where an existing feature spans two domains, responsibility follows the action rather than the old route. For example, the staff directory belongs to People, while the policy granting staff capabilities belongs to System and Access.
Domain landing pages summarize their own workflows. They do not recreate the global dashboard or become a second source of state.
## Operator experience
### Command Deck shell
The shared shell contains:
1. A compact rail for the six domains.
2. Contextual navigation generated from the active domain manifest.
3. A global command/search field available by keyboard.
4. A main workspace using consistent title, context, primary action, filters, content, and feedback regions.
5. Operator identity, effective-capability context, notifications, and session controls.
The shell is desktop-first, fully keyboard operable, and responsive for tablets. Phone layouts may support inspection and low-risk triage, but sensitive multi-step operations are not optimized for phone use.
### Adaptive dashboard
ACL and capability data determine:
- visible domains and routes;
- mandatory queues and warnings;
- permitted metrics and widgets;
- available commands and search providers.
The operator may:
- pin allowed routes and safe commands;
- reorder shortcuts and optional widgets;
- add or remove optional allowed widgets;
- persist preferred filters and presentation density where supported.
The operator may not hide mandatory warnings, reveal unauthorized data, or preserve a shortcut after its required capability is lost.
Preferences are server-persisted, user-scoped, schema-versioned, and non-authoritative. If no suitable existing preference store exists, the foundation adds one additive `housekeeping_user_preferences` store containing presentation state only. It never stores task status or authorization decisions. Every preference is reconciled with the current manifest and capability context when read.
### Standard page contract
Every target page follows the same structural contract:
- localized title, description, breadcrumb/context, and one clear primary action;
- capability-derived actions with server authorization;
- shared filtering, pagination, empty, loading, partial, and error states;
- explicit unsaved-change behavior for editable forms;
- consistent confirmation and outcome feedback;
- stable deep links to owned entities and workflows;
- responsive table-to-detail behavior without hiding critical fields;
- audit context for mutations.
## Operational inbox
The inbox is a read model over domain-owned sources such as tickets, CFH reports, alerts, emulator errors, and detected anomalies.
Each source emits normalized work items containing at least:
- stable source and item IDs;
- domain and required capability;
- severity and source timestamp;
- localized summary and optional context;
- stable destination route and entity target;
- deduplication key;
- freshness/availability metadata.
The aggregator:
1. Requests sources independently with bounded timeouts.
2. Filters every result against the operator's capability context.
3. Deduplicates by stable source identity.
4. Orders by severity, age, and domain policy.
5. Returns both items and per-source availability.
The aggregator never creates, assigns, dismisses, or completes work. Selecting an item opens the owning workflow. If that workflow supports assignment or resolution, those state changes occur there.
A failed or timed-out source does not erase successful sources. The UI labels the missing source and the freshness of remaining data instead of presenting the whole system as healthy.
## Global search and command palette
The palette has three provider types:
1. **Navigation providers** for permitted routes and favorites.
2. **Entity providers** for capability-filtered entities such as users, rooms, tickets, articles, or catalog entries.
3. **Safe command providers** for narrowly scoped, validated, idempotent or reversible actions.
A mutation may run directly from the palette only when it is single-target, low impact, reviewable in the palette, protected by a specific capability, and safe against duplicate submission. It still uses the normal server command and audit path.
Destructive, economic, moderation, permission, bulk, or otherwise sensitive actions return a navigation intent. The target page receives validated context and shows impact, current state, required reason, confirmation, and final outcome.
## Data and command flow
### Queries
```text
page or shell
-> request-scoped capability context
-> typed domain query
-> existing API/repository through an adapter
-> sanitized response
```
The UI does not query arbitrary tables or reproduce sensitive filter rules. Authorization-sensitive results are filtered at the query boundary. Short-lived caching may be used for operational counts, but authorization is applied after cache lookup and sensitive per-user results are not shared across capability contexts.
### Commands
```text
intent
-> server capability check
-> schema validation
-> current-state/concurrency check
-> domain transaction or controlled external call
-> audit outcome
-> typed result and cache invalidation
```
Every command receives a server-issued action ID used as an idempotency key. Duplicate submissions return the original known outcome rather than repeating the mutation.
For records with a revision or update timestamp, edits use optimistic concurrency. A stale edit returns a conflict result and current-state reference; it is not silently overwritten. Where a source cannot expose a revision, the command performs the strongest available transactional re-read before mutation.
## Security and audit
- Default-deny server checks protect every query and command.
- Sensitive actions require a dedicated flow, an explicit target, an impact summary, confirmation, and a non-empty operator reason.
- Domain validation occurs after authorization and before mutation.
- Audit is append-only from the HK application: no HK route can edit or delete audit events.
- Audit records include actor, target, command, reason, sanitized before/after details where appropriate, outcome, timestamp, action ID, and correlation ID.
- Secrets, credentials, tokens, and unnecessary personal data are excluded from audit payloads.
- When data and audit share a transactional store, a privileged mutation and its audit record commit together.
- For external operations, an intent/pending audit record is written before dispatch and completed with success or failure afterward.
- A privileged mutation fails closed if its required audit trail cannot be established.
## Error model
Domain boundaries return typed outcomes rather than leaking raw infrastructure errors:
- validation failure;
- authentication required;
- capability denied;
- not found;
- stale/conflicting state;
- dependency unavailable;
- partial aggregate result;
- unexpected internal failure.
Expected outcomes have localized, actionable messages. Unexpected failures expose a correlation ID to the operator and retain technical detail only in server logs. Forms preserve safe input after recoverable failures. Lists and the operational dashboard distinguish empty results from unavailable data.
## Migration inventory
The first subproject creates a committed migration matrix covering all 137 current pages. Each row contains:
- legacy path and source surface (`admin` or `mod`);
- target domain and owning workflow;
- target path;
- decision: `REHOST`, `REBUILD`, `MERGE`, or `REMOVE`;
- required read and mutation capabilities;
- source queries and mutations;
- audit requirement;
- localization and accessibility status;
- required unit, integration, and E2E coverage;
- parity evidence and migration status.
Decision meanings:
- **REHOST**: the current UI and service are sound enough to enter the new shell after contract and ACL adaptation.
- **REBUILD**: preserve the workflow and sound service logic, but reconstruct its interaction and page composition.
- **MERGE**: combine duplicated routes or variants into one owning workflow with contextual views.
- **REMOVE**: eliminate obsolete or foundation-owned behavior at cutover.
Mandatory consolidations:
- All 13 `/mod` pages merge into People and Community workflows. `/mod` does not redirect after cutover.
- `/admin/housekeeping` ceases to exist as a named feature. Useful comparison/export history moves into System, Access, and Audit.
- `/admin/permissions` remains the live policy editor under System and Access.
- Legacy dashboard, hub, and manual HK-navigation concepts are removed when their responsibilities are supplied by the registry and Command Deck.
No page is considered migrated merely because it renders in the new shell. Its matrix row closes only after data, actions, capability behavior, audit, localization, accessibility, and required tests pass.
## Delivery decomposition
This master design controls the program. For delivery purposes it is also the approved design specification for subproject 01. Subprojects 02 through 06 require their own scoped design specifications before their implementation plans. Subprojects are delivered in this order:
### 01. Inventory & Foundation
This is the first and only scope of the initial implementation plan.
Deliverables:
- the complete 137-page migration matrix;
- HK manifest contracts and registry validation;
- request-scoped capability context and server guard interfaces;
- domain query, command, search, inbox, and widget contracts;
- the Command Deck shell primitives and standard page-state contract;
- six domain manifests with no migrated business workflow yet;
- a non-production/test-only entry mechanism that cannot expose a mixed HK to normal production operators;
- contract, capability, localization-key, accessibility-smoke, and shell tests.
Explicit exclusions:
- no current `/admin` or `/mod` route changes;
- no production operator exposure;
- no operational inbox aggregation;
- no entity search implementation;
- no domain mutation migration;
- no legacy deletion.
### 02. Access, audit & system core
Implement the capability enforcement adapters, audit command path, error taxonomy, correlation IDs, and core observability used by every later vertical.
### 03. People, moderation & support
Deliver the first complete vertical and unify user, ticket, CFH, moderation-action, and ban workflows. This vertical proves the future removal of `/mod` without exposing a partial cutover.
### 04. Command Deck operations
Implement global search, safe commands, favorites, preferences, and the derived inbox against the sources available from completed verticals.
### 05. Remaining domain verticals
Deliver separate scoped specifications and plans for:
1. Content and Engagement;
2. Hotel and World;
3. Economy and Catalog;
4. remaining System, Access, and Observability pages.
Economy and permission-affecting mutations receive the strictest confirmation, concurrency, and audit coverage.
### 06. Parity, cutover & cleanup
Close the migration matrix, run cross-role journeys and data comparisons, switch `/admin`, make `/mod` unreachable, observe the release, then delete unreachable legacy code and later remove obsolete schema safely.
Subproject 01 uses this specification; every later subproject has its own spec, implementation plan, tests, review, and completion gate. A later subproject may not silently expand an earlier approved scope.
## Verification strategy
Every subproject runs proportionate checks from these layers:
1. **Unit tests** for manifest parsing, normalizers, policy functions, reducers, and domain services.
2. **Contract tests** for unique IDs/routes, capability declarations, localization keys, command ownership, and provider behavior.
3. **Integration tests** against representative repository/API implementations, including transactions, external failures, idempotency, and conflicts.
4. **ACL matrix tests** covering permitted, denied, capability-revoked, and super-administrator cases at both render and server boundaries.
5. **E2E journeys** for moderation, support, editorial, economy, hotel operations, and administration roles defined by capabilities rather than rank labels.
6. **Audit assertions** after every tested mutation.
7. **Accessibility checks** for keyboard use, focus order, names, contrast, live feedback, dialogs, and table/detail transitions.
8. **Localization checks** rejecting new hard-coded operator copy and missing translation keys.
9. **Visual regression checks** for the shared shell and high-risk standard states.
10. **Performance comparison** against a recorded legacy baseline using the same environment and dataset. Comparable new flows may not regress median or p95 response time by more than 10% without an explicit reviewed exception. Performance improvements are reported only from measurements.
## Cutover gate
The atomic switch is permitted only when all of the following are true:
- all 137 migration rows are closed with evidence;
- every exposed query and command has a declared and tested capability;
- every mutation has validation and required audit coverage;
- no blocking or critical defect remains open;
- equivalent legacy/new counts and records have been compared for migrated read workflows;
- role journeys for moderator, support operator, editor, economy operator, hotel operator, and administrator pass;
- localization, accessibility, build, type, lint, test, and visual checks pass;
- production-like smoke tests, backup verification, rollback procedure, and health checks have been rehearsed;
- the new HK is not dependent on legacy UI routes;
- communication and operator runbooks are ready for the clean break.
## Cutover and rollback
Before cutover, the new HK is exercised through test/staging or an explicit non-production mechanism. Read-only shadow comparisons may run against representative data. There is no production dual-write.
At cutover:
1. `/admin` changes to the new route composition in one release/flag transition.
2. `/mod` and removed legacy subroutes become unreachable without compatibility redirects.
3. Smoke tests verify authentication, capability filtering, representative reads, one controlled mutation per risk class, audit, and health signals.
Database changes required before cutover are additive and backward-compatible for the emergency rollback window. A flag or previous release can temporarily restore the legacy application if the cutover fails. During normal operation, only one HK is exposed.
After the agreed stability window, unreachable legacy code and flags are removed. Destructive schema cleanup is a later migration and is not coupled to the cutover release.
## Success criteria
The program is complete when:
- `/admin` is the single role-adaptive administration surface;
- `/mod` and the legacy Housekeeping archive surface are gone;
- all 137 legacy pages have an evidenced migration decision;
- all exposed data, navigation, commands, widgets, and inbox items are capability-correct;
- the operational inbox derives live work without owning duplicate workflow state;
- all mutations use the domain command, validation, concurrency, idempotency, and audit path appropriate to their risk;
- no mixed legacy/new production experience exists;
- measured performance meets the approved comparison gate;
- rollback and eventual legacy cleanup are complete.
## Rejected alternatives
### Full greenfield rewrite
Rejected because it would discard reliable existing services and maximize parity, timing, and regression risk across 137 pages.
### Cosmetic refactor of the existing HK
Rejected because it would preserve duplicated `/admin` and `/mod` workflows, inconsistent page boundaries, and manual navigation debt.
### Separate HK service/application
Rejected because the current requirement does not justify another deployment, authentication boundary, or distributed consistency problem.
### Persistent cross-domain task database
Rejected because it would duplicate ticket, moderation, alert, and anomaly state and create reconciliation failure modes.
## Final design invariant
The migration may be incremental internally, but the operator-facing product is not. Until the cutover gate passes, the current HK remains the only normal production surface. After cutover, the new HK is the only surface.
-23
View File
@@ -1,23 +0,0 @@
# Real database integration tests
Run `pnpm test:integration` on a Docker-capable host. Missing Docker or failed container setup fails the suite. CI runs this check before deployment.
Sixteen database tests exercise the production database commands, news actions, public article query and delivery worker against MariaDB 11.4.5 and Redis 7.4.2:
- Migration CLI replay/status, committed catalog bulk edits and undo history, complete rollback after an audit insert fails, and competing catalog previews.
- Real Redis expiry metadata and cache-key isolation, concurrent request idempotency, operation/outbox rollback, and exclusive delivery claims.
- Concurrent duplicate draft creation and publication produce one article, one revision, one audit update and one effect per operation. The public query changes from cached absence to the full published content, including Unicode and a body larger than a TEXT column.
- A database trigger rejects the publication effect after the article, revision and audit writes. The transaction restores all preceding state; the identical request can then retry successfully without duplicate history.
- A trigger rejects the second scheduled-publication effect. Both article updates and both operations roll back, including the first queued effect.
- Competing scheduler ticks publish each due article once, preserve future articles and drafts, retain an unsigned bigint ID beyond JavaScript's safe integer range, and attribute a legacy authorless article to the system actor.
- A real Redis client disconnect leaves a publication committed and readable directly from MariaDB. The worker records a pending failed attempt. Reconnecting retains the stale cached absence until a successful outbox retry rotates the cache revision; the public query then returns the published article. The test advances only the queued retry timestamp to avoid sleeping.
Each execution starts disposable containers with random exposed ports and generated passwords. No production URLs, volumes or credentials are used. The real migration CLI is copied beneath a temporary isolated fixture root so its environment loader cannot read the checkout environment file. Cleanup attempts all connections and containers even if a previous cleanup fails. The fixture inspection connection reads timestamps as UTC; the application keeps its production connection settings and host timezone. Each test receives a fresh news-cache revision, and the disconnect test reconnects its client in a `finally` block.
Only authorization/session lookup, translation lookup, Next.js revalidation/redirects, and the external publication webhook are mocked for the news actions. MariaDB, Drizzle, transactions, article revisions, history, operation deduplication, outbox claims/retries, Redis caching, the publication scheduler, public article lookup and the news delivery handler use their production implementations.
The fixture models the emulator's catalog/audit baseline plus the legacy article columns. Real migrations 0025-0029 and 0031 supply publication, editorial recovery, catalog packages, history and operations tables. This does not certify every historical emulator schema or migration.
These are application-service integration tests, not browser or HTTP end-to-end tests: they do not start a Next.js server, render the news page, verify login/ACL behavior, or send external webhooks. The cache outage test closes and restores the actual application Redis connection; it does not stop the Redis server or model a multi-host network partition. Passing TypeScript or unit tests without Docker is not a passing result for this suite.
Public comment pagination and reaction aggregation are covered by unit tests using the production Drizzle query builder with a substituted database transport, plus server-rendered page tests with substituted service results. This integration fixture does not create users or article-reactions tables and does not execute the public pagination and aggregation queries against MariaDB; its article-comments table is used for submission tests. Comment submission now additionally uses real MariaDB and Redis to verify publication eligibility, filtering and the shared quota across the actual form/API handlers, with authentication replaced at the boundary. The article-cache upgrade test verifies that legacy cached absence is ignored under the versioned key; it is a unit test, separate from the real Redis publication and delivery checks above.
-38
View File
@@ -1,38 +0,0 @@
# Real news browser gate
Run `pnpm test:news:real` with `NEWS_E2E_IMAGE=epicnext-cms:<candidate-tag>`. Docker CLI, a working Docker daemon, the OpenSSL CLI with `-addext` support, installed project dependencies and Playwright Chromium are required. The runner deliberately fails when the image or Docker is unavailable. It never silently skips the browser journey.
`NEWS_E2E_RELEASE=<full-commit-sha>` additionally verifies the image revision label. The runner resolves the local image to its immutable ID before starting it. It does not build or pull the application image. MariaDB 11.4.5 and Redis 7.4.2 Alpine are disposable Testcontainers dependencies and may be pulled when absent.
The deployment script runs this gate after building the candidate and extracting its performance report, before live database migrations and container cutover. The general Playwright suite excludes `e2e/news-real`; this suite has its own configuration and requires the runner.
## What the browser proves
One Chromium journey exercises the candidate's normal Docker entrypoint and standalone Next server:
1. An anonymous request to the staff editor reaches the login page.
2. The browser signs in through the actual login form, credential precheck and Auth.js handler. The test verifies the real Secure/HttpOnly session cookie and database login record.
3. A rank 7 editor, below an occupied rank 9 owner, accesses news through three explicit ACL grants: `admin.dashboard`, `admin.news.view` and `admin.news.edit`.
4. The browser types Unicode content into the bundled TinyMCE editor and saves a draft through the real server action. The persisted HTML must equal what the form submitted.
5. An independent anonymous browser sees the not-found screen; the public articles API returns an empty list. Redis contains the cached null article. Next can stream a not-found screen with HTTP 200, so this check verifies the rendered 404 screen as well as absence from the API.
6. The editor reopens and previews the saved draft in the real preview iframe. Its title, summary and rendered body match; it remains a draft with no article revision created by previewing.
7. Publishing through the editor produces one article, a publication timestamp, one previous-draft revision, a before/after audit entry, two completed operation results and two news-refresh outbox entries.
8. The anonymous page and API immediately show the article, using a new shared Redis cache revision. The browser remains signed out.
No authentication, application HTTP responses, mutations, database calls or cache calls are mocked. The browser blocks resources outside the local fixture origin, such as external avatars. This does not replace any application response. A local HTTPS edge passes requests to Next and sets trusted forwarding headers, allowing the production Secure-cookie behavior to run normally.
The fresh browser contexts retain normal application service-worker registration. The application worker does not cache article or authentication responses. Playwright's worker-blocking injection is avoided because it throws inside the sandboxed preview; browser errors are still checked without filtering. The preview is closed through its Close button, since keyboard events inside its sandbox do not reach the parent dialog.
## Isolation and cleanup
- Each run creates a random Docker network and fresh MariaDB, Redis and candidate containers. All mapped ports are allocated dynamically. The HTTPS listener binds only to `127.0.0.1`.
- No production container, database, volume or credentials are reused. Container configuration is explicit. Child processes receive a small environment whitelist; checkout `.env` and installation service credentials are not forwarded.
- The database uses the current ORM column definitions for 29 tables needed by login, site/admin layouts and news. Unique constraints and composite primary keys are preserved. The emulator-owned `permission_ranks` fixture provides the rank authority columns this flow queries. Real CMS migrations 0026 and 0031 create the recovery/revision and operation/outbox tables. This is a focused fixture, not a replacement for the emulator's complete schema or migration coverage.
- Passwords, Redis credentials and the Auth.js secret are generated per run. The owner has an unknown random password and is never used to bypass ACL checks. Email verification is enabled with a verified fixture staff account. CAPTCHA and forced staff 2FA use their ordinary disabled installation settings; their challenges are outside this flow.
- OpenSSL generates a fresh localhost certificate and private key in the OS temporary directory for each run. The certificate lasts one day and covers `127.0.0.1` and `localhost`. Playwright trusts this self-signed endpoint only in this suite. No certificate or key is committed or copied into build artifacts; cleanup removes both with the temporary credentials.
- Credentials used by the test worker are stored in an OS temporary directory with a mode-0600 file, then removed. Cleanup stops only containers and the network created by this runner; Testcontainers also registers them with its resource reaper.
- Failure artifacts are under `test-results/news-real` and `playwright-report/news-real`. Server logs redact generated passwords/secrets. Playwright traces can contain the short-lived fixture login/session data; all associated services are destroyed after the run.
This browser gate checks the synchronous editor/publication path and durable delivery intent. Scheduler concurrency, rollback, duplicate requests, worker delivery and Redis outage/recovery remain covered by `pnpm test:integration`. It does not claim to test emulator connectivity, external notifications, CAPTCHA/2FA challenges or production data.
The local workstation currently has no working Docker daemon. Type checks, lint and fixture/bootstrap checks can run there; a passing real browser result must come from the Docker-capable CI gate.
+1
View File
@@ -1,3 +1,4 @@
import "dotenv/config";
import { defineConfig } from "drizzle-kit";
// Schema source of truth for the query builder: src/db/schema.ts
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-13
View File
@@ -1,13 +0,0 @@
{
"version": "7",
"dialect": "mysql",
"entries": [
{
"idx": 0,
"version": "5",
"when": 1788791201804,
"tag": "0000_premium_spirit",
"breakpoints": true
}
]
}
@@ -1,12 +0,0 @@
-- 0020_performance_indexes.sql
-- Adds indexes for the hot CMS read paths (shared DB with the Arcturus
-- emulator — additive only, no schema changes to emulator-owned columns).
--
-- users.credits → credits leaderboard (ORDER BY credits DESC LIMIT 20)
-- users_currency(type, amount) → duckets/diamonds leaderboard (WHERE type=? ORDER BY amount DESC LIMIT 20)
-- users_settings.respects_received → respects leaderboard (ORDER BY respects_received DESC LIMIT 20)
-- camera_web.timestamp → homepage recent photos (ORDER BY timestamp DESC LIMIT 4)
CREATE INDEX IF NOT EXISTS `idx_users_credits` ON `users` (`credits`);
CREATE INDEX IF NOT EXISTS `idx_users_currency_type_amount` ON `users_currency` (`type`, `amount`);
CREATE INDEX IF NOT EXISTS `idx_users_settings_respects_received` ON `users_settings` (`respects_received`);
CREATE INDEX IF NOT EXISTS `idx_camera_web_timestamp` ON `camera_web` (`timestamp`);
@@ -1,4 +0,0 @@
-- 0021_add_messenger_offline_user_id_index.sql
-- The /me dashboard counts unread offline messages with
-- `WHERE user_id = ?`; messenger_offline previously had no index there.
CREATE INDEX IF NOT EXISTS `idx_messenger_offline_user_id` ON `messenger_offline` (`user_id`);
@@ -1,4 +0,0 @@
-- Add terms/age consent columns expected by the users schema (register flow).
ALTER TABLE `users`
ADD COLUMN `terms_accepted` TINYINT(1) NOT NULL DEFAULT 0,
ADD COLUMN `age_verified` TINYINT(1) NOT NULL DEFAULT 0;
@@ -1,37 +0,0 @@
-- Theme Builder: scoped theme system for per-route, per-module, and multi-site theming.
-- Idempotent: safe to re-run.
CREATE TABLE IF NOT EXISTS theme_scopes (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
type ENUM('global','site','module','route') NOT NULL,
parent_id BIGINT UNSIGNED NULL,
site_domain VARCHAR(255) NULL,
route_path VARCHAR(255) NULL,
module_id VARCHAR(100) NULL,
is_active TINYINT(1) NOT NULL DEFAULT 1,
sort_order INT NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY theme_scopes_parent_idx (parent_id),
KEY theme_scopes_type_idx (type),
UNIQUE KEY theme_scopes_unique_lookup (type, site_domain, route_path, module_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS theme_scope_values (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
scope_id BIGINT UNSIGNED NOT NULL,
setting_key VARCHAR(100) NOT NULL,
setting_val VARCHAR(255) NOT NULL,
mode ENUM('light','dark') NOT NULL DEFAULT 'light',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY theme_scope_values_unique (scope_id, setting_key, mode),
KEY theme_scope_values_scope_idx (scope_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Seed: create the global scope from existing website_settings theme data.
INSERT IGNORE INTO theme_scopes (id, name, type, parent_id, is_active, sort_order)
VALUES (1, 'Global', 'global', NULL, 1, 0);
@@ -1,3 +0,0 @@
INSERT INTO `acl_permissions` (`slug`, `title`)
VALUES ('housekeeping.preview.access', 'Access Housekeeping preview')
ON DUPLICATE KEY UPDATE `title` = VALUES(`title`);
@@ -1,7 +0,0 @@
-- Existing articles remain published. Preserve any publication settings already present.
ALTER TABLE website_articles
ADD COLUMN IF NOT EXISTS status VARCHAR(20) NOT NULL DEFAULT 'published',
ADD COLUMN IF NOT EXISTS publish_at TIMESTAMP NULL DEFAULT NULL,
ADD COLUMN IF NOT EXISTS published_at TIMESTAMP NULL DEFAULT NULL;
CREATE INDEX IF NOT EXISTS idx_website_articles_publication
ON website_articles (status, publish_at, created_at);
@@ -1,16 +0,0 @@
CREATE TABLE IF NOT EXISTS website_article_drafts (
user_id BIGINT UNSIGNED NOT NULL,
article_key VARCHAR(32) NOT NULL,
version INT UNSIGNED NOT NULL,
payload LONGTEXT NOT NULL,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (user_id, article_key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS website_article_revisions (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
article_id BIGINT UNSIGNED NOT NULL,
user_id BIGINT UNSIGNED NOT NULL,
payload LONGTEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
INDEX article_history (article_id, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
@@ -1,10 +0,0 @@
CREATE TABLE IF NOT EXISTS website_catalog_packages (
id VARCHAR(36) NOT NULL PRIMARY KEY,
name VARCHAR(128) NOT NULL,
version INT UNSIGNED NOT NULL,
status VARCHAR(16) NOT NULL,
mode VARCHAR(16) NOT NULL,
payload LONGTEXT NOT NULL,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
INDEX package_recent (updated_at, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
@@ -1,2 +0,0 @@
-- Preserve complete before/after snapshots for long news articles.
ALTER TABLE admin_audit_log MODIFY COLUMN `before` MEDIUMTEXT NULL, MODIFY COLUMN `after` MEDIUMTEXT NULL;
@@ -1,7 +0,0 @@
CREATE TABLE IF NOT EXISTS website_admin_table_views (
user_id INT NOT NULL,
path VARCHAR(191) NOT NULL,
name VARCHAR(60) NOT NULL,
state TEXT NOT NULL,
PRIMARY KEY (user_id, path, name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
@@ -1,9 +0,0 @@
CREATE TABLE IF NOT EXISTS `website_profile_privacy` (
`user_id` int NOT NULL,
`wallet` boolean NOT NULL DEFAULT false,
`online` boolean NOT NULL DEFAULT true,
`friends` boolean NOT NULL DEFAULT true,
`photos` boolean NOT NULL DEFAULT true,
`registered` boolean NOT NULL DEFAULT true,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
@@ -1,25 +0,0 @@
CREATE TABLE IF NOT EXISTS cms_operations (
id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY,
actor_id INT NOT NULL,
kind VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
request_key CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
request_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
result_json MEDIUMTEXT NULL,
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
UNIQUE KEY operation_request (actor_id,kind,request_key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS cms_outbox (
id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY,
operation_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
topic VARCHAR(64) NOT NULL,
status VARCHAR(16) NOT NULL DEFAULT 'pending',
attempts INT NOT NULL DEFAULT 0,
available_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
lease_until DATETIME(3) NULL,
lease_token CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NULL,
last_error VARCHAR(255) NULL,
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
UNIQUE KEY operation_effect (operation_id,topic),
KEY delivery_pending (status,available_at),
KEY delivery_lease (status,lease_until)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
@@ -1,13 +0,0 @@
CREATE TABLE IF NOT EXISTS `website_notification_reads` (
`user_id` int NOT NULL,
`event_key` varchar(128) NOT NULL,
`read_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`user_id`, `event_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `website_notification_preferences` (
`user_id` int NOT NULL,
`support` boolean NOT NULL DEFAULT true,
`friends` boolean NOT NULL DEFAULT true,
`events` boolean NOT NULL DEFAULT true,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
@@ -1,154 +0,0 @@
-- 0033_referrals_daily_rewards.sql
-- Referral attribution tables (mirror the live-DB shape used by the existing
-- referral claim flow in src/actions/referral.ts) plus the CMS-owned daily
-- login reward schedule and claim ledger. All CREATE statements are idempotent
-- (IF NOT EXISTS) so fresh installs get the tables and existing hotels keep
-- whatever rows they already have.
CREATE TABLE IF NOT EXISTS `user_referrals` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` INT NOT NULL,
`referrals_total` BIGINT UNSIGNED NOT NULL DEFAULT 0,
`created_at` TIMESTAMP NULL,
`updated_at` TIMESTAMP NULL,
PRIMARY KEY (`id`),
KEY `user_referrals_user_idx` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `referrals` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` INT NOT NULL,
`referred_user_id` BIGINT UNSIGNED NOT NULL,
`referred_user_ip` VARCHAR(255) NOT NULL,
`created_at` TIMESTAMP NULL,
`updated_at` TIMESTAMP NULL,
PRIMARY KEY (`id`),
KEY `referrals_user_idx` (`user_id`),
KEY `referrals_referred_user_idx` (`referred_user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `claimed_referral_logs` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` INT NOT NULL,
`ip_address` VARCHAR(255) NOT NULL,
`created_at` TIMESTAMP NULL,
`updated_at` TIMESTAMP NULL,
PRIMARY KEY (`id`),
KEY `claimed_referral_logs_user_idx` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Daily login reward schedule: one row per streak day. The cycle repeats after
-- the highest day (day 1 of the cycle is used for any missing day).
CREATE TABLE IF NOT EXISTS `website_daily_rewards` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`day` INT UNSIGNED NOT NULL DEFAULT 1,
`currency` VARCHAR(20) NOT NULL DEFAULT 'credits',
`amount` INT NOT NULL DEFAULT 0,
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`updated_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
PRIMARY KEY (`id`),
UNIQUE KEY `website_daily_rewards_day_uk` (`day`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Daily reward claims ledger; one row per user per claim date.
CREATE TABLE IF NOT EXISTS `website_daily_reward_claims` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` INT NOT NULL,
`claim_date` DATE NOT NULL,
`streak` INT UNSIGNED NOT NULL DEFAULT 1,
`reward_day` INT UNSIGNED NOT NULL DEFAULT 1,
`currency` VARCHAR(20) NOT NULL DEFAULT 'credits',
`amount` INT NOT NULL DEFAULT 0,
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
PRIMARY KEY (`id`),
UNIQUE KEY `daily_claim_user_date_uk` (`user_id`, `claim_date`),
KEY `daily_claim_created_idx` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Seed a sensible 7-day reward schedule only when the table is still empty.
INSERT INTO `website_daily_rewards` (`day`, `currency`, `amount`)
SELECT 1, 'duckets', 60
FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM `website_daily_rewards`);
INSERT INTO `website_daily_rewards` (`day`, `currency`, `amount`)
SELECT 3, 'credits', 50
FROM DUAL
WHERE (SELECT COUNT(*) FROM `website_daily_rewards`) = 1
AND NOT EXISTS (SELECT 1 FROM `website_daily_rewards` WHERE `day` = 3);
INSERT INTO `website_daily_rewards` (`day`, `currency`, `amount`)
SELECT 5, 'diamonds', 2
FROM DUAL
WHERE (SELECT COUNT(*) FROM `website_daily_rewards`) = 2
AND NOT EXISTS (SELECT 1 FROM `website_daily_rewards` WHERE `day` = 5);
-- Referral + daily reward configuration defaults (never overwrite an existing
-- value — operators tune these keys in the admin panel).
INSERT INTO `website_settings` (`key`, `value`, `comment`)
SELECT 'referrals_block_same_ip', '1', 'Block referral attribution when the new account shares the inviter IP'
FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM `website_settings` WHERE `key` = 'referrals_block_same_ip');
INSERT INTO `website_settings` (`key`, `value`, `comment`)
SELECT 'daily_reward_enabled', '1', 'Enable the daily login reward claims on /me'
FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM `website_settings` WHERE `key` = 'daily_reward_enabled');
-- New ACL slugs backing the /admin/referrals + /admin/daily-rewards modules.
INSERT INTO `acl_permissions` (`slug`, `title`) VALUES
('admin.referrals.view', 'View referrals'),
('admin.referrals.edit', 'Edit referrals'),
('admin.dailyrewards.view', 'View daily login rewards'),
('admin.dailyrewards.edit', 'Edit daily login rewards')
ON DUPLICATE KEY UPDATE `title` = VALUES(`title`);
-- Grant the new slugs to the same roles that already open the admin panel.
INSERT INTO `acl_model_permissions` (`model_type`, `model_id`, `permission_id`)
SELECT 'Role', ar.id, ap.id
FROM `acl_roles` ar
JOIN `acl_permissions` ap ON ap.slug IN (
'admin.referrals.view', 'admin.referrals.edit',
'admin.dailyrewards.view', 'admin.dailyrewards.edit'
)
WHERE EXISTS (
SELECT 1
FROM `acl_model_permissions` amp
JOIN `acl_permissions` apdash ON apdash.id = amp.permission_id
WHERE amp.model_type = 'Role'
AND amp.model_id = ar.id
AND apdash.slug = 'admin.dashboard'
)
AND NOT EXISTS (
SELECT 1
FROM `acl_model_permissions` amp2
WHERE amp2.model_type = 'Role'
AND amp2.model_id = ar.id
AND amp2.permission_id = ap.id
);
-- Safety net matching the 0018 seed: ranks >= 6 view, ranks >= 7 edit.
INSERT INTO `acl_model_permissions` (`model_type`, `model_id`, `permission_id`)
SELECT 'Role', ar.id, ap.id
FROM `permission_ranks` pr
JOIN `acl_roles` ar ON ar.slug = CONCAT('rank_', pr.id)
JOIN `acl_permissions` ap ON ap.slug IN ('admin.referrals.view', 'admin.dailyrewards.view')
WHERE pr.id >= 6
AND NOT EXISTS (
SELECT 1
FROM `acl_model_permissions` amp
WHERE amp.model_type = 'Role'
AND amp.model_id = ar.id
AND amp.permission_id = ap.id
);
INSERT INTO `acl_model_permissions` (`model_type`, `model_id`, `permission_id`)
SELECT 'Role', ar.id, ap.id
FROM `permission_ranks` pr
JOIN `acl_roles` ar ON ar.slug = CONCAT('rank_', pr.id)
JOIN `acl_permissions` ap ON ap.slug IN ('admin.referrals.edit', 'admin.dailyrewards.edit')
WHERE pr.id >= 7
AND NOT EXISTS (
SELECT 1
FROM `acl_model_permissions` amp
WHERE amp.model_type = 'Role'
AND amp.model_id = ar.id
AND amp.permission_id = ap.id
);
-302
View File
@@ -1,302 +0,0 @@
import { readFile } from "node:fs/promises";
import { type BrowserContext, expect, test } from "@playwright/test";
import Redis from "ioredis";
import mysql, {
type ConnectionOptions,
type RowDataPacket,
} from "mysql2/promise";
interface Fixture {
username: string;
userId: number;
password: string;
database: ConnectionOptions;
redis: { host: string; port: number; password: string };
}
async function onlyLocalResources(context: BrowserContext, origin: string) {
// External avatars/telemetry are outside this isolated hotel. All application
// documents, scripts, forms, API requests and auth responses remain untouched.
await context.route("**/*", (route) => {
if (new URL(route.request().url()).origin === origin)
return route.continue();
return route.abort("blockedbyclient");
});
}
test("staff signs in, saves a draft, previews it and publishes to anonymous readers", async ({
page,
context,
browser,
baseURL,
}, testInfo) => {
if (!baseURL || !process.env.NEWS_E2E_FIXTURE)
throw Error("Disposable fixture is required");
const fixture = JSON.parse(
await readFile(process.env.NEWS_E2E_FIXTURE, "utf8"),
) as Fixture;
const database = await mysql.createConnection({
...fixture.database,
timezone: "Z",
charset: "utf8mb4",
supportBigNumbers: true,
bigNumberStrings: true,
});
const redis = new Redis({
...fixture.redis,
maxRetriesPerRequest: 1,
connectTimeout: 5_000,
});
const anonymous = await browser.newContext({
baseURL,
locale: "en-US",
ignoreHTTPSErrors: true,
});
const reader = await anonymous.newPage();
const errors: string[] = [];
page.on("pageerror", (error) => errors.push(error.message));
reader.on("pageerror", (error) => errors.push(error.message));
const rows = async (sql: string, params: string[] = []) =>
(await database.query<RowDataPacket[]>(sql, params))[0];
const title = "Notizia browser: città e novità 🎉";
const publicTitle = reader.locator(
".content-card:has(.article-body) .content-card-title",
);
const slug = "browser-news-real";
const summary =
"Una notizia creata e pubblicata attraverso il pannello reale.";
const body = "È una prova reale: caffè, città e 🎉. Salvata dal browser.";
let articleId = "";
let submittedHtml = "";
let draftRevision: string | null = null;
try {
await onlyLocalResources(context, baseURL);
await onlyLocalResources(anonymous, baseURL);
await redis.ping();
await test.step("real authentication and staff ACL", async () => {
await page.goto("/admin/articles/new");
await expect(page).toHaveURL(/\/login(?:\?|$)/);
expect(await rows("SELECT user_id FROM website_login_logs")).toHaveLength(
0,
);
await page
.locator('input[autocomplete="username"]')
.fill(fixture.username);
await page
.locator('input[autocomplete="current-password"]')
.fill(fixture.password);
await page
.locator('input[autocomplete="current-password"]')
.press("Enter");
await expect(page).toHaveURL(/\/me(?:\?|$)/);
const session = await context.request
.get("/api/auth/session")
.then((response) => response.json());
expect(session.user).toMatchObject({
id: String(fixture.userId),
name: fixture.username,
rank: 7,
});
expect(
(await context.cookies()).some(
(cookie) =>
cookie.name.startsWith("__Secure-authjs.session-token") &&
cookie.secure &&
cookie.httpOnly,
),
).toBe(true);
expect(await rows("SELECT user_id FROM website_login_logs")).toEqual([
expect.objectContaining({ user_id: fixture.userId }),
]);
// The editor is below the highest occupied rank: access requires real ACL grants.
expect(
(await rows("SELECT MAX(rank) AS highest FROM users"))[0].highest,
).toBe(9);
await page.goto("/admin/articles/new");
await expect(page.locator('input[name="title"]')).toBeVisible();
});
await test.step("save the draft using the real rich text editor and server action", async () => {
const form = page.locator('form:has(input[name="title"])');
await form.locator('input[name="title"]').fill(title);
await form.locator('input[name="slug"]').fill(slug);
await form.locator('[name="shortStory"]').fill(summary);
await form
.locator('input[name="image"]')
.fill("/assets/images/EnterHubbly.png");
await form.locator('select[name="status"]').selectOption("draft");
const editor = form
.frameLocator("iframe.tox-edit-area__iframe")
.locator('body[contenteditable="true"]');
await expect(editor).toBeVisible();
await editor.fill(body);
await editor.press("End");
await expect(form.locator('textarea[name="fullStory"]')).toHaveValue(
/Salvata dal browser/,
);
submittedHtml = await form
.locator('textarea[name="fullStory"]')
.inputValue();
await form.locator('button[type="submit"]').click();
await expect(page).toHaveURL(`${baseURL}/admin/articles`);
const articles = await rows("SELECT * FROM website_articles");
expect(articles).toHaveLength(1);
expect(articles[0]).toMatchObject({
title,
slug,
short_story: summary,
status: "draft",
user_id: fixture.userId,
published_at: null,
publish_at: null,
});
expect(articles[0].full_story).toBe(submittedHtml);
articleId = String(articles[0].id);
expect(await rows("SELECT kind, actor_id FROM cms_operations")).toEqual([
expect.objectContaining({
kind: "news.create",
actor_id: fixture.userId,
}),
]);
});
await test.step("anonymous readers and the shared cache still see no published article", async () => {
const response = await reader.goto(`/news/${slug}`);
expect(response?.status()).toBeLessThan(500);
// Next can stream not-found markup with HTTP 200; assert the actual 404 screen.
await expect(reader.locator(".error-screen-code")).toHaveText("404");
await expect(publicTitle).toHaveCount(0);
const listing = await anonymous.request
.get("/api/articles")
.then((response) => response.json());
expect(listing.data).toEqual([]);
expect(listing.meta.total).toBe(0);
draftRevision = await redis.get("cms:news:revision");
expect(draftRevision).not.toBeNull();
expect(
await redis.get(`news:${draftRevision}:article:v2:slug:${slug}`),
).toBe("null");
});
await test.step("preview the persisted draft without publishing it", async () => {
await page
.locator(`a[href="/admin/articles/${articleId}"]`)
.first()
.click();
const form = page.locator('form:has(input[name="title"])');
await expect(form.locator('input[name="title"]')).toHaveValue(title);
await expect(form.locator('select[name="status"]')).toHaveValue("draft");
await expect(
form.frameLocator("iframe.tox-edit-area__iframe").locator("body"),
).toContainText(body);
await form.getByRole("button", { name: "Preview", exact: true }).click();
const preview = page.getByRole("dialog").frameLocator("iframe");
await expect(
preview.getByRole("heading", { name: title, exact: true }),
).toBeVisible();
await expect(preview.locator("body")).toContainText(summary);
await expect(preview.locator("body")).toContainText(body);
expect(await rows("SELECT status FROM website_articles")).toEqual([
{ status: "draft" },
]);
expect(
await rows("SELECT id FROM website_article_revisions"),
).toHaveLength(0);
// Preview autofocus enters its sandboxed iframe, whose Escape event cannot reach the dialog.
await page
.getByRole("dialog")
.getByRole("button", { name: "Close", exact: true })
.click();
await expect(page.getByRole("dialog")).toHaveCount(0);
});
await test.step("publish once and persist revision, audit and delivery intent", async () => {
const form = page.locator('form:has(input[name="title"])');
await form.locator('select[name="status"]').selectOption("published");
await form.locator('button[type="submit"]').click();
await expect(page).toHaveURL(`${baseURL}/admin/articles`);
const articles = await rows("SELECT * FROM website_articles");
expect(articles).toHaveLength(1);
expect(articles[0]).toMatchObject({
status: "published",
user_id: fixture.userId,
slug,
title,
});
expect(articles[0].published_at).toBeInstanceOf(Date);
const revisions = await rows(
"SELECT article_id, user_id, payload FROM website_article_revisions",
);
expect(revisions).toHaveLength(1);
expect(String(revisions[0].article_id)).toBe(articleId);
expect(Number(revisions[0].user_id)).toBe(fixture.userId);
expect(JSON.parse(revisions[0].payload)).toMatchObject({
title,
status: "draft",
});
const audit = await rows(
"SELECT user_id, `before`, `after` FROM admin_audit_log WHERE target='news'",
);
expect(audit).toHaveLength(1);
expect(audit[0].user_id).toBe(fixture.userId);
expect(JSON.parse(audit[0].before).status).toBe("draft");
expect(JSON.parse(audit[0].after).status).toBe("published");
const operations = await rows(
"SELECT kind, actor_id, result_json FROM cms_operations ORDER BY kind",
);
expect(operations.map((operation) => operation.kind)).toEqual([
"news.create",
"news.update",
]);
for (const operation of operations) {
expect(operation.actor_id).toBe(fixture.userId);
expect(JSON.parse(operation.result_json)).toMatchObject({ ok: true });
}
const effects = await rows("SELECT topic FROM cms_outbox");
expect(effects).toEqual([
{ topic: "news.refresh" },
{ topic: "news.refresh" },
]);
expect(await redis.get("cms:news:revision")).not.toBe(draftRevision);
});
await test.step("anonymous pages and API read the newly published content", async () => {
const response = await reader.reload();
expect(response?.status()).toBe(200);
await expect(publicTitle).toHaveText(title);
await expect(publicTitle).toBeVisible();
await expect(reader.locator(".article-body")).toContainText(body);
await expect(reader.locator(".error-screen-code")).toHaveCount(0);
const listing = await anonymous.request
.get("/api/articles")
.then((response) => response.json());
expect(listing.data).toHaveLength(1);
expect(listing.data[0]).toMatchObject({
id: articleId,
title,
slug,
shortStory: summary,
});
expect(listing.meta.total).toBe(1);
const revision = await redis.get("cms:news:revision");
const cached = await redis.get(
`news:${revision}:article:v2:slug:${slug}`,
);
expect(JSON.parse(cached ?? "null")).toMatchObject({
id: articleId,
title,
slug,
});
expect(
(await anonymous.cookies()).some((cookie) =>
cookie.name.includes("session-token"),
),
).toBe(false);
expect(errors).toEqual([]);
});
} finally {
if (errors.length)
await testInfo.attach("browser-errors", {
body: JSON.stringify(errors, null, 2),
contentType: "application/json",
});
await anonymous.close().catch(() => {});
await database.end();
redis.disconnect();
}
});
-38
View File
@@ -1,38 +0,0 @@
import { defineConfig, devices } from "@playwright/test";
if (!process.env.NEWS_E2E_FIXTURE || !process.env.NEWS_E2E_BASE_URL)
throw Error(
"Run this suite with pnpm test:news:real; it requires disposable services.",
);
export default defineConfig({
testDir: ".",
testMatch: "news.spec.ts",
fullyParallel: false,
workers: 1,
retries: 0,
timeout: 240_000,
expect: { timeout: 15_000 },
outputDir: "../../test-results/news-real",
reporter: [
["list"],
[
"html",
{ outputFolder: "../../playwright-report/news-real", open: "never" },
],
],
use: {
baseURL: process.env.NEWS_E2E_BASE_URL,
locale: "en-US",
ignoreHTTPSErrors: true,
trace: "retain-on-failure",
screenshot: "only-on-failure",
video: "off",
launchOptions: {
executablePath: process.env.UI_TEST_BROWSER_PATH || undefined,
},
},
projects: [
{ name: "chromium-real-news", use: { ...devices["Desktop Chrome"] } },
],
});
-387
View File
@@ -1,387 +0,0 @@
import { execFile, spawn } from "node:child_process";
import { randomBytes } from "node:crypto";
import { once } from "node:events";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { request as httpRequest } from "node:http";
import { createServer, type Server } from "node:https";
import { tmpdir } from "node:os";
import { basename, dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import mysql, { type Connection } from "mysql2/promise";
import {
GenericContainer,
Network,
type StartedNetwork,
type StartedTestContainer,
Wait,
} from "testcontainers";
import { STAFF_ID, STAFF_USERNAME, seedDatabase } from "./schema";
const root = fileURLToPath(new URL("../../", import.meta.url));
const execute = promisify(execFile);
const image = process.env.NEWS_E2E_IMAGE;
const release = process.env.NEWS_E2E_RELEASE;
if (!image)
throw Error(
"NEWS_E2E_IMAGE is required: build the candidate image before running this test. Docker is mandatory.",
);
if (!/^epicnext-cms:[a-zA-Z0-9_.-]+$/.test(image))
throw Error("NEWS_E2E_IMAGE must name a local epicnext-cms candidate tag.");
if (release && !/^[0-9a-f]{40}$/.test(release))
throw Error("NEWS_E2E_RELEASE must be a full commit SHA.");
// Never propagate checkout .env, NODE_OPTIONS, installation DB URLs or service tokens.
const inherited = (names: string[]): NodeJS.ProcessEnv => ({
NODE_ENV: "test",
...Object.fromEntries(
names.flatMap((name) =>
process.env[name] === undefined ? [] : [[name, process.env[name]]],
),
),
});
const hostEnv = inherited([
"PATH",
"Path",
"SystemRoot",
"ComSpec",
"TEMP",
"TMP",
"TMPDIR",
"HOME",
"USERPROFILE",
"LOCALAPPDATA",
]);
const dockerEnv = {
...hostEnv,
...inherited([
"DOCKER_HOST",
"DOCKER_CONTEXT",
"DOCKER_CONFIG",
"DOCKER_CERT_PATH",
"DOCKER_TLS_VERIFY",
]),
};
const secrets = Array.from({ length: 4 }, () =>
randomBytes(32).toString("hex"),
);
const [databasePassword, redisPassword, staffPassword, authSecret] = secrets;
const redact = (text: string) =>
secrets.reduce(
(value, secret) => value.replaceAll(secret, "[fixture secret]"),
text,
);
const abort = new AbortController();
const onSignal = () => abort.abort();
process.once("SIGINT", onSignal);
process.once("SIGTERM", onSignal);
let network: StartedNetwork | undefined;
let maria: StartedTestContainer | undefined;
let redis: StartedTestContainer | undefined;
let app: StartedTestContainer | undefined;
let database: Connection | undefined;
let proxy: Server | undefined;
let temporary: string | undefined;
let logs = "";
try {
// Resolve the existing image before Testcontainers; starting by immutable ID cannot pull a tag.
const inspected = await execute(
"docker",
["image", "inspect", image, "--format", "{{json .}}"],
{ env: dockerEnv, timeout: 15_000 },
);
const candidate = JSON.parse(inspected.stdout) as {
Id: string;
Config: { Labels?: Record<string, string> };
};
if (!/^sha256:[0-9a-f]{64}$/.test(candidate.Id))
throw Error("Candidate image identity is invalid");
if (
release &&
candidate.Config.Labels?.["org.opencontainers.image.revision"] !== release
)
throw Error("Candidate image revision does not match NEWS_E2E_RELEASE");
abort.signal.throwIfAborted();
temporary = await mkdtemp(join(tmpdir(), "epicnext-news-e2e-"));
// Fresh local-only TLS material never enters the repository or build artifacts.
await execute(
"openssl",
[
"req",
"-x509",
"-newkey",
"rsa:2048",
"-nodes",
"-keyout",
join(temporary, "localhost.key"),
"-out",
join(temporary, "localhost.crt"),
"-days",
"1",
"-subj",
"/CN=localhost",
"-addext",
"subjectAltName=IP:127.0.0.1,DNS:localhost",
],
{ cwd: temporary, env: hostEnv, timeout: 30_000, signal: abort.signal },
);
console.log("News browser gate: starting isolated MariaDB and Redis");
network = await new Network().start();
const services = await Promise.allSettled([
new GenericContainer("mariadb:11.4.5")
.withNetwork(network)
.withNetworkAliases("news-db")
.withEnvironment({
MARIADB_ROOT_PASSWORD: randomBytes(32).toString("hex"),
MARIADB_DATABASE: "news_e2e",
MARIADB_USER: "news_e2e",
MARIADB_PASSWORD: databasePassword,
})
.withExposedPorts(3306)
.withHealthCheck({
test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"],
interval: 1000,
timeout: 5000,
retries: 60,
startPeriod: 1000,
})
.withWaitStrategy(Wait.forHealthCheck())
.withStartupTimeout(120_000)
.start()
.then((container) => {
maria = container;
}),
new GenericContainer("redis:7.4.2-alpine")
.withNetwork(network)
.withNetworkAliases("news-redis")
.withCommand(["redis-server", "--requirepass", redisPassword])
.withExposedPorts(6379)
.withWaitStrategy(Wait.forLogMessage("Ready to accept connections"))
.withStartupTimeout(60_000)
.start()
.then((container) => {
redis = container;
}),
]);
for (const service of services)
if (service.status === "rejected") throw service.reason;
if (!maria || !redis) throw Error("Disposable services did not start");
abort.signal.throwIfAborted();
database = await mysql.createConnection({
host: maria.getHost(),
port: maria.getMappedPort(3306),
user: "news_e2e",
password: databasePassword,
database: "news_e2e",
charset: "utf8mb4",
timezone: "Z",
supportBigNumbers: true,
bigNumberStrings: true,
});
await seedDatabase(database, staffPassword);
await database.end();
database = undefined;
let upstream: URL | undefined;
let origin = "";
proxy = createServer(
{
cert: await readFile(join(temporary, "localhost.crt")),
key: await readFile(join(temporary, "localhost.key")),
},
(request, response) => {
if (!upstream || request.headers.host !== new URL(origin).host) {
response.writeHead(503);
response.end();
return;
}
// A real local TLS edge, with the same forwarded-host/proto contract as deployment.
const headers = { ...request.headers };
delete headers["cf-connecting-ip"];
delete headers["x-real-client-ip"];
headers["x-forwarded-for"] = "127.0.0.1";
headers["x-real-ip"] = "127.0.0.1";
headers["x-forwarded-host"] = new URL(origin).host;
headers["x-forwarded-proto"] = "https";
const forwarded = httpRequest(
{
hostname: upstream.hostname,
port: upstream.port,
path: request.url,
method: request.method,
headers,
},
(received) => {
response.writeHead(received.statusCode ?? 502, received.headers);
received.pipe(response);
},
);
forwarded.on("error", () => {
if (!response.headersSent) response.writeHead(502);
response.end();
});
request.on("aborted", () => forwarded.destroy());
request.pipe(forwarded);
},
);
proxy.listen(0, "127.0.0.1");
await once(proxy, "listening");
const address = proxy.address();
if (!address || typeof address === "string")
throw Error("Local TLS listener is unavailable");
origin = `https://127.0.0.1:${address.port}`;
console.log("News browser gate: starting the production candidate image");
app = await new GenericContainer(candidate.Id.slice("sha256:".length))
.withNetwork(network)
.withEnvironment({
NODE_ENV: "production",
HOSTNAME: "0.0.0.0",
PORT: "3002",
DATABASE_URL: `mysql://news_e2e:${databasePassword}@news-db:3306/news_e2e`,
REDIS_URL: `redis://:${redisPassword}@news-redis:6379/0`,
HOTEL_NAME: "News browser fixture",
AUTH_SECRET: authSecret,
APP_URL: origin,
NEXT_PUBLIC_APP_URL: origin,
AUTH_URL: origin,
RCON_HOST: "127.0.0.1",
RCON_PORT: "9",
RCON_TIMEOUT_MS: "100",
RCON_MAX_RETRIES: "1",
IMAGING_UPSTREAM_URL: "http://127.0.0.1:9",
LOG_LEVEL: "warn",
})
.withExposedPorts(3002)
.withWaitStrategy(Wait.forHttp("/api/health", 3002).forStatusCode(200))
.withStartupTimeout(120_000)
.withLogConsumer((stream) =>
stream.on("data", (chunk: Buffer) => {
logs = (logs + chunk.toString()).slice(-2_000_000);
}),
)
.start();
upstream = new URL(`http://${app.getHost()}:${app.getMappedPort(3002)}`);
abort.signal.throwIfAborted();
const health = (await fetch(new URL("/api/health", upstream), {
signal: AbortSignal.timeout(10_000),
}).then((response) => response.json())) as {
status?: string;
database?: boolean;
redis?: boolean;
};
if (
health.status !== "ok" ||
health.database !== true ||
health.redis !== true
)
throw Error("Candidate health does not confirm both disposable services");
const fixturePath = join(temporary, "fixture.json");
await writeFile(
fixturePath,
JSON.stringify({
username: STAFF_USERNAME,
userId: STAFF_ID,
password: staffPassword,
database: {
host: maria.getHost(),
port: maria.getMappedPort(3306),
user: "news_e2e",
password: databasePassword,
database: "news_e2e",
},
redis: {
host: redis.getHost(),
port: redis.getMappedPort(6379),
password: redisPassword,
},
}),
{ mode: 0o600 },
);
console.log(
"News browser gate: login, draft, preview, publish and anonymous read",
);
const child = spawn(
process.execPath,
[
resolve(root, "node_modules/@playwright/test/cli.js"),
"test",
"--config",
"e2e/news-real/playwright.config.ts",
],
{
cwd: root,
env: {
...hostEnv,
...inherited([
"DISPLAY",
"XAUTHORITY",
"PLAYWRIGHT_BROWSERS_PATH",
"UI_TEST_BROWSER_PATH",
"CI",
]),
NEWS_E2E_FIXTURE: fixturePath,
NEWS_E2E_BASE_URL: origin,
},
stdio: "inherit",
signal: abort.signal,
},
);
const [code] = (await once(child, "exit")) as [number | null];
if (code !== 0)
throw Error(`Real news browser suite failed (exit ${code ?? "signal"})`);
console.log("News browser gate passed");
} catch (error) {
console.error(
redact(
error instanceof Error ? (error.stack ?? error.message) : String(error),
),
);
process.exitCode = 1;
} finally {
// Stop only objects created by this run. Testcontainers' resource reaper also owns them.
const cleanups: Array<[string, () => Promise<unknown>]> = [
[
"TLS proxy",
async () => {
proxy?.closeAllConnections();
if (proxy)
await new Promise<void>((done) => proxy?.close(() => done()));
},
],
["candidate", async () => app?.stop({ timeout: 10_000 })],
["database connection", async () => database?.end()],
["Redis", async () => redis?.stop()],
["MariaDB", async () => maria?.stop()],
["network", async () => network?.stop()],
[
"temporary credentials",
async () => {
if (!temporary) return;
if (
dirname(resolve(temporary)) !== resolve(tmpdir()) ||
!basename(temporary).startsWith("epicnext-news-e2e-")
)
throw Error(
"Temporary credentials path escaped the fixture directory",
);
await rm(temporary, { recursive: true, force: true });
},
],
];
for (const [name, cleanup] of cleanups) {
try {
await cleanup();
} catch (error) {
console.error(`Cleanup failed for ${name}: ${redact(String(error))}`);
process.exitCode = 1;
}
}
await mkdir(resolve(root, "test-results/news-real"), { recursive: true });
await writeFile(
resolve(root, "test-results/news-real/server.log"),
redact(logs),
);
process.removeListener("SIGINT", onSignal);
process.removeListener("SIGTERM", onSignal);
}
-195
View File
@@ -1,195 +0,0 @@
import { randomBytes } from "node:crypto";
import { readFile } from "node:fs/promises";
import { is, SQL } from "drizzle-orm";
import {
getTableConfig,
MySqlDialect,
type MySqlTable,
} from "drizzle-orm/mysql-core";
import { bcrypt } from "hash-wasm";
import mysql, { type Connection } from "mysql2/promise";
import { splitSqlStatements } from "../../scripts/sql-statements";
import * as schema from "../../src/db/schema";
export const STAFF_ID = 7;
export const STAFF_USERNAME = "NewsEditor";
// Use the actual ORM definitions for the emulator tables this browser journey reads.
// CMS recovery/outbox tables below come from the shipped migrations themselves.
const tables: MySqlTable[] = [
schema.User,
schema.Ban,
schema.WebsiteSetting,
schema.WebsiteLanguages,
schema.AclRole,
schema.AclPermission,
schema.AclModelRole,
schema.AclModelPermission,
schema.WebsiteArticles,
schema.WebsiteArticleComments,
schema.WebsiteArticleReactions,
schema.WebsiteLoginLogs,
schema.AdminAuditLog,
schema.StaffActivities,
schema.WebsiteIpBlacklist,
schema.WebsiteIpWhitelist,
schema.AlertLogs,
schema.ThemeScope,
schema.ThemeScopeValue,
schema.UsersCurrency,
schema.MessengerFriendrequests,
schema.MessengerFriendships,
schema.MessengerOffline,
schema.Rooms,
schema.UsersBadges,
schema.UsersSettings,
schema.UserReferrals,
schema.WebsiteEvent,
schema.WebsiteEventType,
];
const identifier = (name: string) => `\`${name.replaceAll("`", "``")}\``;
export function fixtureStatements(): string[] {
const dialect = new MySqlDialect();
return tables.map((table) => {
const config = getTableConfig(table);
// Fail on new constraints instead of silently reducing the fixture's integrity.
if (
config.foreignKeys.length ||
config.checks.length ||
config.uniqueConstraints.length
)
throw Error(`Fixture requires explicit constraints for ${config.name}`);
const columns = config.columns.map((column) => {
let ddl = `${identifier(column.name)} ${column.getSQLType()}`;
ddl += column.notNull ? " NOT NULL" : " NULL";
if ("autoIncrement" in column && column.autoIncrement)
ddl += " AUTO_INCREMENT";
if (column.primary) ddl += " PRIMARY KEY";
if (column.isUnique) ddl += " UNIQUE";
if (column.default !== undefined) {
if (is(column.default, SQL)) {
const query = dialect.sqlToQuery(column.default);
if (query.params.length)
throw Error(
`Fixture requires parameterized default for ${config.name}.${column.name}`,
);
ddl += ` DEFAULT ${query.sql}`;
} else if (
typeof column.default === "string" ||
typeof column.default === "number" ||
typeof column.default === "boolean" ||
column.default === null
)
ddl += ` DEFAULT ${mysql.escape(column.default)}`;
else
throw Error(
`Fixture requires explicit default for ${config.name}.${column.name}`,
);
} else if (!column.notNull) ddl += " DEFAULT NULL";
return ddl;
});
for (const key of config.primaryKeys)
columns.push(
`PRIMARY KEY (${key.columns.map((column) => identifier(column.name)).join(", ")})`,
);
for (const index of config.indexes) {
if (!index.config.unique) continue;
const names = index.config.columns.map((column) => {
if (is(column, SQL))
throw Error(`Fixture requires expression index for ${config.name}`);
return identifier(column.name);
});
columns.push(
`UNIQUE KEY ${identifier(index.config.name)} (${names.join(", ")})`,
);
}
return `CREATE TABLE ${identifier(config.name)} (${columns.join(",\n")}) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`;
});
}
export async function seedDatabase(
connection: Connection,
staffPassword: string,
) {
for (const statement of fixtureStatements())
await connection.query(statement);
// Rank metadata belongs to the emulator and is queried as raw SQL by authorization.
await connection.query(
"CREATE TABLE permission_ranks (id INT PRIMARY KEY, rank_name VARCHAR(255) NOT NULL) ENGINE=InnoDB",
);
await connection.query(
"INSERT INTO permission_ranks (id, rank_name) VALUES (1, 'Member'), (7, 'Editor'), (9, 'Owner')",
);
for (const migration of [
"0026_article_editor_recovery.sql",
"0031_operations_outbox.sql",
]) {
const contents = await readFile(
new URL(`../../drizzle/migrations/${migration}`, import.meta.url),
"utf8",
);
for (const statement of splitSqlStatements(contents))
await connection.query(statement);
}
const password = await bcrypt({
password: staffPassword,
salt: randomBytes(16),
costFactor: 12,
outputType: "encoded",
});
const ownerPassword = await bcrypt({
password: randomBytes(32).toString("hex"),
salt: randomBytes(16),
costFactor: 12,
outputType: "encoded",
});
await connection.query(
"INSERT INTO users (id, username, password, rank, account_created, ip_register, ip_current, mail, mail_verified) VALUES (?, ?, ?, 7, ?, '127.0.0.1', '127.0.0.1', '[email protected]', '1'), (9, 'FixtureOwner', ?, 9, ?, '127.0.0.1', '127.0.0.1', '[email protected]', '1')",
[
STAFF_ID,
STAFF_USERNAME,
password,
Math.floor(Date.now() / 1000),
ownerPassword,
Math.floor(Date.now() / 1000),
],
);
await connection.query(
"INSERT INTO acl_roles (id, slug, title) VALUES (1, 'news_editor', 'News editor')",
);
await connection.query(
"INSERT INTO acl_model_roles (model_type, model_id, role_id) VALUES ('User', ?, 1)",
[STAFF_ID],
);
for (const [index, slug] of [
"admin.dashboard",
"admin.news.view",
"admin.news.edit",
].entries()) {
await connection.query(
"INSERT INTO acl_permissions (id, slug, title) VALUES (?, ?, ?)",
[index + 1, slug, slug],
);
await connection.query(
"INSERT INTO acl_model_permissions (model_type, model_id, permission_id) VALUES ('Role', 1, ?)",
[index + 1],
);
}
for (const [key, value] of Object.entries({
hotel_name: "News browser fixture",
captcha_provider: "none",
require_email_verification: "1",
force_staff_2fa: "0",
maintenance_enabled: "0",
abuse_guard_enabled: "0",
radio_enabled: "0",
}))
await connection.query(
"INSERT INTO website_settings (`key`, value) VALUES (?, ?)",
[key, value],
);
await connection.query(
"INSERT INTO website_languages (country_code, language) VALUES ('en', 'English')",
);
}
-27
View File
@@ -1,27 +0,0 @@
import { expect, test } from "@playwright/test";
// Read-only production checks. Content mutation tests belong to a seeded staging DB.
test("login remains usable on a narrow viewport", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 720 });
const response = await page.goto("/login");
expect(response?.ok()).toBe(true);
await expect(page.locator('input[type="password"]').first()).toBeVisible();
await expect(page.locator('button[type="submit"]').first()).toBeVisible();
expect(
await page.evaluate(
() => document.documentElement.scrollWidth <= innerWidth + 1,
),
).toBe(true);
await expect(page.locator("body")).not.toContainText("Application error");
});
test("public news is rendered without a server error", async ({ page }) => {
const response = await page.goto("/news");
expect(response?.ok()).toBe(true);
await expect(page.locator("main").first()).toBeVisible();
await expect(page.locator("body")).not.toContainText("Application error");
});
test("staff page is available", async ({ page }) => {
const response = await page.goto("/staff");
expect(response?.ok()).toBe(true);
await expect(page.locator("main").first()).toBeVisible();
});
-10
View File
@@ -1,10 +0,0 @@
# Isolated UI regression checks
Run `pnpm test:ui` after `pnpm install --frozen-lockfile` and `pnpm exec playwright install chromium`.
The fixture server bundles real CMS components with local HTTP/server-action fixtures. It does not use the database or production credentials. Production smoke tests remain in the separate `pnpm test:e2e` command.
The suite covers accessible settings switches, news editor/preview, support-table filters, import history, attachment recovery and news/event recovery. Axe checks WCAG A/AA rules. The sandboxed preview cannot execute Axe; its accessible name and keyboard exit are checked separately. Automated checks do not replace a full accessibility audit.
Visual references are committed under `__screenshots__/<platform>/<viewport>`. Normal runs compare references and must not update them. For an intentional UI change, use `pnpm test:ui:update`, inspect every changed PNG and commit only accepted references. Keep the Playwright browser version aligned with the lockfile. Linux references must be captured on the Linux runner; Windows references are not interchangeable.
Fixtures contain synthetic data only. Do not add production requests, environment secrets, ignored local documents or database access to tests. CI retains test reports and failures as the `ui-results` artifact.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

-109
View File
@@ -1,109 +0,0 @@
import { expect, test } from "@playwright/test";
const attachmentId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
const file = {
name: "fixture_chair.nitro",
mimeType: "application/octet-stream",
buffer: Buffer.from("isolated upload fixture"),
};
test.beforeEach(async ({ page }) => {
await page.goto("/admin/attachment-harness");
await page
.getByText("Attach original file and resume", { exact: true })
.click();
});
test("attachment upload and double-click resume send one retry and refresh history", async ({
page,
}) => {
let retries = 0;
await page.route("**/api/admin/studio/import-attachment", async (route) => {
expect(route.request().method()).toBe("POST");
expect(route.request().postData()).toContain('name="classname"');
expect(route.request().postData()).toContain("fixture_chair");
expect(route.request().postData()).toContain(
'filename="fixture_chair.nitro"',
);
await route.fulfill({ json: { ok: true, attachmentId } });
});
await page.route("**/api/admin/studio/import-jobs", async (route) => {
retries++;
expect(route.request().method()).toBe("PATCH");
expect(route.request().postDataJSON()).toEqual({
id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
action: "retry",
attachments: { fixture_chair: attachmentId },
});
await new Promise((resolve) => setTimeout(resolve, 150));
await route.fulfill({ json: { ok: true } });
});
await page.getByLabel("Choose the original .nitro file").setInputFiles(file);
await expect(
page.getByText("Matching original file attached", { exact: true }),
).toBeVisible();
await page
.getByRole("button", {
name: "Resume failed imports with this file",
exact: true,
})
.dblclick();
await expect(page.getByLabel("Resumed count")).toHaveText("1");
expect(retries).toBe(1);
await expect(
page.getByRole("button", {
name: "Resume failed imports with this file",
exact: true,
}),
).toHaveCount(0);
});
for (const scenario of [
{
name: "owner rejection",
status: 403,
code: "forbidden",
message: "Could not attach the file.",
},
{
name: "mismatched furniture",
status: 400,
code: "mismatchedFile",
message: "This file belongs to different furniture.",
},
{
name: "network failure",
status: 0,
code: "",
message: "Network connection failed",
},
])
test(`attachment ${scenario.name} shows readable error without enabling resume`, async ({
page,
}) => {
let retries = 0;
await page.route("**/api/admin/studio/import-jobs", async (route) => {
retries++;
await route.fulfill({ json: { ok: true } });
});
await page.route("**/api/admin/studio/import-attachment", (route) =>
scenario.status
? route.fulfill({
status: scenario.status,
json: { ok: false, code: scenario.code },
})
: route.abort("failed"),
);
await page
.getByLabel("Choose the original .nitro file")
.setInputFiles(file);
await expect(page.getByRole("alert")).toContainText(scenario.message);
await expect(
page.getByRole("button", {
name: "Resume failed imports with this file",
exact: true,
}),
).toHaveCount(0);
await expect(page.getByLabel("Resumed count")).toHaveText("0");
expect(retries).toBe(0);
});
-143
View File
@@ -1,143 +0,0 @@
import { expect, type Page, test } from "@playwright/test";
/**
* The guarantee this file exists to guard: an import that finishes outside this
* page — the job worker, another tab, another browser — puts the new categories
* on screen without a reload. Every earlier test in this suite asserted only
* that no page errors were thrown, so a regression back to "refresh the page to
* see it" would have gone unnoticed.
*/
function node(id: number, caption: string, itemCount = 0) {
return {
id,
caption,
parentId: -1,
depth: 0,
orderNum: id,
enabled: "1",
visible: "1",
iconImage: 0,
iconColor: 0,
pageLayout: "default_3x3",
childCount: 0,
itemCount,
};
}
/** The catalog as the server would report it; specs move it forward mid-test. */
const catalog = {
revision: "rev-1",
pages: [node(1, "Root")],
treeStatus: 200,
};
async function mockStudio(page: Page) {
await page.route("**/api/**", async (route) => {
const url = new URL(route.request().url());
if (url.pathname === "/api/admin/catalog/revision")
return route.fulfill({ json: { ok: true, revision: catalog.revision } });
if (
url.pathname === "/api/admin/catalog/tree" &&
url.searchParams.get("mode") === "full"
)
return route.fulfill({
status: catalog.treeStatus,
json: {
ok: catalog.treeStatus === 200,
pages: catalog.pages,
totals: null,
revision: catalog.revision,
},
});
if (url.pathname.endsWith("/inspect"))
return route.fulfill({ json: { items: [] } });
if (url.pathname.endsWith("/source-assets"))
return route.fulfill({ json: { items: [] } });
if (url.pathname.endsWith("/furni"))
return route.fulfill({
json: url.searchParams.has("action")
? { totalInDb: 0, inCatalog: 0, notInCatalog: 0, missingNitro: 0 }
: {
items: [],
meta: {
currentPage: 1,
lastPage: 1,
total: 0,
perPage: 100,
},
},
});
if (url.pathname.endsWith("/clone"))
return route.fulfill({ json: { sources: [] } });
if (url.pathname.endsWith("/import-jobs"))
return route.fulfill({ json: { ok: true, jobs: [], nextCursor: null } });
return route.fulfill({
status: 404,
json: { error: "Unknown fixture endpoint" },
});
});
}
test.beforeEach(() => {
catalog.revision = "rev-1";
catalog.pages = [node(1, "Root")];
catalog.treeStatus = 200;
});
test("a write announced by another tab lands in the mounted categories", async ({
page,
}, testInfo) => {
test.skip(
(testInfo.project.use.viewport?.width ?? 0) < 1024,
"the category rail is collapsed on narrow viewports",
);
await mockStudio(page);
const navigations: string[] = [];
page.on("framenavigated", (frame) => {
if (frame === page.mainFrame()) navigations.push(frame.url());
});
await page.goto("/admin/studio-harness");
await expect(page.getByRole("button", { name: /^Root/ })).toBeVisible();
const navigationsAfterLoad = navigations.length;
// An import finished elsewhere: the catalog moved on, so the tree route now
// answers with the imported category.
catalog.revision = "rev-2";
catalog.pages = [...catalog.pages, node(2, "Imported Furniture", 3)];
await page.evaluate((revision) => {
const channel = new BroadcastChannel("atom-cms-catalog");
channel.postMessage({ revision });
channel.close();
}, catalog.revision);
await expect(
page.getByRole("button", { name: /Imported Furniture/ }),
).toBeVisible();
// The page was never navigated or reloaded: the tree updated in place.
expect(navigations).toHaveLength(navigationsAfterLoad);
});
test("a failed refresh keeps the categories and says it is stale", async ({
page,
}, testInfo) => {
test.skip(
(testInfo.project.use.viewport?.width ?? 0) < 1024,
"the category rail is collapsed on narrow viewports",
);
await mockStudio(page);
await page.goto("/admin/studio-harness");
await expect(page.getByRole("button", { name: /^Root/ })).toBeVisible();
catalog.treeStatus = 500;
catalog.revision = "rev-2";
await page.evaluate((revision) => {
const channel = new BroadcastChannel("atom-cms-catalog");
channel.postMessage({ revision });
channel.close();
}, catalog.revision);
await expect(page.getByRole("button", { name: "Retry" })).toBeVisible();
await expect(page.getByRole("button", { name: /^Root/ })).toBeVisible();
});
Loaded 100 of 1603 files, more files were not shown because too many files have changed in this diff. Show more