Compare commits
99 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c01d8d8d2e | |||
| bf9bd76278 | |||
| 0fe5792a7d | |||
| 3f7364be8e | |||
| 2d0e6ab2dc | |||
| cc49f6997a | |||
| fecc18cbc8 | |||
| 7f27e6771f | |||
| 4e99897313 | |||
| ccab9024d4 | |||
| 11f9f584de | |||
| 3b88036fda | |||
| 0c73bf2cdc | |||
| 2c7b5dfd02 | |||
| 5d5db4e766 | |||
| e5dccf1664 | |||
| bfafecedc7 | |||
| 2c5a094c5c | |||
| 2462ba6897 | |||
| 90275f88e9 | |||
| 34a7b1c013 | |||
| 7419c68337 | |||
| fc99e2b233 | |||
| 7974b9c6d7 | |||
| 60cbda5b22 | |||
| a27d19b4d1 | |||
| d68d84e5c8 | |||
| 6891769124 | |||
| b32ba1ed6b | |||
| f99357460f | |||
| 90b589a88e | |||
| 1ad8ad5b68 | |||
| 962f1d9586 | |||
| a7885846ac | |||
| d868aac703 | |||
| 577b7fa6ae | |||
| a27c705e39 | |||
| b0e9145bba | |||
| 39696d42fe | |||
| 50f5ca1d5b | |||
| 11b6490e4c | |||
| 1cff576439 | |||
| 8978acdb49 | |||
| 0d8123ed4a | |||
| db1d28a75b | |||
| 64bcd0ab9f | |||
| 1d48f59fe1 | |||
| e37d1fac58 | |||
| 9ee3ff45d0 | |||
| 5453152f1c | |||
| b416baec5c | |||
| 38ddd70c12 | |||
| b00a16159e | |||
| dcfcb67f9b | |||
| cde0b465a9 | |||
| 28f69e4bf3 | |||
| 1cf82d81a7 | |||
| ae98e7ad74 | |||
| caa9fe5d56 | |||
| c6e61f64ba | |||
| 3ec0451cbb | |||
| edac463ec3 | |||
| 2d3537f61c | |||
| 6025b3194d | |||
| 8713ab7f60 | |||
| 8994901e4a | |||
| b86669f1e1 | |||
| 80296282e8 | |||
| 5551c89bda | |||
| dbde67c0fa | |||
| 067e460a4d | |||
| 3678193ae2 | |||
| 74eacbc78f | |||
| 37bf894412 | |||
| 506b5c3dc4 | |||
| ab6db37326 | |||
| eb2ce290a7 | |||
| 8a4c1a7c0a | |||
| 4d3836fb2e | |||
| 75499992eb | |||
| 62643f241b | |||
| 64f606152f | |||
| e2a698e892 | |||
| d1d71dba25 | |||
| bb81fa5f4b | |||
| 03e19893b3 | |||
| 279314e4b7 | |||
| 730912a3f4 | |||
| ff9fb64e75 | |||
| 9cbbe74051 | |||
| 2e1c71c1ab | |||
| f6ca713a6e | |||
| 197cd8e1e0 | |||
| 681b440381 | |||
| 3daeac9e53 | |||
| 7febba2d9c | |||
| 0a3a53763c | |||
| 85a60a2dc7 | |||
| e74e73a3a0 |
@@ -10,14 +10,6 @@ NODE_ENV=production
|
||||
# Generate one with: openssl rand -base64 64
|
||||
#JWT_SECRET=your_very_long_random_jwt_secret_here
|
||||
|
||||
# OIDC SSO for admins (#798) — configured in the admin UI; only these two
|
||||
# values live in the environment:
|
||||
# Key encrypting the OIDC client secret at rest (defaults to JWT_SECRET).
|
||||
#OIDC_ENCRYPTION_KEY=
|
||||
# Break-glass: 'true' re-enables local password login even while the SSO
|
||||
# settings disable it (recovery when the IdP is down or misconfigured).
|
||||
#OIDC_BREAK_GLASS=false
|
||||
|
||||
# Auth cookie Secure flag
|
||||
# unset - default: follows NODE_ENV (production=true, dev=false)
|
||||
# true - always set Secure (HTTPS-only cookies; breaks plain-HTTP access)
|
||||
@@ -115,11 +107,6 @@ VITE_API_URL=/api
|
||||
# DB_PORT=5432
|
||||
# REDIS_PORT=6379
|
||||
|
||||
# File watcher (watch-folder auto-import, local storage only)
|
||||
# Max photos processed in parallel — raise on hosts with memory headroom,
|
||||
# lower to 1 on very small hosts. Default: 2
|
||||
# FILE_WATCHER_CONCURRENCY=2
|
||||
|
||||
# Release Channel
|
||||
# Options: 'stable' (default), 'beta', or specific version like 'v2.3.0'
|
||||
# 'stable' uses the :stable tag (same as :latest on main)
|
||||
|
||||
@@ -95,15 +95,6 @@ jobs:
|
||||
repo_lc="${GITHUB_REPOSITORY,,}"
|
||||
echo "BACKEND_IMAGE_NAME=${repo_lc}/backend" >> "$GITHUB_ENV"
|
||||
echo "FRONTEND_IMAGE_NAME=${repo_lc}/frontend" >> "$GITHUB_ENV"
|
||||
# Mirror manifests to Docker Hub (picpeak/{backend,frontend}) only on the
|
||||
# canonical org repo, where the DOCKERHUB_* secrets live. Forks (and any
|
||||
# other owner) fall back to GHCR-only — the Docker Hub image line and login
|
||||
# are gated on this flag so their builds keep working unchanged.
|
||||
if [[ "$GITHUB_REPOSITORY" == "PicPeak/picpeak" ]]; then
|
||||
echo "DOCKERHUB_ENABLED=true" >> "$GITHUB_ENV"
|
||||
else
|
||||
echo "DOCKERHUB_ENABLED=false" >> "$GITHUB_ENV"
|
||||
fi
|
||||
|
||||
- name: Prepare platform pair
|
||||
run: |
|
||||
@@ -242,15 +233,6 @@ jobs:
|
||||
repo_lc="${GITHUB_REPOSITORY,,}"
|
||||
echo "BACKEND_IMAGE_NAME=${repo_lc}/backend" >> "$GITHUB_ENV"
|
||||
echo "FRONTEND_IMAGE_NAME=${repo_lc}/frontend" >> "$GITHUB_ENV"
|
||||
# Mirror manifests to Docker Hub (picpeak/{backend,frontend}) only on the
|
||||
# canonical org repo, where the DOCKERHUB_* secrets live. Forks (and any
|
||||
# other owner) fall back to GHCR-only — the Docker Hub image line and login
|
||||
# are gated on this flag so their builds keep working unchanged.
|
||||
if [[ "$GITHUB_REPOSITORY" == "PicPeak/picpeak" ]]; then
|
||||
echo "DOCKERHUB_ENABLED=true" >> "$GITHUB_ENV"
|
||||
else
|
||||
echo "DOCKERHUB_ENABLED=false" >> "$GITHUB_ENV"
|
||||
fi
|
||||
|
||||
- name: Download digest artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
@@ -284,24 +266,11 @@ jobs:
|
||||
echo "is_prerelease=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
if: env.DOCKERHUB_ENABLED == 'true'
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: docker.io
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata for Backend
|
||||
id: meta-backend
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
# GHCR always; Docker Hub (picpeak/backend) added on the canonical repo so
|
||||
# the same tag scheme is mirrored to both registries. metadata-action drops
|
||||
# the blank second line on forks → GHCR-only there.
|
||||
images: |
|
||||
${{ env.REGISTRY }}/${{ env.BACKEND_IMAGE_NAME }}
|
||||
${{ env.DOCKERHUB_ENABLED == 'true' && 'docker.io/picpeak/backend' || '' }}
|
||||
images: ${{ env.REGISTRY }}/${{ env.BACKEND_IMAGE_NAME }}
|
||||
labels: |
|
||||
org.opencontainers.image.title=PicPeak Backend
|
||||
org.opencontainers.image.description=PicPeak photo sharing platform backend service
|
||||
@@ -313,10 +282,6 @@ jobs:
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}},enable=${{ steps.context.outputs.is_prerelease == 'false' }}
|
||||
type=semver,pattern={{major}},enable=${{ steps.context.outputs.is_prerelease == 'false' }}
|
||||
# #668/#783: publish the git-tag name verbatim (v3.45.0 / v3.84.0-beta.0)
|
||||
# so users can pin the same string as the GitHub release. metadata-action's
|
||||
# `pattern=v{{version}}` silently dropped it on prereleases, so use type=ref.
|
||||
type=ref,event=tag
|
||||
type=sha,format=short
|
||||
# `:latest` + `:stable` follow the stable channel (the `stable` branch +
|
||||
# stable release tags). The default branch is now `main` (active dev),
|
||||
@@ -333,15 +298,10 @@ jobs:
|
||||
docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
|
||||
$(printf "${{ env.REGISTRY }}/${{ env.BACKEND_IMAGE_NAME }}@sha256:%s " *)
|
||||
|
||||
- name: Inspect manifest (GHCR)
|
||||
- name: Inspect manifest
|
||||
run: |
|
||||
docker buildx imagetools inspect ${{ env.REGISTRY }}/${{ env.BACKEND_IMAGE_NAME }}:${{ steps.meta-backend.outputs.version }}
|
||||
|
||||
- name: Inspect manifest (Docker Hub)
|
||||
if: env.DOCKERHUB_ENABLED == 'true'
|
||||
run: |
|
||||
docker buildx imagetools inspect docker.io/picpeak/backend:${{ steps.meta-backend.outputs.version }}
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Frontend: per-arch build, then merge into a multi-arch manifest
|
||||
# -----------------------------------------------------------------------------
|
||||
@@ -371,15 +331,6 @@ jobs:
|
||||
repo_lc="${GITHUB_REPOSITORY,,}"
|
||||
echo "BACKEND_IMAGE_NAME=${repo_lc}/backend" >> "$GITHUB_ENV"
|
||||
echo "FRONTEND_IMAGE_NAME=${repo_lc}/frontend" >> "$GITHUB_ENV"
|
||||
# Mirror manifests to Docker Hub (picpeak/{backend,frontend}) only on the
|
||||
# canonical org repo, where the DOCKERHUB_* secrets live. Forks (and any
|
||||
# other owner) fall back to GHCR-only — the Docker Hub image line and login
|
||||
# are gated on this flag so their builds keep working unchanged.
|
||||
if [[ "$GITHUB_REPOSITORY" == "PicPeak/picpeak" ]]; then
|
||||
echo "DOCKERHUB_ENABLED=true" >> "$GITHUB_ENV"
|
||||
else
|
||||
echo "DOCKERHUB_ENABLED=false" >> "$GITHUB_ENV"
|
||||
fi
|
||||
|
||||
- name: Prepare platform pair
|
||||
run: |
|
||||
@@ -499,15 +450,6 @@ jobs:
|
||||
repo_lc="${GITHUB_REPOSITORY,,}"
|
||||
echo "BACKEND_IMAGE_NAME=${repo_lc}/backend" >> "$GITHUB_ENV"
|
||||
echo "FRONTEND_IMAGE_NAME=${repo_lc}/frontend" >> "$GITHUB_ENV"
|
||||
# Mirror manifests to Docker Hub (picpeak/{backend,frontend}) only on the
|
||||
# canonical org repo, where the DOCKERHUB_* secrets live. Forks (and any
|
||||
# other owner) fall back to GHCR-only — the Docker Hub image line and login
|
||||
# are gated on this flag so their builds keep working unchanged.
|
||||
if [[ "$GITHUB_REPOSITORY" == "PicPeak/picpeak" ]]; then
|
||||
echo "DOCKERHUB_ENABLED=true" >> "$GITHUB_ENV"
|
||||
else
|
||||
echo "DOCKERHUB_ENABLED=false" >> "$GITHUB_ENV"
|
||||
fi
|
||||
|
||||
- name: Download digest artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
@@ -541,24 +483,11 @@ jobs:
|
||||
echo "is_prerelease=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
if: env.DOCKERHUB_ENABLED == 'true'
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: docker.io
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata for Frontend
|
||||
id: meta-frontend
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
# GHCR always; Docker Hub (picpeak/frontend) added on the canonical repo so
|
||||
# the same tag scheme is mirrored to both registries. metadata-action drops
|
||||
# the blank second line on forks → GHCR-only there.
|
||||
images: |
|
||||
${{ env.REGISTRY }}/${{ env.FRONTEND_IMAGE_NAME }}
|
||||
${{ env.DOCKERHUB_ENABLED == 'true' && 'docker.io/picpeak/frontend' || '' }}
|
||||
images: ${{ env.REGISTRY }}/${{ env.FRONTEND_IMAGE_NAME }}
|
||||
labels: |
|
||||
org.opencontainers.image.title=PicPeak Frontend
|
||||
org.opencontainers.image.description=PicPeak photo sharing platform frontend application
|
||||
@@ -570,10 +499,6 @@ jobs:
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}},enable=${{ steps.context.outputs.is_prerelease == 'false' }}
|
||||
type=semver,pattern={{major}},enable=${{ steps.context.outputs.is_prerelease == 'false' }}
|
||||
# #668/#783: publish the git-tag name verbatim (v3.45.0 / v3.84.0-beta.0)
|
||||
# so users can pin the same string as the GitHub release. metadata-action's
|
||||
# `pattern=v{{version}}` silently dropped it on prereleases, so use type=ref.
|
||||
type=ref,event=tag
|
||||
type=sha,format=short
|
||||
# `:latest` + `:stable` follow the stable channel (the `stable` branch +
|
||||
# stable release tags). The default branch is now `main` (active dev),
|
||||
@@ -590,15 +515,10 @@ jobs:
|
||||
docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
|
||||
$(printf "${{ env.REGISTRY }}/${{ env.FRONTEND_IMAGE_NAME }}@sha256:%s " *)
|
||||
|
||||
- name: Inspect manifest (GHCR)
|
||||
- name: Inspect manifest
|
||||
run: |
|
||||
docker buildx imagetools inspect ${{ env.REGISTRY }}/${{ env.FRONTEND_IMAGE_NAME }}:${{ steps.meta-frontend.outputs.version }}
|
||||
|
||||
- name: Inspect manifest (Docker Hub)
|
||||
if: env.DOCKERHUB_ENABLED == 'true'
|
||||
run: |
|
||||
docker buildx imagetools inspect docker.io/picpeak/frontend:${{ steps.meta-frontend.outputs.version }}
|
||||
|
||||
summary:
|
||||
needs: [build-backend, merge-backend, build-frontend, merge-frontend]
|
||||
if: always()
|
||||
@@ -612,15 +532,6 @@ jobs:
|
||||
repo_lc="${GITHUB_REPOSITORY,,}"
|
||||
echo "BACKEND_IMAGE_NAME=${repo_lc}/backend" >> "$GITHUB_ENV"
|
||||
echo "FRONTEND_IMAGE_NAME=${repo_lc}/frontend" >> "$GITHUB_ENV"
|
||||
# Mirror manifests to Docker Hub (picpeak/{backend,frontend}) only on the
|
||||
# canonical org repo, where the DOCKERHUB_* secrets live. Forks (and any
|
||||
# other owner) fall back to GHCR-only — the Docker Hub image line and login
|
||||
# are gated on this flag so their builds keep working unchanged.
|
||||
if [[ "$GITHUB_REPOSITORY" == "PicPeak/picpeak" ]]; then
|
||||
echo "DOCKERHUB_ENABLED=true" >> "$GITHUB_ENV"
|
||||
else
|
||||
echo "DOCKERHUB_ENABLED=false" >> "$GITHUB_ENV"
|
||||
fi
|
||||
|
||||
- name: Build Summary
|
||||
run: |
|
||||
@@ -659,10 +570,6 @@ jobs:
|
||||
echo "### 📦 Images" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Backend: \`${{ env.REGISTRY }}/${{ env.BACKEND_IMAGE_NAME }}\`" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Frontend: \`${{ env.REGISTRY }}/${{ env.FRONTEND_IMAGE_NAME }}\`" >> $GITHUB_STEP_SUMMARY
|
||||
if [[ "$DOCKERHUB_ENABLED" == "true" ]]; then
|
||||
echo "- Backend (Docker Hub): \`docker.io/picpeak/backend\`" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Frontend (Docker Hub): \`docker.io/picpeak/frontend\`" >> $GITHUB_STEP_SUMMARY
|
||||
fi
|
||||
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "### 🏗️ Architectures" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
@@ -30,29 +30,6 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
|
||||
# The .picpeak restore suites gate their real-Postgres cases behind
|
||||
# PICPEAK_PG_TEST_URL and `describe.skip` themselves out when it is
|
||||
# unset — so until now they never ran here. That hid the half that
|
||||
# matters: sequence resync, operator/role preservation across a
|
||||
# cross-instance restore, and (with #1041) whether a SQLite-shaped
|
||||
# row actually lands in Postgres with the right STORED VALUES rather
|
||||
# than merely not throwing. Everything else in the suite still runs
|
||||
# on SQLite; this service only un-gates those cases.
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:15-alpine
|
||||
env:
|
||||
POSTGRES_USER: picpeak
|
||||
POSTGRES_PASSWORD: testpass
|
||||
POSTGRES_DB: picpeak_test
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U picpeak -d picpeak_test"
|
||||
--health-interval 2s
|
||||
--health-timeout 2s
|
||||
--health-retries 30
|
||||
ports:
|
||||
- 5432:5432
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
@@ -75,9 +52,6 @@ jobs:
|
||||
# The S3 path itself is covered separately by the integration
|
||||
# suite when MinIO is provisioned.
|
||||
SKIP_S3_TESTS: 'true'
|
||||
# Un-gates the real-Postgres cases in the .picpeak restore suites
|
||||
# (see the `services:` note above). Absent it they silently skip.
|
||||
PICPEAK_PG_TEST_URL: 'postgres://picpeak:testpass@127.0.0.1:5432/picpeak_test'
|
||||
run: |
|
||||
# Excluded suites — fail on upstream/beta too, tracked
|
||||
# separately as test-infra debt:
|
||||
|
||||
+2
-3
@@ -130,6 +130,5 @@ docker-compose.dev.yml
|
||||
# New layout development files
|
||||
new-layouts/
|
||||
|
||||
# Backend runtime storage (generated media, previews, thumbnails,
|
||||
# CRM/accounting documents) — never commit
|
||||
backend/storage/
|
||||
# Generated CRM/accounting documents (runtime) — never commit
|
||||
backend/storage/business-docs/
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "3.105.1-beta.0"
|
||||
".": "3.83.0-beta.0"
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
{".":"3.44.0"}
|
||||
{".":"3.45.14"}
|
||||
|
||||
+932
-1587
File diff suppressed because it is too large
Load Diff
@@ -1,48 +1,90 @@
|
||||
# 📸 PicPeak - Open Source Photo Sharing for Events
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **PicPeak has moved to its own GitHub organization.**
|
||||
>
|
||||
> - **Docker images** are now published at `ghcr.io/picpeak/picpeak/{backend,frontend}`. The old path (`ghcr.io/the-luap/picpeak/...`) is no longer served — update your `docker-compose.yml`.
|
||||
> - **Branches**: active development is now on `main` (was `beta`); the curated stable channel is now `stable` (was `main`). Existing PRs and clones auto-redirect via GitHub.
|
||||
>
|
||||
> See **[`docs/migration-to-org.md`](docs/migration-to-org.md)** for the one-line `docker-compose.yml` edit and full details.
|
||||
|
||||
<div align="center">
|
||||
<img src="docs/picpeak-logo.png" alt="PicPeak Logo" width="300" />
|
||||
|
||||
# 📸 PicPeak
|
||||
|
||||
**Open-source, self-hosted photo sharing for events.**
|
||||
|
||||
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
[](https://www.docker.com/)
|
||||
[](https://nodejs.org/)
|
||||
[](https://reactjs.org/)
|
||||
[](https://buymeacoffee.com/theluap)
|
||||
|
||||
[Homepage](https://www.picpeak.app) · [Live Demo](https://demo.picpeak.app) · [Documentation](https://docs.picpeak.app) · [Support ☕](https://buymeacoffee.com/theluap)
|
||||
[Homepage](https://www.picpeak.app) · [Live Demo](https://demo.picpeak.app) · [Documentation](https://docs.picpeak.app) · [Support the project ☕](https://buymeacoffee.com/theluap)
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
**PicPeak** is a powerful, self-hosted open-source alternative to commercial photo-sharing platforms like PicDrop.com and Scrapbook.de. Built for photographers and event organizers, it makes it simple to share beautiful, time-limited photo galleries with clients while keeping full control over your data and branding.
|
||||
**PicPeak** is a powerful, self-hosted open-source alternative to commercial photo-sharing platforms like PicDrop.com and Scrapbook.de. Designed specifically for photographers and event organizers, PicPeak makes it simple to share beautiful, time-limited photo galleries with clients while maintaining full control over your data and branding.
|
||||
|
||||

|
||||
|
||||
> [!IMPORTANT]
|
||||
> **PicPeak has moved to its own GitHub organization.** Docker images are now at `ghcr.io/picpeak/picpeak/{backend,frontend}` and active development is on `main`. The old `ghcr.io/the-luap/...` path still responds but its tags are **frozen** at 2026-05-27 — if updates never arrive, check your image path first. See **[`docs/migration-to-org.md`](docs/migration-to-org.md)** for the one-line `docker-compose.yml` edit.
|
||||
|
||||
## Contents
|
||||
|
||||
- [Live Demo](#-live-demo)
|
||||
- [Quick Start](#-quick-start)
|
||||
- [Why PicPeak?](#-why-picpeak)
|
||||
- [Features](#-features)
|
||||
- [Documentation](#-documentation)
|
||||
- [Comparison](#-comparison-with-alternatives)
|
||||
- [Tech Stack](#️-tech-stack)
|
||||
- [Contributing & Support](#-contributing)
|
||||
- [License](#-license)
|
||||
|
||||
## 🎮 Live Demo
|
||||
|
||||
Try PicPeak without installing anything — [demo.picpeak.app](https://demo.picpeak.app) · [admin panel](https://demo.picpeak.app/admin)
|
||||
Try PicPeak without installing anything:
|
||||
|
||||
| Email | Password |
|
||||
| | |
|
||||
|---|---|
|
||||
| `demo@picpeak.app` | `Demo2026!` |
|
||||
| **Demo URL** | [demo.picpeak.app](https://demo.picpeak.app) |
|
||||
| **Admin Panel** | [demo.picpeak.app/admin](https://demo.picpeak.app/admin) |
|
||||
| **Email** | `demo@picpeak.app` |
|
||||
| **Password** | `Demo2026!` |
|
||||
|
||||
> The demo resets periodically. Uploaded content may be removed without notice.
|
||||
|
||||
## 🌟 Why Choose PicPeak?
|
||||
|
||||
Unlike expensive SaaS solutions, PicPeak gives you:
|
||||
|
||||
- **💰 No Monthly Fees** - One-time setup, unlimited galleries
|
||||
- **🔒 Complete Data Control** - Your photos stay on your server
|
||||
- **🎨 White-Label Ready** - Full branding customization
|
||||
- **📱 Mobile-First Design** - Beautiful on all devices
|
||||
- **🚀 Lightning Fast** - Optimized performance and caching
|
||||
- **🌍 Multi-Language** - Built-in i18n support (EN, DE)
|
||||
|
||||
## ✨ Key Features
|
||||
|
||||
### For Photographers
|
||||
- 📁 **Drag & Drop Upload** - Simply drop photos into folders
|
||||
- 🔗 **External Media (Reference Mode)** - Browse and import from a read‑only external folder library without copying originals
|
||||
- ⏰ **Auto-Expiring Galleries** - Set expiration dates (default: 30 days)
|
||||
- 🔐 **Password Protection** - Secure client galleries
|
||||
- 📧 **Automated Emails** - Creation confirmations and expiration warnings
|
||||
- 📊 **Analytics Dashboard** - Track views, downloads, and engagement
|
||||
- 📽️ **Live Slideshow** - A separate fullscreen "Diashow" link per event for projectors at live events — auto-picks-up new uploads while it runs, with transitions, a logo watermark, and image-fit/colour options ([guide](docs/live-slideshow.md))
|
||||
- 🎨 **Custom Themes** - Match your brand perfectly
|
||||
- 🌐 **Public Landing Page** - Publish a curated marketing page when guests visit your root URL
|
||||
|
||||
### For Clients
|
||||
- 🖼️ **Beautiful Galleries** - Clean, modern interface
|
||||
- 📱 **Mobile Optimized** - Swipe through photos on any device
|
||||
- ⬇️ **Bulk Downloads** - Download all photos with one click
|
||||
- 🔍 **Smart Search** - Find photos quickly
|
||||
- 📤 **Guest Uploads** - Optional client photo uploads
|
||||
- 🛡️ **Download Protection** - Advanced image protection with watermarking and right-click prevention
|
||||
|
||||
### Technical Excellence
|
||||
- 🐳 **Docker Ready** - Deploy in minutes
|
||||
- 🔄 **Auto-Processing** - Automatic thumbnail generation
|
||||
- 🗂️ **Reference Library Support** - Point PicPeak at `EXTERNAL_MEDIA_ROOT` to reference existing originals, index quickly, and generate thumbnails on demand
|
||||
- 💾 **Smart Storage** - Automatic archiving of expired galleries
|
||||
- 🛡️ **Security First** - JWT auth, rate limiting, CORS protection
|
||||
- 📈 **Scalable** - From small studios to large agencies
|
||||
|
||||
### For Studios — CRM & Accounting (Beta · off by default)
|
||||
- 📝 **Quotes → Contracts → Invoices** - One deal lineage; cancel-and-reissue (Storno) keeps issued invoices immutable
|
||||
- ⏱️ **Hours Logging & Calendar** - Per-customer time tracking; admin calendar of events, logged hours, and pending quotes/contracts
|
||||
- 🧾 **Inbound Supplier Invoices & Expenses** - Capture received invoices (upload/camera, rasterised server-side), categorise, and re-bill costs to clients
|
||||
- 📊 **Tax Report & Accountant Export** - Period-scoped income/cost report with VAT breakdown; PDF/CSV plus a Treuhänder/Banana (Swiss/LI) journal export, scopable to income-only or cost-only
|
||||
- 🌍 **VAT & Multi-currency** - Single VAT-code registry snapshotted onto each document; data-driven per-country rates
|
||||
- ⚠️ **Verify locally** - Feature-flagged off by default. Seeded contracts, QR/IBAN and tax defaults are **examples only** — review your own legal **and tax** regulations first (see disclaimers below)
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
Get PicPeak running in under 5 minutes:
|
||||
@@ -54,8 +96,8 @@ cd picpeak
|
||||
|
||||
# Copy the environment template — the defaults work out of the box.
|
||||
# Machine secrets (JWT, DB, Redis) are auto-generated on first run, and the
|
||||
# admin account is created in the browser. Edit .env only to customise
|
||||
# (domain, SMTP, storage paths, …) — nothing is required.
|
||||
# admin account is created in the browser (see below). Edit .env only to
|
||||
# customise (domain, SMTP, storage paths, …) — nothing is required.
|
||||
cp .env.example .env
|
||||
|
||||
# Start with Docker Compose
|
||||
@@ -64,61 +106,293 @@ docker compose up -d
|
||||
# Access at http://localhost:3000
|
||||
```
|
||||
|
||||
On first start, open **http://localhost:3000/admin** and follow the in-browser setup to create your admin account. Full details — the one-time setup token, Docker file permissions, and ARM64 notes — are in **[First-run setup](https://docs.picpeak.app/getting-started/first-login)**.
|
||||
### First run — create your admin account
|
||||
|
||||
> **Updating / release channels:** set `PICPEAK_CHANNEL` (`stable` default, or `beta`) in `.env`, then `docker compose pull && docker compose up -d`. See [RELEASING.md](RELEASING.md) for the promotion cadence.
|
||||
On first start with no `ADMIN_PASSWORD` set, PicPeak has **no admin account yet** and greets you with an in-browser setup screen — no credentials in `.env`:
|
||||
|
||||
## 🌟 Why PicPeak?
|
||||
1. Open **http://localhost:3000/admin** — you'll be redirected to `/setup`.
|
||||
2. Read the **one-time setup token** from the 0600 file the backend writes it to
|
||||
(it is deliberately *not* printed to the logs — that would leave a live
|
||||
bootstrap credential in `docker logs`):
|
||||
```bash
|
||||
docker compose exec backend cat /app/data/SETUP_TOKEN
|
||||
```
|
||||
It is bind-mounted, so `sudo cat data/SETUP_TOKEN` on the host works too. Only
|
||||
if that file could not be written does the backend fall back to logging the
|
||||
token (`docker compose logs backend | grep -i "setup token"`).
|
||||
3. Paste the token, set your admin **email + password**, and you're in. The token is single-use, and the setup screen closes permanently once an admin exists.
|
||||
|
||||
Unlike expensive SaaS solutions, PicPeak gives you:
|
||||
> Prefer the old behaviour? Set `ADMIN_PASSWORD` in `.env` and PicPeak auto-creates the admin on first boot instead (credentials written to `data/ADMIN_CREDENTIALS.txt`).
|
||||
|
||||
- **💰 No Monthly Fees** — one-time setup, unlimited galleries
|
||||
- **🔒 Complete Data Control** — your photos stay on your server
|
||||
- **🎨 White-Label Ready** — full branding customization
|
||||
- **📱 Mobile-First Design** — beautiful on all devices
|
||||
- **🌍 Multi-Language** — built-in i18n (EN, DE)
|
||||
Note on Docker file permissions
|
||||
- The backend container starts as root, chowns bind-mounted host directories (`./storage`, `./data`, `./logs`) to UID 1001 (`nodejs`), then drops privileges via `su-exec` before running the app. No host-side setup needed for fresh installs.
|
||||
- If you pin `user:` in a compose override (e.g. to map a specific host UID), the self-chown is skipped and you must pre-chown the host directories to that UID — see [docs.picpeak.app/deployment/docker#permissions](https://docs.picpeak.app/deployment/docker#permissions).
|
||||
|
||||
## ✨ Features
|
||||
**ARM64 (aarch64) systems:** Pre-built images include native `linux/arm64`, no platform flags or emulation needed. If you're on an older image tag that's still amd64-only, see [docker-compose.amd64.override.yml](docker-compose.amd64.override.yml) for a transitional fallback.
|
||||
|
||||
**For photographers** — drag & drop upload, auto-expiring & password-protected galleries, automated emails, an analytics dashboard, custom themes, a public landing page, and a [Live Slideshow](https://docs.picpeak.app/features/live-slideshow) projector view that auto-picks-up new uploads during live events.
|
||||
## 🔄 Release Channels
|
||||
|
||||
**For clients** — clean mobile-optimized galleries, one-click bulk downloads, smart search, optional guest uploads, and download protection (watermarking + right-click prevention).
|
||||
PicPeak offers two release channels for different needs. Stable promotions are cut from a known-good beta point every 4–6 weeks — see [RELEASING.md](RELEASING.md) for the maintainer's promotion criteria and cadence policy.
|
||||
|
||||
**Technical** — Docker-ready, automatic thumbnail generation, external media reference mode, smart archiving of expired galleries, S3-compatible [storage backends](https://docs.picpeak.app/features/storage-backends), [webhooks](https://docs.picpeak.app/features/webhooks), and security-first defaults (JWT, rate limiting, CORS).
|
||||
### Stable Channel (Recommended)
|
||||
- Production-ready releases
|
||||
- Thoroughly tested before release
|
||||
- Docker tags: `stable`, `latest`, or specific version like `v2.3.0`
|
||||
|
||||
<details>
|
||||
<summary><strong>🧾 For studios — CRM & Accounting (Beta, off by default)</strong></summary>
|
||||
### Beta Channel
|
||||
- Early access to new features
|
||||
- May contain bugs or incomplete functionality
|
||||
- Docker tags: `beta` or specific version like `v2.3.0-beta.1`
|
||||
|
||||
- 📝 **Quotes → Contracts → Invoices** — one deal lineage; cancel-and-reissue (Storno) keeps issued invoices immutable
|
||||
- ⏱️ **Hours Logging & Calendar** — per-customer time tracking; admin calendar of events, logged hours, and pending quotes/contracts
|
||||
- 🧾 **Inbound Supplier Invoices & Expenses** — capture received invoices (upload/camera, rasterised server-side), categorise, and re-bill costs to clients
|
||||
- 📊 **Tax Report & Accountant Export** — period-scoped income/cost report with VAT breakdown; PDF/CSV plus a Treuhänder/Banana (Swiss/LI) journal export
|
||||
- 🌍 **VAT & Multi-currency** — single VAT-code registry snapshotted onto each document
|
||||
### Switching Channels
|
||||
|
||||
</details>
|
||||
Set the `PICPEAK_CHANNEL` environment variable in your `.env` file:
|
||||
|
||||
> [!WARNING]
|
||||
> **CRM & Accounting — examples only, verify locally.** Feature-flagged off by default. Seeded contract blocks are written by the maintainer, **not a lawyer**; QR-bills/SEPA payloads and every tax, VAT and Treuhänder/Banana figure are computed from your input and defaults and are **jurisdiction-specific guidance only**. Have your lawyer review contracts, scan a test QR with your bank's app, and verify all numbers with your accountant / Treuhänder / tax authority before customer-facing use. Read **[the CRM disclaimers](https://docs.picpeak.app/features/crm/disclaimers)** first.
|
||||
```bash
|
||||
# For stable releases (default)
|
||||
PICPEAK_CHANNEL=stable
|
||||
|
||||
# For beta releases
|
||||
PICPEAK_CHANNEL=beta
|
||||
|
||||
# For a specific version
|
||||
PICPEAK_CHANNEL=v2.3.0
|
||||
```
|
||||
|
||||
Then update your containers:
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.production.yml pull
|
||||
docker compose -f docker-compose.production.yml up -d
|
||||
```
|
||||
|
||||
### Update Notifications
|
||||
|
||||
The admin dashboard automatically notifies you when updates are available for your channel. To disable update checks, set:
|
||||
|
||||
```bash
|
||||
UPDATE_CHECK_ENABLED=false
|
||||
```
|
||||
|
||||
## 📖 Documentation
|
||||
|
||||
Full documentation lives at **[docs.picpeak.app](https://docs.picpeak.app)** — deployment, admin settings, API, branding, and more.
|
||||
Full documentation lives at **[docs.picpeak.app](https://docs.picpeak.app)** — deployment, admin settings reference, API docs, webhooks, archive lifecycle, branding, and everything else. Some quick links:
|
||||
|
||||
| Topic | Link |
|
||||
- 🚀 [**Deployment**](https://docs.picpeak.app/deployment) - Docker, environment variables, reverse proxy, SSL
|
||||
- ⚙️ [**Admin Settings**](https://docs.picpeak.app/guides/admin-settings) - Every tab in the Settings panel
|
||||
- 🎯 [**Creating Events**](https://docs.picpeak.app/guides/creating-events) - Full event field reference
|
||||
- 📽️ [**Live Slideshow**](https://docs.picpeak.app/features/live-slideshow) - Fullscreen projector view that auto-updates during live events
|
||||
- 💾 [**Backup & Restore**](https://docs.picpeak.app/guides/backup-restore) - Backup configuration, restore wizard, full disaster recovery
|
||||
- 🔌 [**API Reference**](https://docs.picpeak.app/api) - REST endpoints, OpenAPI spec, webhooks
|
||||
- 🪝 [**Webhooks**](https://docs.picpeak.app/features/webhooks) - Event payloads, signing, filters, templates
|
||||
|
||||
Project meta:
|
||||
|
||||
- 🤝 [**Contributing**](CONTRIBUTING.md) - How to contribute
|
||||
- 📜 [**License**](LICENSE) - MIT License
|
||||
- 🔒 [**Security**](SECURITY.md) - Security policies
|
||||
- 📋 [**Code of Conduct**](CODE_OF_CONDUCT.md) - Community guidelines
|
||||
|
||||
## 🌐 Public Landing Page
|
||||
|
||||
Spotlight your studio with a customizable marketing page at `/`:
|
||||
|
||||
- Head to **Admin → CMS Pages** to enable the public landing page toggle.
|
||||
- Edit the provided HTML template (rich sections, hero, testimonials) and optional CSS overrides.
|
||||
- The preview renders in a sandboxed iframe so you can iterate safely before publishing.
|
||||
- PicPeak sanitizes stored HTML and CSS server-side—scripts, iframes, and unsafe attributes are stripped automatically.
|
||||
- Use **Reset to default** anytime to restore the bundled template.
|
||||
- The backend caches the rendered landing page for 60 seconds by default; override with `PUBLIC_SITE_CACHE_TTL_MS` if you need a different TTL.
|
||||
- When the landing page is disabled PicPeak continues to serve the admin SPA/login exactly as before.
|
||||
|
||||
## 🎯 Use Cases
|
||||
|
||||
Perfect for:
|
||||
- 💒 **Wedding Photographers** - Share ceremony photos securely
|
||||
- 🎂 **Event Photography** - Birthday parties, corporate events
|
||||
- 📸 **Portrait Studios** - Client galleries with download limits
|
||||
- 🏢 **Corporate Events** - Internal photo sharing with branding
|
||||
- 🎓 **School Photography** - Secure parent access with expiration
|
||||
- 📽️ **Live Events** - Put a [Live Slideshow](docs/live-slideshow.md) on the venue projector that updates as you shoot
|
||||
|
||||
## 🏗️ Tech Stack
|
||||
|
||||
- **Backend**: Node.js, Express, SQLite/PostgreSQL
|
||||
- **Frontend**: React, Tailwind CSS, Framer Motion
|
||||
- **Storage**: Local filesystem (default) or S3-compatible object store (AWS S3, MinIO, R2, B2, Wasabi, Spaces) — see [Storage Backends](#storage-backends)
|
||||
- **Email**: SMTP with customizable templates
|
||||
- **Analytics**: Privacy-focused with Umami integration
|
||||
|
||||
## 💾 Storage Backends
|
||||
|
||||
PicPeak supports two storage backends for photos, thumbnails, hero images, watermarks, and archive zips. Both are configured via environment variables; no code change is required to switch.
|
||||
|
||||
| Capability | `STORAGE_BACKEND=local` (default) | `STORAGE_BACKEND=s3` |
|
||||
|---|---|---|
|
||||
| Photo / thumbnail / hero storage | Local filesystem under `STORAGE_PATH` | Bucket on any S3-compatible service |
|
||||
| Admin UI upload | ✅ | ✅ |
|
||||
| Filesystem auto-import (chokidar watcher) | ✅ | ❌ — disabled (use the upload API) |
|
||||
| Watermarks, fingerprinting, fragmentation | ✅ | ✅ (materialized to a tmp file just-in-time) |
|
||||
| Bulk download zips (cached + on-the-fly) | ✅ | ✅ |
|
||||
| Backups | ✅ | ✅ |
|
||||
| External media reference mode (`EXTERNAL_MEDIA_ROOT`) | ✅ (always local) | ✅ (still local — not migrated) |
|
||||
|
||||
### Switching to an S3-compatible backend
|
||||
|
||||
1. Provision a bucket and credentials. The minimum IAM policy is documented in `.env.example`.
|
||||
2. Set `STORAGE_BACKEND=s3` plus `STORAGE_S3_BUCKET`, `STORAGE_S3_REGION`, `STORAGE_S3_ACCESS_KEY`, `STORAGE_S3_SECRET_KEY`. For non-AWS providers (MinIO, R2, B2, …) also set `STORAGE_S3_ENDPOINT`.
|
||||
3. If you have existing local content, copy it first: `node backend/scripts/migrate-storage.js --dry-run` then `node backend/scripts/migrate-storage.js`. The script is idempotent and writes a failures CSV.
|
||||
4. Restart the backend. The startup check pings the bucket and refuses to boot on misconfig.
|
||||
|
||||
Note: presigned-URL serving (zero-bandwidth direct downloads from S3) is intentionally **not** in v1 — every request still streams through the backend so watermarks, devtools-detection, and access logging keep working.
|
||||
|
||||
## 🔔 Webhooks
|
||||
|
||||
PicPeak POSTs event/photo lifecycle notifications to URLs you configure under **Settings → Webhooks**. Each delivery is signed `HMAC-SHA256` with a per-webhook secret in the `X-PicPeak-Signature` header so receivers can verify the request really came from your PicPeak instance.
|
||||
|
||||
### Event types
|
||||
|
||||
| Event | Fires when |
|
||||
|---|---|
|
||||
| 🚀 Deployment (Docker, env, reverse proxy, SSL) | [docs.picpeak.app/deployment](https://docs.picpeak.app/deployment) |
|
||||
| ⚙️ Admin settings reference | [docs.picpeak.app/guides/admin-settings](https://docs.picpeak.app/guides/admin-settings) |
|
||||
| 🎯 Creating events | [docs.picpeak.app/guides/creating-events](https://docs.picpeak.app/guides/creating-events) |
|
||||
| 📽️ Live Slideshow | [docs.picpeak.app/features/live-slideshow](https://docs.picpeak.app/features/live-slideshow) |
|
||||
| 💾 Backup & Restore | [docs.picpeak.app/guides/backup-restore](https://docs.picpeak.app/guides/backup-restore) |
|
||||
| 🔌 API reference | [docs.picpeak.app/api](https://docs.picpeak.app/api) |
|
||||
| 🪝 Webhooks | [docs.picpeak.app/features/webhooks](https://docs.picpeak.app/features/webhooks) |
|
||||
| 💾 Storage backends (local / S3) | [docs.picpeak.app/features/storage-backends](https://docs.picpeak.app/features/storage-backends) |
|
||||
| 💻 System requirements & tuning | [docs.picpeak.app/deployment/system-requirements](https://docs.picpeak.app/deployment/system-requirements) |
|
||||
| 🧾 CRM & Accounting | [docs.picpeak.app/features/crm](https://docs.picpeak.app/features/crm) · [disclaimers](https://docs.picpeak.app/features/crm/disclaimers) |
|
||||
| 🗺️ Roadmap | [GitHub Issues](https://github.com/PicPeak/picpeak/issues) |
|
||||
| `event.created` | Gallery created (admin or API) |
|
||||
| `event.published` | Draft becomes live (`is_draft: true → false`) — also fires when an event is created with `is_draft=false` |
|
||||
| `event.archived` | Bulk-archive, manual archive, or auto-archive on expiry |
|
||||
| `event.expired` | Expiration checker marks the gallery inactive (fires before `event.archived` in the cascade) |
|
||||
| `photo.uploaded` | Admin upload, API upload, guest upload, or auto-import |
|
||||
| `photo.deleted` | Single delete, bulk delete (NOT fired per-photo when an event is archived — receivers infer from `event.archived` to avoid flooding) |
|
||||
|
||||
**Project meta:** [Contributing](CONTRIBUTING.md) · [License](LICENSE) · [Security](SECURITY.md) · [Code of Conduct](CODE_OF_CONDUCT.md)
|
||||
### Payload shape
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "delivery-uuid",
|
||||
"type": "event.published",
|
||||
"created_at": "2026-04-28T05:25:00.000Z",
|
||||
"data": {
|
||||
"event": { "id": 123, "slug": "wedding-smith", "share_url": "https://..." }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Also sent on every request:
|
||||
- `X-PicPeak-Signature` — `HMAC-SHA256(secret, raw_body)` as hex
|
||||
- `X-PicPeak-Event` — the event type (handy for routing without parsing the body)
|
||||
- `X-PicPeak-Delivery` — UUID for idempotency on the receiver side
|
||||
- `User-Agent: PicPeak-Webhooks/1.0`
|
||||
|
||||
### Verifying signatures
|
||||
|
||||
**Node.js**
|
||||
```js
|
||||
const crypto = require('crypto');
|
||||
function verify(secret, rawBody, signature) {
|
||||
const expected = crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
|
||||
const a = Buffer.from(expected, 'hex');
|
||||
const b = Buffer.from(signature, 'hex');
|
||||
if (a.length !== b.length) return false;
|
||||
return crypto.timingSafeEqual(a, b);
|
||||
}
|
||||
```
|
||||
|
||||
**Python**
|
||||
```python
|
||||
import hmac, hashlib
|
||||
def verify(secret: str, raw_body: bytes, signature: str) -> bool:
|
||||
expected = hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
|
||||
return hmac.compare_digest(expected, signature)
|
||||
```
|
||||
|
||||
**curl + openssl** (one-liner for a quick replay)
|
||||
```sh
|
||||
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$SECRET" | awk '{print $2}')
|
||||
[ "$SIG" = "$RECEIVED_SIG" ] && echo OK || echo MISMATCH
|
||||
```
|
||||
|
||||
### Retries + observability
|
||||
|
||||
- `2xx` → success, recorded with latency
|
||||
- Non-`2xx` or network error → exponential backoff: `1m → 5m → 30m → 2h → 12h`, max 5 attempts
|
||||
- After max attempts: status `failed`, surfaces in **Settings → Webhooks → Deliveries** with a "Replay" button
|
||||
- Up to 5 deliveries in flight at once; one slow consumer can't block others (configurable via `WEBHOOK_DELIVERY_CONCURRENCY`)
|
||||
- Response body truncated to 1KB before storage so chatty receivers don't bloat the audit log
|
||||
|
||||
The deliveries page (`/admin/webhooks/:id/deliveries`) shows every attempt with timestamp, status, HTTP code, latency, payload sent, signature, and response. Click "Send test event" to fire a synthetic delivery for any event type.
|
||||
|
||||
### SSRF protection
|
||||
|
||||
Webhook URLs are validated against the same private-IP blocklist used elsewhere in the app — loopback, private RFC1918 ranges, link-local, `.local`/`.internal` hostnames, cloud metadata endpoints. The check runs both at create time and per-delivery (DNS-rebinding mitigation).
|
||||
|
||||
For local development with a receiver on the same machine or docker network, set `WEBHOOK_ALLOW_PRIVATE_URLS=true`. Production deployments must leave this OFF.
|
||||
|
||||
## 💻 System Requirements
|
||||
|
||||
### Minimum Requirements
|
||||
- **CPU**: 2 CPU cores
|
||||
- **RAM**: **4 GB minimum** for a normal photo-upload workload — sharp/libvips
|
||||
decodes the full uncompressed frame before resize, and the default two
|
||||
worker loops at sharp-concurrency 2 can push peak RSS past 1.5 GB on a
|
||||
batch of 20-MP+ photos. On a 2 GB VPS that's enough to OOM-kill the
|
||||
backend mid-batch (surfaces as 503s on thumbnails — see [Low-memory
|
||||
hosts](#low-memory-hosts) below for the recipe to run on 2 GB).
|
||||
- **Storage**: 20GB minimum (plus photo storage needs)
|
||||
- **OS**: Linux (Ubuntu 20.04+), macOS, or Windows with WSL2
|
||||
- **Node.js**: v18.0.0 or higher
|
||||
- **Database**: SQLite (included) or PostgreSQL 12+
|
||||
|
||||
### Docker Requirements (Recommended)
|
||||
- **Docker**: v20.10.0+
|
||||
- **Docker Compose**: v2.0.0+
|
||||
|
||||
### Low-memory hosts
|
||||
|
||||
Running on 2 GB RAM (e.g. an entry-level VPS) is workable but requires
|
||||
tuning the upload-processor concurrency down. The backend auto-detects
|
||||
total RAM at startup via `os.totalmem()` — on a host that reports < 3 GB,
|
||||
it defaults `UPLOAD_PROCESSOR_CONCURRENCY` to **1** instead of 2 and logs
|
||||
a one-shot warning. You can pin the value explicitly in `.env`:
|
||||
|
||||
```env
|
||||
# Single worker loop — slower batch processing, lower peak RSS
|
||||
UPLOAD_PROCESSOR_CONCURRENCY=1
|
||||
```
|
||||
|
||||
The trade-off is throughput: a single worker processes one photo at a
|
||||
time, so a 100-photo batch takes ~2× as long but won't OOM. **Health-check
|
||||
note**: if the backend dies under memory pressure, the gallery serves
|
||||
`503 Service Unavailable` on thumbnails until Docker's
|
||||
`restart: unless-stopped` brings the container back. Persistent 503s
|
||||
during/after an upload batch on a low-memory host are almost always this.
|
||||
|
||||
### Video Support Requirements
|
||||
When enabling video uploads, consider these additional resources:
|
||||
|
||||
| Resource | Recommendation | Notes |
|
||||
|----------|----------------|-------|
|
||||
| **RAM** | 4GB+ recommended | FFmpeg processing requires more memory |
|
||||
| **Storage** | Plan for 10-100x more | Videos are significantly larger than images |
|
||||
| **CPU** | Additional cores help | Video thumbnail extraction is CPU-intensive |
|
||||
| **Bandwidth** | Higher throughput | Video streaming requires more bandwidth |
|
||||
|
||||
**Technical Notes:**
|
||||
- FFmpeg is bundled via npm (`@ffmpeg-installer/ffmpeg`) - no system installation required
|
||||
- Maximum upload size: **10GB per video file**
|
||||
- Chunked upload support for files >100MB (resumable uploads)
|
||||
- Supported formats: MP4, WebM, MOV, AVI
|
||||
- Video thumbnails are automatically generated from the first few seconds
|
||||
|
||||
**For Nginx/Reverse Proxy:**
|
||||
If using Nginx, increase the client max body size:
|
||||
```nginx
|
||||
client_max_body_size 10G;
|
||||
proxy_read_timeout 3600;
|
||||
proxy_send_timeout 3600;
|
||||
```
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
We love contributions! PicPeak is built by photographers, for photographers. Whether you're fixing bugs, adding features, or improving documentation, your help is welcome.
|
||||
|
||||
See our [Contributing Guide](CONTRIBUTING.md) for details.
|
||||
|
||||
## 📊 Comparison with Alternatives
|
||||
|
||||
@@ -135,79 +409,168 @@ Full documentation lives at **[docs.picpeak.app](https://docs.picpeak.app)** —
|
||||
| Quotes / Contracts / Invoices | 🧪 Beta | ❌ | ❌ | ✅ |
|
||||
| Incoming Invoices & Accounting | 🧪 Beta | ❌ | ❌ | ❌ |
|
||||
|
||||
<sub>*You bring your own server and, optionally, a domain. **Limited only by your server storage. ***Pixieset's "unlimited" is photos only; video is capped by plan. 🧪 Beta = built but feature-flagged off by default.</sub>
|
||||
*You still bring your own server (own hardware or a VPS) and, if you want one, a domain.
|
||||
**Limited only by your server storage.
|
||||
***Pixieset's "unlimited" is photos only; video is capped by plan (roughly 0–10 h depending on tier).
|
||||
🧪 Beta = built but feature-flagged off by default (see [Beta Features](#-beta-features-use-at-your-own-risk)).
|
||||
|
||||
## 🏗️ Tech Stack
|
||||
## 🛡️ Security
|
||||
|
||||
- **Backend**: Node.js, Express, SQLite/PostgreSQL
|
||||
- **Frontend**: React, Tailwind CSS, Framer Motion
|
||||
- **Storage**: Local filesystem (default) or S3-compatible object store (AWS S3, MinIO, R2, B2, Wasabi, Spaces) — see [Storage Backends](https://docs.picpeak.app/features/storage-backends)
|
||||
- **Email**: SMTP with customizable templates
|
||||
- **Analytics**: Privacy-focused with Umami integration
|
||||
- **External media**: point PicPeak at `EXTERNAL_MEDIA_ROOT` to reference existing originals read-only, index quickly, and generate thumbnails on demand
|
||||
PicPeak takes security seriously:
|
||||
- 🔐 Password hashing with bcrypt
|
||||
- 🎫 JWT-based authentication
|
||||
- 🚦 Rate limiting on all endpoints
|
||||
- 🛡️ CORS protection
|
||||
- 📝 Activity logging
|
||||
- 🔒 Secure file access
|
||||
|
||||
Found a security issue? Please open a [security issue](https://github.com/PicPeak/picpeak/issues/new?labels=security) on GitHub
|
||||
|
||||
## 📸 Screenshots
|
||||
|
||||
<details>
|
||||
<summary>Click to see the admin dashboard, analytics, and event management</summary>
|
||||
### 🎛️ **Admin Dashboard**
|
||||
Get a complete overview of your photo galleries, analytics, and system status.
|
||||
|
||||
### 🎛️ Admin Dashboard
|
||||
<img src="docs/screenshot-dashboard.png" alt="PicPeak Admin Dashboard" width="800" />
|
||||
|
||||
### 📊 Analytics & Insights
|
||||
### 📊 **Analytics & Insights**
|
||||
Track gallery performance, view statistics, and monitor user engagement.
|
||||
|
||||
<img src="docs/screenshot-analytics.png" alt="PicPeak Analytics Dashboard" width="800" />
|
||||
|
||||
### 📁 Event Management
|
||||
### 📁 **Event Management**
|
||||
Organize and manage your photo galleries with intuitive event management tools.
|
||||
|
||||
<img src="docs/screenshots-events.png" alt="PicPeak Events Management" width="800" />
|
||||
|
||||
### ✨ **Key Interface Highlights**
|
||||
|
||||
<details>
|
||||
<summary>👆 Click to see more interface details</summary>
|
||||
|
||||
#### What makes PicPeak's interface special:
|
||||
|
||||
- **🎨 Clean Design**: Modern, photographer-friendly interface
|
||||
- **📱 Responsive**: Perfect on desktop, tablet, and mobile
|
||||
- **⚡ Fast Loading**: Optimized for quick photo browsing
|
||||
- **🔒 Secure Access**: Password-protected galleries with expiration
|
||||
- **📤 Easy Uploads**: Drag & drop functionality for effortless photo management
|
||||
- **🎯 Client-Focused**: Intuitive gallery experience for your clients
|
||||
|
||||
</details>
|
||||
|
||||
## 🤝 Contributing
|
||||
## 🗺️ Roadmap
|
||||
|
||||
We love contributions! PicPeak is built by photographers, for photographers — whether you're fixing bugs, adding features, or improving docs. See the [Contributing Guide](CONTRIBUTING.md) to get started.
|
||||
We're constantly improving PicPeak and welcome contributions from our community! If you have ideas for new features or want to help implement existing ones, please open an issue or submit a pull request. Your contributions help make PicPeak better for everyone.
|
||||
|
||||
Found a security issue? Please open a [security issue](https://github.com/PicPeak/picpeak/issues/new?labels=security). See [SECURITY.md](SECURITY.md) for the policy.
|
||||
### 🚧 Beta Features (Use at your own risk)
|
||||
|
||||
These features are currently in beta testing and may have limited functionality or stability:
|
||||
|
||||
| Feature | Description | Status |
|
||||
|---------|-------------|--------|
|
||||
| **CRM & Accounting Module** | Quotes, contracts, invoices (+ Storno), hours logging, calendar, and tax report — plus inbound supplier-invoice capture, internal expenses, and a Treuhänder/Banana (Swiss/LI) accountant-journal export. Feature-flagged off by default. Seeded contract blocks, payment terms, IBAN / QR-bill and tax defaults are **examples only** and need legal / financial / **tax** review before customer-facing use. See [docs.picpeak.app/features/crm](https://docs.picpeak.app/features/crm). | 🧪 Beta |
|
||||
| **Simple Deployment Script** | One-click deployment script for quick server setup with automated configuration and dependency installation | 🧪 Beta |
|
||||
|
||||
### 📋 Future Enhancements
|
||||
|
||||
| Feature | Description | Priority | Status |
|
||||
|---------|-------------|----------|---------|
|
||||
| **Backup & Restore** | Comprehensive backup system with S3/MinIO support, automated scheduling, and safe restore functionality | High | ✅ Implemented |
|
||||
| **External Media Library (Reference Mode)** | Use an external folder library as a read‑only source with import and on‑demand thumbnail generation | High | ✅ Implemented |
|
||||
| **Download Protection** | Advanced image protection system with canvas rendering, invisible watermarking, right-click prevention, and DevTools detection to protect photos from unauthorized downloads | High | ✅ Implemented |
|
||||
| **Gallery Templates** | Multiple gallery layouts (grid, masonry, carousel, timeline, hero, mosaic) with custom CSS styling support. Includes starter templates like Apple Liquid Glass for complete visual customization | Medium | ✅ Implemented |
|
||||
| **Face Recognition** | AI-powered face detection to help guests find their photos and create automatic person-based albums | Low | 🔄 Open |
|
||||
| **Gallery Feedback** | Allow guests to like, rate, and comment on photos with admin notifications and moderation | Medium | ✅ Implemented |
|
||||
| **Video Support** | Upload and display videos alongside photos in galleries with streaming support | Low | ✅ Implemented |
|
||||
| **Multiple Administrators** | Support for multiple admin accounts with role-based permissions and activity tracking | Low | ✅ Implemented |
|
||||
| **Filtering & Export Options** | Filter photos by likes, ratings, comments, or favorites. Search by filename. Sort by date, name, size, or rating. Export filtered selections as ZIP or generate Capture One/Lightroom-compatible file lists for professional workflows | Medium | ✅ Implemented |
|
||||
|
||||
**Status Legend:** ✅ Implemented | 🚧 In Progress | 🔄 Open | 📋 Planned
|
||||
|
||||
## ☕ Support the Project
|
||||
|
||||
PicPeak is free, open source, and self-hostable forever. If it saves you time or replaces a paid subscription, consider [buying me a coffee](https://buymeacoffee.com/theluap) — it directly funds new features, bug fixes, and keeping the demo + docs running. You can also ⭐ star the repo, share it, file good bug reports, or open a PR.
|
||||
PicPeak is free, open source, and self-hostable forever. If it saves you time or replaces a paid subscription, consider buying me a coffee — it directly funds the time spent on new features, bug fixes, and keeping the demo + docs running.
|
||||
|
||||
<p align="left">
|
||||
<a href="https://buymeacoffee.com/theluap" target="_blank">
|
||||
<img src="https://img.buymeacoffee.com/button-api/?text=Buy%20me%20a%20coffee&emoji=☕&slug=theluap&button_colour=FFDD00&font_colour=000000&font_family=Cookie&outline_colour=000000&coffee_colour=ffffff" alt="Buy Me A Coffee" />
|
||||
</a>
|
||||
</p>
|
||||
|
||||
Other ways to support without spending anything: ⭐ star the repo, share it with photographer friends, file good bug reports, or open a PR.
|
||||
|
||||
## 🙏 Acknowledgments
|
||||
|
||||
PicPeak is inspired by the best features of commercial platforms while remaining completely open source. It's developed with AI assistance, but human-tested end-to-end, security-audited, and human-reviewed for quality.
|
||||
PicPeak is inspired by the best features of commercial platforms while remaining completely open source. Special thanks to all contributors who make this project possible.
|
||||
|
||||
### 👥 Contributors
|
||||
|
||||
A huge thank you to the people whose code, reports, and feedback have shaped PicPeak:
|
||||
|
||||
**[@the-luap](https://github.com/the-luap)** — creator and lead maintainer
|
||||
- Gallery foundation (events, uploads, sharing, download protection, templates)
|
||||
- Backup & restore, analytics, branding/theming
|
||||
- The architecture every later feature builds on
|
||||
|
||||
**[@Luca-Timo](https://github.com/Luca-Timo)**
|
||||
- Native Apple Silicon multi-arch images
|
||||
- CRM & accounting suite (quotes/contracts/invoices)
|
||||
- Hours logging & Treuhänder/Banana tax export
|
||||
- Gallery header/banner decoupling
|
||||
|
||||
**[@Rekoo-PS](https://github.com/Rekoo-PS)** — bug reports & product feedback
|
||||
- Login-loop fix, mobile-lightbox overhaul, bulk-delete workflow
|
||||
- Also a [BuyMeACoffee](https://buymeacoffee.com/theluap) supporter
|
||||
- [**@the-luap**](https://github.com/the-luap) — creator and lead maintainer. Started the project and built PicPeak's foundation and the entire gallery experience (events, galleries, uploads, sharing, download protection, templates), plus backup & restore, analytics, system health, branding/theming, and WhatsApp notifications — and the architecture every later feature builds on.
|
||||
- [**@Luca-Timo**](https://github.com/Luca-Timo) — native Apple Silicon multi-arch images, external-URL toggle for legal CMS pages, the lazy-loaded folder tree picker, the admin-email picker on event creation, the data-driven self-hosted webfont system, the gallery header/banner decoupling, several typed-API refactors, and the CRM + accounting suite (quotes/contracts/invoices, hours logging, calendar, tax report, inbound supplier-invoice capture, expenses, and the Treuhänder/Banana export). Consistently raises the bar with thoughtful PRs.
|
||||
- [**@Rekoo-PS**](https://github.com/Rekoo-PS) — sharp-eyed bug reporter and product feedback. Filed the issues that drove the login-loop fix, the gallery-loading skeleton work, the redirection cleanup, the mobile-lightbox overhaul, the admin-events search-counter fix, the photo-count column, and the bulk-delete workflow. Also a [BuyMeACoffee](https://buymeacoffee.com/theluap) supporter — the kind of feedback loop that keeps the project useful for real deployments.
|
||||
|
||||
If you've contributed and aren't listed here, please open a PR — this list is meant to grow.
|
||||
|
||||
### 🤖 AI-Assisted Development
|
||||
|
||||
This project was generated with the assistance of AI technology, but has been:
|
||||
- ✅ **Fully tested end-to-end** by human developers
|
||||
- 🔒 **Security audited** with comprehensive security checks
|
||||
- 👨💻 **Human-reviewed** for code quality and best practices
|
||||
- 🧪 **Production-tested** in real-world scenarios
|
||||
|
||||
We believe in transparent development practices and the responsible use of AI as a tool to accelerate development while maintaining high standards of quality and security.
|
||||
|
||||
## ⚠️ CRM & Accounting disclaimers — examples only, verify locally
|
||||
|
||||
The CRM & accounting modules (contracts, invoices, QR-bills, the tax
|
||||
report and the accountant exports) ship seeded content and computed
|
||||
figures that are intended as a **starting point only**:
|
||||
|
||||
- **Contract blocks** (image rights, NDA, model release, cancellation,
|
||||
jurisdiction, …) are written by the maintainer, **not by a lawyer**.
|
||||
Every operator must have their lawyer review and adapt them before
|
||||
sending any contract to a customer.
|
||||
- **QR-bills and SEPA EPC payloads** are rendered from the data you
|
||||
typed. Picpeak is open source — please scan a test invoice with your
|
||||
bank's app to check the QR actually works. We are not responsible for
|
||||
any mistakes that come from sending an invoice with bad data on it.
|
||||
- **Tax, VAT & accounting figures** (the tax report, VAT-payable, the
|
||||
per-rate breakdown, the Treuhänder / Banana export, etc.) are computed
|
||||
from the data you enter and the defaults you configure. They are
|
||||
**guidance only and jurisdiction-specific** — tax rules, VAT rates,
|
||||
deduction schemes (e.g. the Liechtenstein 20 % Gewinnungskosten flat
|
||||
rate) and filing duties differ by country and change over time. **Every
|
||||
operator must check their own tax / VAT regulations and verify the
|
||||
numbers with their accountant / Treuhänder / tax authority before
|
||||
relying on any figure or export.** Picpeak makes no warranty that the
|
||||
output is correct for your jurisdiction or situation.
|
||||
|
||||
Read [`docs/crm-disclaimers.md`](docs/crm-disclaimers.md) before
|
||||
enabling the Contracts, Invoices or Accounting features.
|
||||
|
||||
## 📄 License
|
||||
|
||||
PicPeak is released under the [MIT License](LICENSE). Use it freely for personal or commercial projects.
|
||||
|
||||
## 🚀 Ready to Get Started?
|
||||
|
||||
1. ⭐ **Star this repository** to show your support
|
||||
2. 📖 Read the [docs at docs.picpeak.app](https://docs.picpeak.app)
|
||||
3. 🐛 Report issues or request features
|
||||
4. 🤝 Join our community and contribute!
|
||||
|
||||
---
|
||||
|
||||
<p align="center">
|
||||
Made with ❤️ by photographers, for photographers
|
||||
<br>
|
||||
<a href="https://www.picpeak.app">Homepage</a> ·
|
||||
<a href="https://demo.picpeak.app">Live Demo</a> ·
|
||||
<a href="https://docs.picpeak.app">Documentation</a> ·
|
||||
<a href="https://www.picpeak.app">Homepage</a> •
|
||||
<a href="https://demo.picpeak.app">Live Demo</a> •
|
||||
<a href="https://github.com/PicPeak/picpeak">GitHub</a> •
|
||||
<a href="https://docs.picpeak.app">Documentation</a> •
|
||||
<a href="https://github.com/PicPeak/picpeak/issues">Support</a>
|
||||
</p>
|
||||
|
||||
+4
-18
@@ -52,19 +52,13 @@ The actual mechanics, in order:
|
||||
- **`.release-please-manifest.json`** — keep `stable`'s; release-please owns this file.
|
||||
- Any other auto-merged file — spot-check that the auto-merge produced something sensible, especially for security-sensitive files (`backend/src/middleware/`, `backend/src/utils/tokenUtils.js`).
|
||||
|
||||
5. **Pin the stable version to match `main` (number alignment — see Versioning).** Determine `X.Y.Z` = the `main` tip's **base** version (its `vX.Y.Z-beta.N`, dropping the `-beta.N` suffix), and add an empty commit on the release branch:
|
||||
```bash
|
||||
git commit --allow-empty -m "chore: release X.Y.Z" -m "Release-As: X.Y.Z"
|
||||
```
|
||||
The `Release-As:` footer forces release-please to cut exactly `X.Y.Z`. Without it, release-please computes the next MINOR from the *previous stable* tag (e.g. `3.45.0` → `3.46.0`) while `main` is already at `3.84.x`, so the stable number drifts ever further behind for the same code.
|
||||
5. **Wait for CI on the PR.** All ten checks (the original eight plus `merge-backend` and `merge-frontend`) must be green. If anything fails, fix on the release branch (NOT on `main` — `main` has already moved on).
|
||||
|
||||
6. **Wait for CI on the PR.** All ten checks (the original eight plus `merge-backend` and `merge-frontend`) must be green. If anything fails, fix on the release branch (NOT on `main` — `main` has already moved on).
|
||||
6. **Merge.** Standard merge commit, not squash — the PR's history (the individual feature commits) carries forward into `stable`'s log.
|
||||
|
||||
7. **Merge.** Standard merge commit, not squash — the PR's history (the individual feature commits) carries forward into `stable`'s log.
|
||||
7. **release-please picks it up.** Within minutes, release-please will open a new `chore(stable): release X.Y.Z` PR proposing the stable release. Review the auto-generated CHANGELOG.md entries for accuracy, edit if needed, and merge. That merge creates the `vX.Y.Z` git tag, publishes Docker images on the `:stable` and `:latest` tags, and creates the GitHub Release page.
|
||||
|
||||
8. **release-please picks it up.** Within minutes, release-please will open a new `chore(stable): release X.Y.Z` PR proposing the stable release. Review the auto-generated CHANGELOG.md entries for accuracy, edit if needed, and merge. That merge creates the `vX.Y.Z` git tag, publishes Docker images on the `:stable` and `:latest` tags, and creates the GitHub Release page.
|
||||
|
||||
9. **Close the loop.** Bulk-close any `bug` issues that were fixed-but-not-closed and now appear in the released changelog. Reference the merge commit so reporters know which version contains the fix.
|
||||
8. **Close the loop.** Bulk-close any `bug` issues that were fixed-but-not-closed and now appear in the released changelog. Reference the merge commit so reporters know which version contains the fix.
|
||||
|
||||
## Hotfix path (backport to current stable)
|
||||
|
||||
@@ -89,14 +83,6 @@ PicPeak follows [Semantic Versioning](https://semver.org/) with one project-spec
|
||||
|
||||
release-please derives all of this from conventional commit prefixes (`feat:`, `fix:`, `BREAKING CHANGE:`, etc.) automatically.
|
||||
|
||||
### Stable ↔ pre-release number alignment
|
||||
|
||||
The two channels run **independent** release-please counters: `main` bumps on every merge (racing ahead), while `stable` only bumps on a promotion. Left to itself, `stable` computes each promotion as the next MINOR from the *previous stable tag*, so the two drift far apart — e.g. `main` at `v3.83.x-beta.0` while `stable` sat at `v3.45.0` for the **same code**, which reads as "stable is 38 versions behind" when it isn't.
|
||||
|
||||
To keep the numbers legible, **a promotion sets the stable version to the current `main` base version** (the `X.Y.Z` of the `main` tip's `vX.Y.Z-beta.N`, minus the suffix). Promoting a `main` at `v3.84.2-beta.0` therefore cuts stable `v3.84.2`, and the stable number tracks `main` instead of lagging. This is forced with the `Release-As:` commit in step 5 of the cut procedure — the one-time catch-up jump (e.g. `3.45.0 → 3.84.x`) is expected and happens only on the first aligned promotion.
|
||||
|
||||
> **Release-engineering note (2026-07):** `release-please.yml` (the stable workflow) *must* keep `target-branch: stable`. Without it, release-please defaults to the repo's default branch (`main`), reads `main`'s stale `.release-please-manifest.json`, and cuts a wrong/regressed version — this is what produced a bogus `v2.7.0` once. If a promotion ever yields an unexpected version, check that first.
|
||||
|
||||
## Things that don't go through this process
|
||||
|
||||
- **Documentation-only changes** can land on either `stable` or `main` directly (no release cut needed); release-please will pick them up on the next regular release.
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
node_modules
|
||||
npm-debug.log
|
||||
.env
|
||||
storage
|
||||
storage/events/active/*
|
||||
storage/events/archived/*
|
||||
storage/thumbnails/*
|
||||
data/*.db
|
||||
logs/*
|
||||
coverage
|
||||
|
||||
@@ -106,12 +106,6 @@ ARCHIVE_PATH=/app/storage/events/archived
|
||||
# EVENTS_PATH=./storage/events
|
||||
# ARCHIVE_PATH=./storage/events/archived
|
||||
|
||||
# File watcher (auto-import from the events/active folder, local storage only)
|
||||
# Max photos processed in parallel by the watcher. The boot scan and bulk
|
||||
# folder drops fire one handler per file — this bound keeps thumbnail
|
||||
# generation from exhausting memory on small hosts. Default: 2
|
||||
# FILE_WATCHER_CONCURRENCY=2
|
||||
|
||||
# Analytics Backend Configuration (OPTIONAL)
|
||||
# Used for server-side tracking only
|
||||
# Primary configuration should be done through Admin UI > Settings > Analytics
|
||||
|
||||
+2
-14
@@ -27,15 +27,6 @@ FROM node:22-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# knexfile.js picks its config block by NODE_ENV, and the `development` block
|
||||
# defaults to sqlite3. Leaving NODE_ENV unset here meant every deployment that
|
||||
# doesn't go through our compose files — Kubernetes, Helm, plain `docker run` —
|
||||
# silently ran on SQLite and ignored DB_HOST/DB_USER/DB_PASSWORD, while
|
||||
# wait-for-db.sh (shell, reads DB_HOST directly) reported "PostgreSQL is up" in
|
||||
# the same log. The compose files still override this, so nothing changes for
|
||||
# compose users. See #1038.
|
||||
ENV NODE_ENV=production
|
||||
|
||||
# Redeclare CACHEBUST — ARGs don't cross stage boundaries, so the builder
|
||||
# stage's declaration never reached this stage. Consuming it in the RUN below
|
||||
# busts that layer's cache every CI run (CACHEBUST=github.run_number), so the
|
||||
@@ -77,12 +68,9 @@ RUN rm -rf /usr/local/lib/node_modules/npm /usr/local/bin/npm /usr/local/bin/npx
|
||||
# PDFs to flat PNGs server-side so the admin UI NEVER renders a raw (possibly
|
||||
# malicious) PDF. pdftoppm does not execute embedded JS or fetch remote
|
||||
# resources, so it doubles as the SSRF/phone-home guard for untrusted inbound
|
||||
# documents (see https://docs.picpeak.app/features/accounting/incoming-invoices).
|
||||
# exiftool extracts the embedded full-res JPEG preview from RAW/DNG uploads
|
||||
# (Apple ProRAW etc.) — sharp's libvips has no raw loader, so the pipeline
|
||||
# thumbnails/displays that preview while keeping the original for download.
|
||||
# documents (see docs/accounting-inbound-invoices.md).
|
||||
RUN apk add --no-cache dumb-init postgresql-client ffmpeg su-exec \
|
||||
fontconfig ttf-dejavu ttf-liberation poppler-utils exiftool && \
|
||||
fontconfig ttf-dejavu ttf-liberation poppler-utils && \
|
||||
fc-cache -f
|
||||
|
||||
# Create non-root user
|
||||
|
||||
@@ -8,10 +8,7 @@ RUN apk upgrade --no-cache
|
||||
# Install dumb-init for proper signal handling and ffmpeg for video uploads.
|
||||
# Alpine's ffmpeg ships both ffmpeg + ffprobe built natively against musl;
|
||||
# the npm-bundled binary doesn't run reliably on Alpine. Match production.
|
||||
# exiftool: extract embedded JPEG previews from RAW/DNG uploads (#821) — kept in
|
||||
# sync with the production Dockerfile so dev/native runtimes don't accept a DNG
|
||||
# and then fail it with ENOENT.
|
||||
RUN apk add --no-cache dumb-init ffmpeg exiftool
|
||||
RUN apk add --no-cache dumb-init ffmpeg
|
||||
|
||||
# Copy package files
|
||||
COPY package*.json ./
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
/**
|
||||
* Backup credential exposure regression tests.
|
||||
*
|
||||
* The generic settings reads (GET /admin/settings, GET /admin/settings/:type)
|
||||
* masked the recaptcha/umami/rybbit keys but returned backup_s3_secret_key
|
||||
* and backup_rsync_ssh_key (an SSH PRIVATE KEY) in plaintext to any
|
||||
* settings.view holder; GET /admin/backup/config returned them too. Both now
|
||||
* mask, and PUT /admin/backup/config skips the mask sentinel so the edit
|
||||
* form round-trips without clobbering stored credentials.
|
||||
*/
|
||||
|
||||
const request = require('supertest');
|
||||
const express = require('express');
|
||||
|
||||
const { bootCrmDb } = require('./helpers/crmDb');
|
||||
|
||||
jest.mock('../../src/middleware/auth', () => ({
|
||||
adminAuth: (req, _res, next) => {
|
||||
req.admin = { id: 1, username: 'test-admin' };
|
||||
next();
|
||||
},
|
||||
}));
|
||||
jest.mock('../../src/middleware/permissions', () => ({
|
||||
requirePermission: () => (_req, _res, next) => next(),
|
||||
requireSuperAdmin: () => (_req, _res, next) => next(),
|
||||
}));
|
||||
|
||||
describe('backup credential masking', () => {
|
||||
let db;
|
||||
let cleanup;
|
||||
let app;
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
|
||||
// Upsert: several backup_* keys are pre-seeded by the backup migrations.
|
||||
const seed = [
|
||||
{ setting_key: 'backup_destination_type', setting_value: JSON.stringify('s3'), setting_type: 'backup' },
|
||||
{ setting_key: 'backup_s3_endpoint', setting_value: JSON.stringify('https://s3.example.com'), setting_type: 'backup' },
|
||||
{ setting_key: 'backup_s3_bucket', setting_value: JSON.stringify('backups'), setting_type: 'backup' },
|
||||
{ setting_key: 'backup_s3_access_key', setting_value: JSON.stringify('AKIAEXAMPLE'), setting_type: 'backup' },
|
||||
{ setting_key: 'backup_s3_secret_key', setting_value: JSON.stringify('super-secret-s3-key'), setting_type: 'backup' },
|
||||
{ setting_key: 'backup_rsync_ssh_key', setting_value: JSON.stringify('-----BEGIN OPENSSH PRIVATE KEY-----abc'), setting_type: 'backup' },
|
||||
];
|
||||
for (const row of seed) {
|
||||
await db('app_settings').insert(row).onConflict('setting_key').merge();
|
||||
}
|
||||
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api/admin/backup', require('../../src/routes/adminBackup'));
|
||||
app.use('/api/admin/settings', require('../../src/routes/adminSettings'));
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => {
|
||||
if (cleanup) await cleanup();
|
||||
});
|
||||
|
||||
it('masks the credentials in GET /admin/backup/config', async () => {
|
||||
const res = await request(app).get('/api/admin/backup/config').expect(200);
|
||||
expect(res.body.backup_s3_secret_key).toBe('••••••••');
|
||||
expect(res.body.backup_rsync_ssh_key).toBe('••••••••');
|
||||
// Non-secret fields stay readable for the form.
|
||||
expect(res.body.backup_s3_bucket).toBe('backups');
|
||||
});
|
||||
|
||||
it('masks the credentials in the generic GET /admin/settings/:type read', async () => {
|
||||
const res = await request(app).get('/api/admin/settings/backup').expect(200);
|
||||
expect(res.body.backup_s3_secret_key).toBe('••••••••');
|
||||
expect(res.body.backup_rsync_ssh_key).toBe('••••••••');
|
||||
});
|
||||
|
||||
it('masks the credentials in the generic GET /admin/settings read', async () => {
|
||||
const res = await request(app).get('/api/admin/settings').expect(200);
|
||||
expect(res.body.backup_s3_secret_key).toBe('••••••••');
|
||||
expect(res.body.backup_rsync_ssh_key).toBe('••••••••');
|
||||
});
|
||||
|
||||
it('PUT /admin/backup/config keeps the stored secret when the sentinel round-trips', async () => {
|
||||
await request(app)
|
||||
.put('/api/admin/backup/config')
|
||||
.send({
|
||||
backup_destination_type: 's3',
|
||||
backup_s3_endpoint: 'https://s3.example.com',
|
||||
backup_s3_bucket: 'renamed-bucket',
|
||||
backup_s3_access_key: 'AKIAEXAMPLE',
|
||||
backup_s3_secret_key: '••••••••',
|
||||
backup_rsync_ssh_key: '••••••••',
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
const secret = await db('app_settings').where({ setting_key: 'backup_s3_secret_key' }).first();
|
||||
expect(JSON.parse(secret.setting_value)).toBe('super-secret-s3-key');
|
||||
const sshKey = await db('app_settings').where({ setting_key: 'backup_rsync_ssh_key' }).first();
|
||||
expect(JSON.parse(sshKey.setting_value)).toBe('-----BEGIN OPENSSH PRIVATE KEY-----abc');
|
||||
const bucket = await db('app_settings').where({ setting_key: 'backup_s3_bucket' }).first();
|
||||
expect(JSON.parse(bucket.setting_value)).toBe('renamed-bucket');
|
||||
});
|
||||
|
||||
it('PUT /admin/backup/config stores a genuinely new secret', async () => {
|
||||
await request(app)
|
||||
.put('/api/admin/backup/config')
|
||||
.send({ backup_s3_secret_key: 'rotated-s3-key' })
|
||||
.expect(200);
|
||||
|
||||
const secret = await db('app_settings').where({ setting_key: 'backup_s3_secret_key' }).first();
|
||||
expect(JSON.parse(secret.setting_value)).toBe('rotated-s3-key');
|
||||
});
|
||||
});
|
||||
@@ -1,211 +0,0 @@
|
||||
/**
|
||||
* Layered per-event category ordering (#782).
|
||||
*
|
||||
* Two ordering layers, resolved per event:
|
||||
* - GLOBAL default — photo_categories.display_order (migration 159),
|
||||
* set via POST /reorder-global; applies everywhere.
|
||||
* - PER-EVENT override — event_category_order (migration 160), set via
|
||||
* POST /reorder; overrides the default for one gallery.
|
||||
* - DELETE /reorder/:eventId clears an event's override.
|
||||
*
|
||||
* Verified against a real SQLite DB with the full core-migration set applied.
|
||||
*/
|
||||
const request = require('supertest');
|
||||
const {
|
||||
bootCrmDb, seedMinimal, assignAdminRole, mintAdminToken, buildRouteApp,
|
||||
} = require('./helpers/crmDb');
|
||||
|
||||
jest.setTimeout(120000);
|
||||
|
||||
describe('category ordering (#782)', () => {
|
||||
let db;
|
||||
let cleanup;
|
||||
let token;
|
||||
let app;
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
const { adminId } = await seedMinimal(db);
|
||||
await assignAdminRole(db, adminId, 'super_admin');
|
||||
token = mintAdminToken(adminId);
|
||||
app = buildRouteApp('/api/admin/categories', require('../../src/routes/adminCategories'));
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => { if (cleanup) await cleanup(); });
|
||||
|
||||
const auth = (r) => r.set('Authorization', `Bearer ${token}`);
|
||||
|
||||
async function insertEvent(slug) {
|
||||
await db('events').insert({
|
||||
event_type: 'wedding', password_hash: 'x',
|
||||
expires_at: new Date(Date.now() + 9e9).toISOString(),
|
||||
is_active: true, is_archived: false, slug, share_link: slug,
|
||||
event_name: slug, event_date: '2026-01-01',
|
||||
});
|
||||
return (await db('events').where({ slug }).first()).id;
|
||||
}
|
||||
|
||||
async function insertCat(name, { is_global = false, event_id = null, display_order = 0 } = {}) {
|
||||
const res = await db('photo_categories').insert({
|
||||
name,
|
||||
slug: name.toLowerCase().replace(/\s+/g, '-'),
|
||||
is_global: is_global ? 1 : 0,
|
||||
event_id,
|
||||
display_order,
|
||||
}).returning('id');
|
||||
return res[0]?.id ?? res[0];
|
||||
}
|
||||
|
||||
const getEvent = (eventId) => auth(request(app).get(`/api/admin/categories/event/${eventId}`)).expect(200);
|
||||
|
||||
describe('migration 159 backfill', () => {
|
||||
it('seeds display_order from alphabetical order, scoped per event', async () => {
|
||||
const eventId = await insertEvent('backfill-ev');
|
||||
await insertCat('Reception', { event_id: eventId });
|
||||
await insertCat('Ceremony', { event_id: eventId });
|
||||
await insertCat('Pre-Ceremony', { event_id: eventId });
|
||||
|
||||
// Re-run the migration: addColumn is guarded (no-op); the backfill loop
|
||||
// re-runs and assigns per-scope alphabetical order — what an upgrade does.
|
||||
await require('../../migrations/core/159_add_category_display_order').up(db);
|
||||
|
||||
const evCats = await db('photo_categories').where({ event_id: eventId }).orderBy('display_order', 'asc');
|
||||
expect(evCats.map((c) => c.name)).toEqual(['Ceremony', 'Pre-Ceremony', 'Reception']);
|
||||
expect(evCats.map((c) => c.display_order)).toEqual([1, 2, 3]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('global default order (POST /reorder-global)', () => {
|
||||
it('reverses the global order and every non-customised event follows it', async () => {
|
||||
const before = (await auth(request(app).get('/api/admin/categories/global')).expect(200)).body;
|
||||
expect(before.length).toBeGreaterThan(1);
|
||||
const reversedIds = before.map((c) => c.id).reverse();
|
||||
|
||||
const res = await auth(request(app).post('/api/admin/categories/reorder-global'))
|
||||
.send({ orderedIds: reversedIds })
|
||||
.expect(200);
|
||||
expect(res.body.map((c) => c.id)).toEqual(reversedIds);
|
||||
|
||||
// A fresh event (no override) shows globals in the new global order.
|
||||
const eventId = await insertEvent('follows-global');
|
||||
const globalsInEvent = (await getEvent(eventId)).body.filter((c) => c.is_global).map((c) => c.id);
|
||||
expect(globalsInEvent).toEqual(reversedIds);
|
||||
});
|
||||
});
|
||||
|
||||
describe('per-event override (POST /reorder)', () => {
|
||||
it('pins a custom order for one event without affecting another', async () => {
|
||||
const eventA = await insertEvent('override-a');
|
||||
const eventB = await insertEvent('override-b');
|
||||
const a1 = await insertCat('A-Ceremony', { event_id: eventA });
|
||||
const a2 = await insertCat('A-Reception', { event_id: eventA });
|
||||
|
||||
// Current resolved list for A (globals + A's two categories).
|
||||
const listA = (await getEvent(eventA)).body;
|
||||
// Put A-Reception first, then A-Ceremony, then the globals in their order.
|
||||
const globalsA = listA.filter((c) => c.is_global).map((c) => c.id);
|
||||
const desired = [a2, a1, ...globalsA];
|
||||
|
||||
const res = await auth(request(app).post('/api/admin/categories/reorder'))
|
||||
.send({ event_id: eventA, orderedIds: desired })
|
||||
.expect(200);
|
||||
expect(res.body.map((c) => c.id)).toEqual(desired);
|
||||
// override_position is set on every row for a customised event.
|
||||
expect(res.body.every((c) => c.override_position != null)).toBe(true);
|
||||
|
||||
// Event B is untouched — no override, follows the global default.
|
||||
const listB = (await getEvent(eventB)).body;
|
||||
expect(listB.every((c) => c.override_position == null)).toBe(true);
|
||||
});
|
||||
|
||||
it('accepts global ids but rejects another event’s category', async () => {
|
||||
const eventId = await insertEvent('scope-ev');
|
||||
const own = await insertCat('Own', { event_id: eventId });
|
||||
const global = (await db('photo_categories').where('is_global', 1).first()).id;
|
||||
const foreign = await insertCat('Foreign', { event_id: await insertEvent('other-ev') });
|
||||
|
||||
// A global id is allowed (globals can be arranged per event).
|
||||
await auth(request(app).post('/api/admin/categories/reorder'))
|
||||
.send({ event_id: eventId, orderedIds: [own, global] })
|
||||
.expect(200);
|
||||
|
||||
// A foreign event's category is out of scope.
|
||||
await auth(request(app).post('/api/admin/categories/reorder'))
|
||||
.send({ event_id: eventId, orderedIds: [own, foreign] })
|
||||
.expect(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('reset (DELETE /reorder/:eventId)', () => {
|
||||
it('clears the override and reverts to the global default', async () => {
|
||||
const eventId = await insertEvent('reset-ev');
|
||||
const c1 = await insertCat('R-One', { event_id: eventId });
|
||||
const list = (await getEvent(eventId)).body;
|
||||
const globals = list.filter((c) => c.is_global).map((c) => c.id);
|
||||
|
||||
await auth(request(app).post('/api/admin/categories/reorder'))
|
||||
.send({ event_id: eventId, orderedIds: [c1, ...globals] })
|
||||
.expect(200);
|
||||
expect((await getEvent(eventId)).body.some((c) => c.override_position != null)).toBe(true);
|
||||
|
||||
const res = await auth(request(app).delete(`/api/admin/categories/reorder/${eventId}`)).expect(200);
|
||||
expect(res.body.every((c) => c.override_position == null)).toBe(true);
|
||||
expect(await db('event_category_order').where({ event_id: eventId }).first()).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('event ownership (PR #790 review)', () => {
|
||||
let limitedToken;
|
||||
let foreignEventId;
|
||||
|
||||
beforeAll(async () => {
|
||||
const bcrypt = require('bcrypt');
|
||||
// A non-super_admin role that DOES hold settings.view + settings.edit —
|
||||
// the exact case the review flagged (settings.edit is grantable).
|
||||
const roleRes = await db('roles').insert({ name: 'gallery-mgr', display_name: 'Gallery Mgr' }).returning('id');
|
||||
const roleId = roleRes[0]?.id ?? roleRes[0];
|
||||
const permIds = await db('permissions').whereIn('name', ['settings.view', 'settings.edit']).pluck('id');
|
||||
await db('role_permissions').insert(permIds.map((permission_id) => ({ role_id: roleId, permission_id })));
|
||||
|
||||
const a2 = await db('admin_users').insert({
|
||||
username: 'limited', email: 'limited@example.com',
|
||||
password_hash: await bcrypt.hash('x', 4), role_id: roleId,
|
||||
must_change_password: false, created_at: new Date(),
|
||||
}).returning('id');
|
||||
limitedToken = mintAdminToken(a2[0]?.id ?? a2[0]);
|
||||
|
||||
// An event owned by a DIFFERENT admin (the seeded super_admin).
|
||||
const owner = (await db('admin_users').where({ username: 'tester' }).first()).id;
|
||||
await db('events').insert({
|
||||
event_type: 'wedding', password_hash: 'x',
|
||||
expires_at: new Date(Date.now() + 9e9).toISOString(),
|
||||
is_active: true, is_archived: false, slug: 'owned-ev', share_link: 'owned-ev',
|
||||
event_name: 'Owned', event_date: '2026-01-01', created_by: owner,
|
||||
});
|
||||
foreignEventId = (await db('events').where({ slug: 'owned-ev' }).first()).id;
|
||||
});
|
||||
|
||||
const limitedAuth = (r) => r.set('Authorization', `Bearer ${limitedToken}`);
|
||||
|
||||
it('blocks a non-owner from reading, reordering or resetting another event', async () => {
|
||||
await limitedAuth(request(app).get(`/api/admin/categories/event/${foreignEventId}`)).expect(403);
|
||||
await limitedAuth(request(app).post('/api/admin/categories/reorder'))
|
||||
.send({ event_id: foreignEventId, orderedIds: [1] }).expect(403);
|
||||
await limitedAuth(request(app).delete(`/api/admin/categories/reorder/${foreignEventId}`)).expect(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST / (create) appends to the end of its scope', () => {
|
||||
it('assigns display_order = max + 1 within the event', async () => {
|
||||
const eventId = await insertEvent('append-ev');
|
||||
await insertCat('First', { event_id: eventId, display_order: 1 });
|
||||
await insertCat('Second', { event_id: eventId, display_order: 2 });
|
||||
|
||||
const res = await auth(request(app).post('/api/admin/categories'))
|
||||
.send({ name: 'Third', is_global: false, event_id: eventId })
|
||||
.expect(200);
|
||||
|
||||
expect(res.body.display_order).toBe(3);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,413 +0,0 @@
|
||||
/**
|
||||
* CRM mint-and-send paths — integration tests (#587).
|
||||
*
|
||||
* Pins the three document "mint" flows end-to-end through the real
|
||||
* HTTP → route → service → DB → email-queue → file pipeline:
|
||||
*
|
||||
* 1. POST /api/admin/quotes/:id/send (draft → sent + PDF + token + email)
|
||||
* 2. POST /api/admin/invoices/:id/cancel (issued → cancelled + Storno row)
|
||||
* — the issue spec named this /:id/storno; the real route is
|
||||
* /:id/cancel (invoiceService.cancelInvoice → createStorno).
|
||||
* 3. POST /api/admin/contracts/:id/countersign
|
||||
* (signed_by_customer → fully_signed + stamped PDF + sha256 + email)
|
||||
*
|
||||
* Real SQLite with the full core-migration run (helpers/crmDb), real
|
||||
* pdfkit/pdf-lib rendering — no mock-fs, no network.
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
const request = require('supertest');
|
||||
const {
|
||||
bootCrmDb, seedMinimal, assignAdminRole, mintAdminToken, buildRouteApp,
|
||||
} = require('./helpers/crmDb');
|
||||
|
||||
// Full migration run + cold-requiring pdfService/emailProcessor is slow
|
||||
// under CI load; match the other CRM integration suites.
|
||||
jest.setTimeout(120000);
|
||||
|
||||
const CUSTOMER_EMAIL = 'customer@example.com';
|
||||
|
||||
// 1x1 transparent PNG — smallest valid signature pad output.
|
||||
const SIGNATURE_DATA_URL = 'data:image/png;base64,'
|
||||
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';
|
||||
|
||||
// SQLite round-trips dates inconsistently (epoch ms number, numeric
|
||||
// string, or ISO string) — parse robustly before comparing.
|
||||
const toMillis = (v) => {
|
||||
if (typeof v === 'number') return v;
|
||||
if (typeof v === 'string' && /^\d+$/.test(v)) return Number(v);
|
||||
return Date.parse(v);
|
||||
};
|
||||
|
||||
const sha256 = (buf) => crypto.createHash('sha256').update(buf).digest('hex');
|
||||
|
||||
// Count embedded image XObjects per page via pdf-lib — used to prove BOTH
|
||||
// signature stamps (customer + admin) made it into the final PDF instead of
|
||||
// only asserting file existence/hash (codex review of #850 round 2).
|
||||
async function countImagesPerPage(pdfPath) {
|
||||
const { PDFDocument, PDFName, PDFDict } = require('pdf-lib');
|
||||
const doc = await PDFDocument.load(fs.readFileSync(pdfPath));
|
||||
return doc.getPages().map((page) => {
|
||||
const resources = page.node.Resources();
|
||||
const xobjects = resources && resources.lookupMaybe(PDFName.of('XObject'), PDFDict);
|
||||
if (!xobjects) return 0;
|
||||
let images = 0;
|
||||
for (const [, ref] of xobjects.entries()) {
|
||||
const stream = page.doc.context.lookup(ref);
|
||||
const subtype = stream && stream.dict && stream.dict.get(PDFName.of('Subtype'));
|
||||
if (subtype && subtype.toString() === '/Image') images += 1;
|
||||
}
|
||||
return images;
|
||||
});
|
||||
}
|
||||
|
||||
let db;
|
||||
let cleanup;
|
||||
let tmpDir;
|
||||
// Real (symlink-resolved) storage root — on macOS os.tmpdir() returns
|
||||
// /var/... while the services persist under process.cwd() which
|
||||
// resolves to /private/var/....
|
||||
let storageRoot;
|
||||
let adminId;
|
||||
let customerId;
|
||||
let token;
|
||||
let quoteApp;
|
||||
let invoiceApp;
|
||||
let contractApp;
|
||||
let quoteService;
|
||||
let invoiceService;
|
||||
let contractService;
|
||||
|
||||
const prevCwd = process.cwd();
|
||||
|
||||
const auth = { get Authorization() { return `Bearer ${token}`; } };
|
||||
|
||||
async function enableFlag(key) {
|
||||
const updated = await db('feature_flags').where({ key }).update({ value: true });
|
||||
if (!updated) await db('feature_flags').insert({ key, value: true });
|
||||
}
|
||||
|
||||
// ----- per-path seed helpers -----------------------------------------
|
||||
|
||||
async function seedQuote() {
|
||||
const id = await quoteService.createQuote({
|
||||
customerAccountId: customerId,
|
||||
currency: 'CHF',
|
||||
vatRate: 0,
|
||||
eventName: 'Testshooting',
|
||||
lineItems: [
|
||||
{ position: 1, quantity: 1, description: 'Photo package', unit_price_minor: 150000, discount_percent: 0 },
|
||||
],
|
||||
}, adminId);
|
||||
return id;
|
||||
}
|
||||
|
||||
async function seedIssuedInvoice(status = 'sent') {
|
||||
const { invoiceIds } = await invoiceService.createInvoice({
|
||||
customerAccountId: customerId,
|
||||
currency: 'CHF',
|
||||
vatRate: 7.7,
|
||||
lineItems: [
|
||||
{ position: 1, quantity: 1, description: 'Wedding coverage', unit_price_minor: 200000, discount_percent: 0 },
|
||||
],
|
||||
}, adminId);
|
||||
const id = invoiceIds[0];
|
||||
// Fast-forward past the send step — Storno only applies to issued
|
||||
// documents (sent/paid/overdue), and rendering+sending the original
|
||||
// is covered by the quote path already.
|
||||
await db('invoices').where({ id }).update({
|
||||
status, sent_at: new Date(), updated_at: new Date(),
|
||||
});
|
||||
return db('invoices').where({ id }).first();
|
||||
}
|
||||
|
||||
async function seedCustomerSignedContract() {
|
||||
const id = await contractService.createContract({
|
||||
customerAccountId: customerId,
|
||||
title: 'Fotografie-Vertrag',
|
||||
}, adminId);
|
||||
// Real send + customer-sign flow (codex review of #850): a direct
|
||||
// status UPDATE skipped the customer's signature asset and stamped
|
||||
// PDF, so countersign exercised its unsigned-PDF fallback and a
|
||||
// regression dropping the customer's signature would stay green.
|
||||
const { token } = await contractService.sendContract(id, adminId);
|
||||
await contractService.recordCustomerSignature({
|
||||
token,
|
||||
name: 'Custo Mer',
|
||||
ip: '127.0.0.1',
|
||||
signatureDataUrl: SIGNATURE_DATA_URL,
|
||||
accepted: true,
|
||||
});
|
||||
return db('contracts').where({ id }).first();
|
||||
}
|
||||
|
||||
// ----- suite ----------------------------------------------------------
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup, tmpDir } = await bootCrmDb());
|
||||
// Business-doc PDFs (quotes/invoices/contracts) persist under
|
||||
// `process.cwd()/storage/business-docs/...` — chdir into the temp dir
|
||||
// so every test artifact lands isolated and gets cleaned up.
|
||||
process.chdir(tmpDir);
|
||||
storageRoot = path.join(fs.realpathSync(tmpDir), 'storage', 'business-docs');
|
||||
|
||||
// Fail-fast on the pre-existing logActivity-inside-transaction
|
||||
// deadlock: createContract and createStorno call logActivity() from
|
||||
// inside a knex transaction WITHOUT passing the trx as executor, so
|
||||
// the audit insert tries to grab a second connection from the
|
||||
// single-connection SQLite pool while the trx holds it. In
|
||||
// production that stalls each call for the full 60 s acquire
|
||||
// timeout (the error is then swallowed by logActivity's catch);
|
||||
// here we shrink the timeout so the same swallowed failure costs
|
||||
// 2 s instead of blowing the per-test budget. Behaviour under test
|
||||
// is unchanged — the mint paths themselves never wait on this.
|
||||
db.client.pool.acquireTimeoutMillis = 2000;
|
||||
|
||||
// node-sqlite3 detects Date bind params via `InstanceOf(global.Date)`
|
||||
// against the NATIVE realm's Date — under jest's vm sandbox the
|
||||
// service code's `new Date()` is a different constructor, the check
|
||||
// fails, and the value stringifies to the literal "[object Object]"
|
||||
// (the exact pathology helpers/crmDb.js documents for
|
||||
// createPublicToken). Normalize Date bindings to ISO strings before
|
||||
// they reach the driver so the real service inserts round-trip the
|
||||
// same way they do outside jest.
|
||||
// Patch on the prototype — knex mints transaction clients via
|
||||
// Object.create(prototype), so an instance-level patch would miss
|
||||
// every query issued inside a db.transaction().
|
||||
const clientProto = Object.getPrototypeOf(db.client);
|
||||
const origQuery = clientProto._query;
|
||||
clientProto._query = function patchedQuery(connection, obj) {
|
||||
if (obj && Array.isArray(obj.bindings)) {
|
||||
obj.bindings = obj.bindings.map(
|
||||
(b) => (b && typeof b === 'object' && typeof b.toISOString === 'function' ? b.toISOString() : b),
|
||||
);
|
||||
}
|
||||
return origQuery.call(this, connection, obj);
|
||||
};
|
||||
|
||||
({ adminId, customerId } = await seedMinimal(db));
|
||||
await assignAdminRole(db, adminId, 'super_admin');
|
||||
token = mintAdminToken(adminId);
|
||||
|
||||
// CRM surfaces are feature-flagged; migration 107 seeds them OFF.
|
||||
await enableFlag('quotes');
|
||||
await enableFlag('bills');
|
||||
await enableFlag('contracts');
|
||||
|
||||
quoteService = require('../../src/services/quoteService');
|
||||
invoiceService = require('../../src/services/invoiceService');
|
||||
contractService = require('../../src/services/contractService');
|
||||
|
||||
quoteApp = buildRouteApp('/api/admin/quotes', require('../../src/routes/adminQuotes'));
|
||||
invoiceApp = buildRouteApp('/api/admin/invoices', require('../../src/routes/adminInvoices'));
|
||||
contractApp = buildRouteApp('/api/admin/contracts', require('../../src/routes/adminContracts'));
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => {
|
||||
process.chdir(prevCwd);
|
||||
if (cleanup) await cleanup();
|
||||
});
|
||||
|
||||
describe('POST /api/admin/quotes/:id/send', () => {
|
||||
test('draft quote: 200 → sent + sent_at + PDF on disk + action token + quote_sent email', async () => {
|
||||
const quoteId = await seedQuote();
|
||||
await db('email_queue').del();
|
||||
|
||||
const res = await request(quoteApp)
|
||||
.post(`/api/admin/quotes/${quoteId}/send`)
|
||||
.set(auth);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.sent).toBe(true);
|
||||
expect(res.body.token).toMatch(/^[0-9a-f]{64}$/);
|
||||
|
||||
// DB state
|
||||
const quote = await db('quotes').where({ id: quoteId }).first();
|
||||
expect(quote.status).toBe('sent');
|
||||
expect(quote.sent_at).toBeTruthy();
|
||||
|
||||
// PDF persisted inside the isolated storage root
|
||||
expect(quote.pdf_path).toBeTruthy();
|
||||
expect(quote.pdf_path.startsWith(path.join(storageRoot, 'quote'))).toBe(true);
|
||||
expect(fs.existsSync(quote.pdf_path)).toBe(true);
|
||||
expect(fs.statSync(quote.pdf_path).size).toBeGreaterThan(0);
|
||||
|
||||
// Action token row: right quote, future expiry
|
||||
const tokenRow = await db('quote_action_tokens').where({ token: res.body.token }).first();
|
||||
expect(tokenRow).toBeTruthy();
|
||||
expect(tokenRow.quote_id).toBe(quoteId);
|
||||
expect(toMillis(tokenRow.expires_at)).toBeGreaterThan(Date.now());
|
||||
|
||||
// Email queued to the customer's primary address
|
||||
const emails = await db('email_queue').where({ email_type: 'quote_sent' });
|
||||
expect(emails).toHaveLength(1);
|
||||
expect(emails[0].recipient_email).toBe(CUSTOMER_EMAIL);
|
||||
const emailData = JSON.parse(emails[0].email_data);
|
||||
expect(emailData.quote_number).toBe(quote.quote_number);
|
||||
});
|
||||
|
||||
test('already-sent quote: 409 (spec said 400; service throws 409)', async () => {
|
||||
const quoteId = await seedQuote();
|
||||
await request(quoteApp).post(`/api/admin/quotes/${quoteId}/send`).set(auth).expect(200);
|
||||
|
||||
const res = await request(quoteApp)
|
||||
.post(`/api/admin/quotes/${quoteId}/send`)
|
||||
.set(auth);
|
||||
expect(res.status).toBe(409);
|
||||
expect(res.body.error).toMatch(/cannot send a quote with status 'sent'/i);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/admin/invoices/:id/cancel (Storno mint)', () => {
|
||||
test('sent invoice: original cancelled, Storno row minted with negated totals + lineage', async () => {
|
||||
const original = await seedIssuedInvoice('sent');
|
||||
await db('email_queue').del();
|
||||
|
||||
const res = await request(invoiceApp)
|
||||
.post(`/api/admin/invoices/${original.id}/cancel`)
|
||||
.set(auth);
|
||||
// Route responds via successResponse default — 200, not the 201
|
||||
// the issue spec assumed.
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.cancelled).toBe(true);
|
||||
expect(res.body.stornoId).toBeGreaterThan(0);
|
||||
|
||||
const storno = await db('invoices').where({ id: res.body.stornoId }).first();
|
||||
expect(storno.kind).toBe('storno');
|
||||
expect(storno.cancels_invoice_id).toBe(original.id);
|
||||
expect(storno.deal_uuid).toBe(original.deal_uuid);
|
||||
|
||||
// Negated amounts
|
||||
expect(storno.net_amount_minor).toBe(-original.net_amount_minor);
|
||||
expect(storno.vat_amount_minor).toBe(-original.vat_amount_minor);
|
||||
expect(storno.total_amount_minor).toBe(-original.total_amount_minor);
|
||||
|
||||
// Freshly sequenced number from the same series
|
||||
expect(typeof storno.invoice_number).toBe('string');
|
||||
expect(storno.invoice_number.length).toBeGreaterThan(0);
|
||||
expect(storno.invoice_number).not.toBe(original.invoice_number);
|
||||
|
||||
// Line items snapshotted onto the Storno
|
||||
const originalItems = await db('invoice_line_items').where({ invoice_id: original.id });
|
||||
const stornoItems = await db('invoice_line_items').where({ invoice_id: storno.id });
|
||||
expect(stornoItems).toHaveLength(originalItems.length);
|
||||
|
||||
// Original flipped + back-linked
|
||||
const refreshed = await db('invoices').where({ id: original.id }).first();
|
||||
expect(refreshed.status).toBe('cancelled');
|
||||
expect(refreshed.cancellation_storno_id).toBe(storno.id);
|
||||
|
||||
// sendStorno side effects (codex review of #850): cancelInvoice
|
||||
// swallows a sendStorno failure by design, so without these
|
||||
// assertions a broken render/persist/queue leg would stay green.
|
||||
const sentStorno = await db('invoices').where({ id: storno.id }).first();
|
||||
expect(sentStorno.status).toBe('sent');
|
||||
expect(sentStorno.pdf_path).toBeTruthy();
|
||||
expect(fs.existsSync(sentStorno.pdf_path)).toBe(true);
|
||||
const stornoEmails = await db('email_queue').where({ email_type: 'storno_issued' });
|
||||
expect(stornoEmails.length).toBeGreaterThanOrEqual(1);
|
||||
expect(stornoEmails[0].recipient_email).toBe(CUSTOMER_EMAIL);
|
||||
});
|
||||
|
||||
test('paid invoice can be cancelled via Storno too (refund document leg)', async () => {
|
||||
const original = await seedIssuedInvoice('paid');
|
||||
|
||||
const res = await request(invoiceApp)
|
||||
.post(`/api/admin/invoices/${original.id}/cancel`)
|
||||
.set(auth);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.stornoId).toBeGreaterThan(0);
|
||||
|
||||
const refreshed = await db('invoices').where({ id: original.id }).first();
|
||||
expect(refreshed.status).toBe('cancelled');
|
||||
});
|
||||
|
||||
test('already-cancelled invoice: 409 ALREADY_CANCELLED', async () => {
|
||||
const original = await seedIssuedInvoice('sent');
|
||||
await request(invoiceApp).post(`/api/admin/invoices/${original.id}/cancel`).set(auth).expect(200);
|
||||
|
||||
const res = await request(invoiceApp)
|
||||
.post(`/api/admin/invoices/${original.id}/cancel`)
|
||||
.set(auth);
|
||||
expect(res.status).toBe(409);
|
||||
expect(res.body.code).toBe('ALREADY_CANCELLED');
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/admin/contracts/:id/countersign', () => {
|
||||
test('customer-signed contract: 200 → fully_signed + stamped PDF + sha256 + signature asset + email with attachment', async () => {
|
||||
const contract = await seedCustomerSignedContract();
|
||||
await db('email_queue').del();
|
||||
|
||||
const res = await request(contractApp)
|
||||
.post(`/api/admin/contracts/${contract.id}/countersign`)
|
||||
.set(auth)
|
||||
.send({ name: 'Admin Tester', signatureDataUrl: SIGNATURE_DATA_URL });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.status).toBe('fully_signed');
|
||||
|
||||
const row = await db('contracts').where({ id: contract.id }).first();
|
||||
expect(row.status).toBe('fully_signed');
|
||||
expect(row.signed_admin_name).toBe('Admin Tester');
|
||||
expect(row.signed_by_admin_at).toBeTruthy();
|
||||
|
||||
// The customer's own signature (from the real sign flow in the seed)
|
||||
// must survive countersigning — layered, not replaced.
|
||||
expect(row.signed_customer_signature_path).toBeTruthy();
|
||||
expect(fs.existsSync(row.signed_customer_signature_path)).toBe(true);
|
||||
expect(row.signed_customer_name).toBe('Custo Mer');
|
||||
|
||||
// Admin signature image persisted under the storage root
|
||||
expect(row.signed_admin_signature_path).toBeTruthy();
|
||||
expect(row.signed_admin_signature_path.startsWith(
|
||||
path.join(storageRoot, 'contract', 'signatures'),
|
||||
)).toBe(true);
|
||||
expect(fs.existsSync(row.signed_admin_signature_path)).toBe(true);
|
||||
|
||||
// Stamped, fully-signed PDF written and hashed. The issue spec
|
||||
// called this `integrity_hash`; the real column is
|
||||
// `signed_pdf_sha256` (plus `pdf_sha256` for the unsigned base).
|
||||
expect(row.signed_pdf_render_failed_at).toBeFalsy();
|
||||
expect(row.signed_pdf_path).toBeTruthy();
|
||||
expect(fs.existsSync(row.signed_pdf_path)).toBe(true);
|
||||
expect(row.signed_pdf_sha256).toMatch(/^[0-9a-f]{64}$/);
|
||||
expect(sha256(fs.readFileSync(row.signed_pdf_path))).toBe(row.signed_pdf_sha256);
|
||||
|
||||
// BOTH stamps must be embedded in the final document — a regression
|
||||
// stamping the admin onto the unsigned base PDF would keep every
|
||||
// path/hash assertion above green (codex review of #850 round 2).
|
||||
const imagesPerPage = await countImagesPerPage(row.signed_pdf_path);
|
||||
const maxImagesOnAPage = Math.max(...imagesPerPage);
|
||||
expect(maxImagesOnAPage).toBeGreaterThanOrEqual(2);
|
||||
|
||||
// contract_fully_signed email to the customer's primary address,
|
||||
// carrying the signed PDF as attachment (plus the audit cert).
|
||||
const emails = await db('email_queue').where({ email_type: 'contract_fully_signed' });
|
||||
const customerCopy = emails.find((e) => e.recipient_email === CUSTOMER_EMAIL);
|
||||
expect(customerCopy).toBeTruthy();
|
||||
const emailData = JSON.parse(customerCopy.email_data);
|
||||
expect(emailData.contract_number).toBe(contract.contract_number);
|
||||
expect(Array.isArray(emailData.attachments)).toBe(true);
|
||||
const pdfAttachment = emailData.attachments.find(
|
||||
(a) => a.filename === `${contract.contract_number}-signed.pdf`,
|
||||
);
|
||||
expect(pdfAttachment).toBeTruthy();
|
||||
expect(pdfAttachment.contentType).toBe('application/pdf');
|
||||
expect(fs.existsSync(pdfAttachment.contentPath)).toBe(true);
|
||||
});
|
||||
|
||||
test('draft contract: 409 — countersign requires sent/signed_by_customer', async () => {
|
||||
const draftId = await contractService.createContract({
|
||||
customerAccountId: customerId,
|
||||
title: 'Noch nicht versendet',
|
||||
}, adminId);
|
||||
|
||||
const res = await request(contractApp)
|
||||
.post(`/api/admin/contracts/${draftId}/countersign`)
|
||||
.set(auth)
|
||||
.send({ name: 'Admin Tester' });
|
||||
expect(res.status).toBe(409);
|
||||
expect(res.body.error).toMatch(/cannot counter-sign a contract with status 'draft'/i);
|
||||
});
|
||||
});
|
||||
@@ -1,256 +0,0 @@
|
||||
/**
|
||||
* Download resolutions (#858).
|
||||
*
|
||||
* Pins the contracts that are easy to break later:
|
||||
*
|
||||
* - the global → per-event cascade, including NULL = inherit
|
||||
* - the picker never offers a size ABOVE the standard (a photographer who
|
||||
* lowers the standard is not silently handing out full-res), and 'Original'
|
||||
* only reappears when the admin explicitly allows it
|
||||
* - `fit: 'inside'` + no-upscaling resize semantics, which is exactly what
|
||||
* the requester asked for on the issue
|
||||
* - a guest-supplied resolution is validated against the policy rather than
|
||||
* trusted
|
||||
*/
|
||||
|
||||
const sharp = require('sharp');
|
||||
|
||||
const { bootCrmDb, seedMinimal } = require('./helpers/crmDb');
|
||||
|
||||
// Both modules under test pull in src/database/db.js transitively. bootCrmDb
|
||||
// only works when it runs BEFORE the first require of db.js (it sets
|
||||
// TEST_DATABASE_PATH, which knexfile reads at module-init time), so these are
|
||||
// required lazily in beforeAll rather than at module scope — otherwise knex
|
||||
// binds to the shared default SQLite file and every run after the first one
|
||||
// fails with "table `migrations` already exists".
|
||||
let resolveEventDownloadPolicy;
|
||||
let pickRequestedResolution;
|
||||
let parseResolution;
|
||||
let invalidateDownloadGlobals;
|
||||
let resizeToBox;
|
||||
|
||||
describe('Download resolutions (#858)', () => {
|
||||
let db;
|
||||
let cleanup;
|
||||
|
||||
const setGlobal = async (key, value) => {
|
||||
await db('app_settings').where({ setting_key: key }).del();
|
||||
await db('app_settings').insert({
|
||||
setting_key: key,
|
||||
setting_value: JSON.stringify(value),
|
||||
setting_type: 'download',
|
||||
updated_at: new Date().toISOString(),
|
||||
});
|
||||
invalidateDownloadGlobals();
|
||||
};
|
||||
|
||||
const PRESETS = [
|
||||
{ label: 'Large', width: 3000, height: 2000 },
|
||||
{ label: 'Medium', width: 1500, height: 1000 },
|
||||
{ label: 'Small', width: 800, height: 600 },
|
||||
];
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
await seedMinimal(db);
|
||||
|
||||
({
|
||||
resolveEventDownloadPolicy,
|
||||
pickRequestedResolution,
|
||||
parseResolution,
|
||||
invalidateDownloadGlobals,
|
||||
} = require('../../src/utils/downloadResolutions'));
|
||||
({ resizeToBox } = require('../../src/services/imageProcessor'));
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => {
|
||||
if (cleanup) await cleanup();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await setGlobal('download_resolutions', PRESETS);
|
||||
await setGlobal('download_standard_resolution', 'original');
|
||||
await setGlobal('download_resolution_picker_enabled', false);
|
||||
await setGlobal('download_allow_original', false);
|
||||
});
|
||||
|
||||
describe('cascade', () => {
|
||||
it('inherits the global standard when the event has no override', async () => {
|
||||
await setGlobal('download_standard_resolution', '1500x1000');
|
||||
const policy = await resolveEventDownloadPolicy({ download_standard_resolution: null });
|
||||
expect(policy.standard).toBe('1500x1000');
|
||||
expect(policy.standardBox).toEqual({ width: 1500, height: 1000 });
|
||||
});
|
||||
|
||||
it('lets an event override the global standard', async () => {
|
||||
await setGlobal('download_standard_resolution', '1500x1000');
|
||||
const policy = await resolveEventDownloadPolicy({ download_standard_resolution: '800x600' });
|
||||
expect(policy.standard).toBe('800x600');
|
||||
});
|
||||
|
||||
it('treats a NULL picker flag as inherit and an explicit false as override', async () => {
|
||||
await setGlobal('download_resolution_picker_enabled', true);
|
||||
expect((await resolveEventDownloadPolicy({ download_resolution_picker_enabled: null })).pickerEnabled).toBe(true);
|
||||
expect((await resolveEventDownloadPolicy({ download_resolution_picker_enabled: false })).pickerEnabled).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('choice list', () => {
|
||||
it('never offers a size larger than the standard', async () => {
|
||||
await setGlobal('download_standard_resolution', '1500x1000');
|
||||
const { choices } = await resolveEventDownloadPolicy({});
|
||||
expect(choices.map((c) => c.id)).toEqual(['1500x1000', '800x600']);
|
||||
// The regression that matters: 3000x2000 must not be reachable.
|
||||
expect(choices.some((c) => c.id === '3000x2000')).toBe(false);
|
||||
});
|
||||
|
||||
it('bounds EACH dimension, not the pixel area (codex review round 2)', async () => {
|
||||
// 2000x700 is 1.4MP — under 1500x1000's 1.5MP — so an area comparison
|
||||
// would offer it and hand back a 2000px-wide file despite a 1500px cap.
|
||||
await setGlobal('download_resolutions', [
|
||||
...PRESETS,
|
||||
{ label: 'Wide', width: 2000, height: 700 },
|
||||
]);
|
||||
await setGlobal('download_standard_resolution', '1500x1000');
|
||||
const { choices } = await resolveEventDownloadPolicy({});
|
||||
expect(choices.some((c) => c.id === '2000x700')).toBe(false);
|
||||
});
|
||||
|
||||
it('omits Original when the standard is capped and the admin has not allowed it', async () => {
|
||||
await setGlobal('download_standard_resolution', '1500x1000');
|
||||
const { choices } = await resolveEventDownloadPolicy({});
|
||||
expect(choices.some((c) => c.id === 'original')).toBe(false);
|
||||
});
|
||||
|
||||
it('re-adds Original when the admin explicitly allows it', async () => {
|
||||
await setGlobal('download_standard_resolution', '1500x1000');
|
||||
await setGlobal('download_allow_original', true);
|
||||
const { choices } = await resolveEventDownloadPolicy({});
|
||||
expect(choices[0].id).toBe('original');
|
||||
});
|
||||
|
||||
it('offers Original when the standard already is original', async () => {
|
||||
const { choices } = await resolveEventDownloadPolicy({});
|
||||
expect(choices[0].id).toBe('original');
|
||||
expect(choices.map((c) => c.id)).toContain('3000x2000');
|
||||
});
|
||||
});
|
||||
|
||||
describe('request validation', () => {
|
||||
it('falls back to the standard when nothing is requested', async () => {
|
||||
await setGlobal('download_standard_resolution', '1500x1000');
|
||||
const policy = await resolveEventDownloadPolicy({});
|
||||
expect(pickRequestedResolution(policy, undefined)).toBe('1500x1000');
|
||||
});
|
||||
|
||||
it('refuses any explicit request while the picker is off', async () => {
|
||||
const policy = await resolveEventDownloadPolicy({});
|
||||
expect(policy.pickerEnabled).toBe(false);
|
||||
expect(pickRequestedResolution(policy, '800x600')).toBeNull();
|
||||
});
|
||||
|
||||
it('refuses a size that is not on the offered list', async () => {
|
||||
await setGlobal('download_resolution_picker_enabled', true);
|
||||
await setGlobal('download_standard_resolution', '1500x1000');
|
||||
const policy = await resolveEventDownloadPolicy({});
|
||||
// Above the standard → not offered → rejected rather than silently served.
|
||||
expect(pickRequestedResolution(policy, '3000x2000')).toBeNull();
|
||||
expect(pickRequestedResolution(policy, '9999x9999')).toBeNull();
|
||||
expect(pickRequestedResolution(policy, '800x600')).toBe('800x600');
|
||||
});
|
||||
|
||||
it('parses only well-formed resolution ids', () => {
|
||||
expect(parseResolution('original')).toBeNull();
|
||||
expect(parseResolution(null)).toBeNull();
|
||||
expect(parseResolution('abc')).toBeNull();
|
||||
expect(parseResolution('0x0')).toBeNull();
|
||||
expect(parseResolution('1500x1000')).toEqual({ width: 1500, height: 1000 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('job dedup identity (codex review round 1)', () => {
|
||||
// The leak this pins: a PIN client's archive contains hidden photos. If the
|
||||
// dedup key ignored the visibility scope, a guest asking for the same size
|
||||
// would be handed the client's job token — and the delivery route only
|
||||
// checked the event id.
|
||||
let jobService;
|
||||
|
||||
beforeAll(() => {
|
||||
jobService = require('../../src/services/downloadJobService');
|
||||
});
|
||||
|
||||
it('separates client and guest archives of the same size and photo set', () => {
|
||||
const guest = jobService.dedupKey(1, '1500x1000', [1, 2, 3], false, 'public');
|
||||
const client = jobService.dedupKey(1, '1500x1000', [1, 2, 3], false, 'hidden');
|
||||
expect(guest).not.toBe(client);
|
||||
});
|
||||
|
||||
it('keys on the RESOLVED photo set, so a stale archive is not reused', () => {
|
||||
const before = jobService.dedupKey(1, '1500x1000', [1, 2, 3], false, 'public');
|
||||
const afterUpload = jobService.dedupKey(1, '1500x1000', [1, 2, 3, 4], false, 'public');
|
||||
const afterHide = jobService.dedupKey(1, '1500x1000', [1, 2], false, 'public');
|
||||
expect(new Set([before, afterUpload, afterHide]).size).toBe(3);
|
||||
});
|
||||
|
||||
it('is order-independent for the same set', () => {
|
||||
expect(jobService.dedupKey(1, 'original', [3, 1, 2], true, 'public'))
|
||||
.toBe(jobService.dedupKey(1, 'original', [1, 2, 3], true, 'public'));
|
||||
});
|
||||
|
||||
it('maps access levels onto the two visibility scopes', () => {
|
||||
expect(jobService.visibilityScopeFor('client')).toBe('hidden');
|
||||
expect(jobService.visibilityScopeFor('guest')).toBe('public');
|
||||
expect(jobService.visibilityScopeFor(undefined)).toBe('public');
|
||||
});
|
||||
});
|
||||
|
||||
describe('resize semantics', () => {
|
||||
const make = (w, h) => sharp({
|
||||
create: { width: w, height: h, channels: 3, background: { r: 10, g: 100, b: 200 } },
|
||||
}).jpeg().toBuffer();
|
||||
|
||||
const box = { width: 1500, height: 1000 };
|
||||
|
||||
it('fits a 3:2 photo exactly into a 3:2 box', async () => {
|
||||
const out = await sharp(await resizeToBox(await make(6000, 4000), box)).metadata();
|
||||
expect([out.width, out.height]).toEqual([1500, 1000]);
|
||||
});
|
||||
|
||||
it('treats the box as an "up to" bound for other aspect ratios', async () => {
|
||||
// Portrait: height is the binding edge, width comes out smaller.
|
||||
const portrait = await sharp(await resizeToBox(await make(4000, 6000), box)).metadata();
|
||||
expect(portrait.height).toBe(1000);
|
||||
expect(portrait.width).toBeLessThan(1500);
|
||||
|
||||
const fourThree = await sharp(await resizeToBox(await make(4000, 3000), box)).metadata();
|
||||
expect(fourThree.height).toBe(1000);
|
||||
expect(fourThree.width).toBeLessThan(1500);
|
||||
});
|
||||
|
||||
it('never upscales an image already smaller than the box', async () => {
|
||||
const out = await sharp(await resizeToBox(await make(800, 600), box)).metadata();
|
||||
expect([out.width, out.height]).toEqual([800, 600]);
|
||||
});
|
||||
|
||||
it('passes the buffer through untouched for the original size', async () => {
|
||||
const src = await make(4000, 3000);
|
||||
expect(await resizeToBox(src, null)).toBe(src);
|
||||
});
|
||||
|
||||
it('keeps the source format so the filename and mime type stay honest', async () => {
|
||||
// A .gif re-encoded as JPEG would ship mislabelled bytes, since the
|
||||
// download routes keep the original filename and mime type.
|
||||
const gif = await sharp({
|
||||
create: { width: 4000, height: 3000, channels: 3, background: { r: 1, g: 2, b: 3 } },
|
||||
}).gif().toBuffer();
|
||||
const out = await sharp(await resizeToBox(gif, box)).metadata();
|
||||
expect(out.format).toBe('gif');
|
||||
expect(out.width).toBe(1333);
|
||||
});
|
||||
|
||||
it('returns the input rather than throwing on an undecodable source', async () => {
|
||||
const junk = Buffer.from('not an image');
|
||||
expect(await resizeToBox(junk, box)).toBe(junk);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,50 +0,0 @@
|
||||
/**
|
||||
* Catalog-driven event-type defaults (#800 follow-up).
|
||||
*
|
||||
* The contract→event conversion used to hardcode `event_type: 'wedding'` and
|
||||
* the v1 API validated against a fixed whitelist. Both now follow the live
|
||||
* event_types catalog; these tests pin the shared resolver.
|
||||
*/
|
||||
|
||||
const { bootCrmDb } = require('./helpers/crmDb');
|
||||
|
||||
describe('resolveDefaultEventType follows the catalog', () => {
|
||||
let db;
|
||||
let cleanup;
|
||||
let eventTypeService;
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
// Require AFTER bootCrmDb so the service shares this db instance
|
||||
// (see crmDb.js — a second knex pool on one SQLite file deadlocks).
|
||||
eventTypeService = require('../../src/services/eventTypeService');
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => {
|
||||
if (cleanup) await cleanup();
|
||||
});
|
||||
|
||||
it("prefers the 'other' catch-all while it is active", async () => {
|
||||
expect(await eventTypeService.resolveDefaultEventType()).toBe('other');
|
||||
});
|
||||
|
||||
it('falls over to the first active type when other is deactivated', async () => {
|
||||
const other = await db('event_types').where({ slug_prefix: 'other' }).first();
|
||||
await db('event_types').where({ id: other.id }).update({ is_active: 0 });
|
||||
|
||||
const resolved = await eventTypeService.resolveDefaultEventType();
|
||||
expect(resolved).not.toBe('other');
|
||||
expect(await db('event_types').where({ slug_prefix: resolved }).first()).toBeTruthy();
|
||||
|
||||
await db('event_types').where({ id: other.id }).update({ is_active: 1 });
|
||||
});
|
||||
|
||||
it("returns the literal 'other' only for an empty catalog", async () => {
|
||||
const rows = await db('event_types').select('*');
|
||||
await db('event_types').del();
|
||||
|
||||
expect(await eventTypeService.resolveDefaultEventType()).toBe('other');
|
||||
|
||||
await db('event_types').insert(rows);
|
||||
});
|
||||
});
|
||||
@@ -1,133 +0,0 @@
|
||||
/**
|
||||
* Setup-window event type deletion (#800).
|
||||
*
|
||||
* The first-run setup wizard may delete the seeded SYSTEM event types —
|
||||
* but ONLY while the `setup_wizard_completed` flag is unset (migration 161
|
||||
* seeds it false on a fresh install, true when an admin already exists).
|
||||
* These tests pin the whole contract:
|
||||
*
|
||||
* - fresh install → flag false → system types deletable (in-use checks
|
||||
* still apply), and the per-type reminder template goes with the type
|
||||
* - reminder-template self-heal does NOT resurrect templates for slugs
|
||||
* that no longer exist in the catalog
|
||||
* - after markSetupWizardCompleted() → system deletion is refused again
|
||||
*/
|
||||
|
||||
const { bootCrmDb } = require('./helpers/crmDb');
|
||||
|
||||
describe('event type deletion during the setup window (#800)', () => {
|
||||
let db;
|
||||
let cleanup;
|
||||
let eventTypeService;
|
||||
let setupService;
|
||||
let ensureEventReminderTemplatesSeeded;
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
// Require AFTER bootCrmDb so every service shares this db instance
|
||||
// (see crmDb.js — a second knex pool on one SQLite file deadlocks).
|
||||
eventTypeService = require('../../src/services/eventTypeService');
|
||||
setupService = require('../../src/services/setupService');
|
||||
({ ensureEventReminderTemplatesSeeded } = require('../../src/services/eventReminderTemplates'));
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => {
|
||||
if (cleanup) await cleanup();
|
||||
});
|
||||
|
||||
it('migration 161 seeds the flag false on a fresh (admin-less) install', async () => {
|
||||
const row = await db('app_settings').where({ setting_key: 'setup_wizard_completed' }).first();
|
||||
expect(row).toBeTruthy();
|
||||
expect(JSON.parse(row.setting_value)).toBe(false);
|
||||
expect(await setupService.isSetupWizardCompleted()).toBe(false);
|
||||
});
|
||||
|
||||
it('refuses to delete a system type that events already use, even in the window', async () => {
|
||||
const corporate = await db('event_types').where({ slug_prefix: 'corporate' }).first();
|
||||
await db('events').insert({
|
||||
slug: 'corporate-test-2026-01-01',
|
||||
event_name: 'Test',
|
||||
event_type: 'corporate',
|
||||
event_date: '2026-01-01',
|
||||
host_email: 'host@example.com',
|
||||
admin_email: 'admin@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: 'share-corporate-test',
|
||||
expires_at: new Date(Date.now() + 86400000),
|
||||
});
|
||||
|
||||
await expect(eventTypeService.deleteEventType(corporate.id))
|
||||
.rejects.toMatchObject({ code: 'IN_USE' });
|
||||
});
|
||||
|
||||
it('deletes an unused system type in the window, taking its reminder template along', async () => {
|
||||
// Seed the per-type reminder templates first so there is something to clean up.
|
||||
await ensureEventReminderTemplatesSeeded(db);
|
||||
expect(await db('email_templates').where({ template_key: 'event_reminder_wedding' }).first()).toBeTruthy();
|
||||
|
||||
const wedding = await db('event_types').where({ slug_prefix: 'wedding' }).first();
|
||||
expect(wedding.is_system).toBeTruthy();
|
||||
|
||||
const result = await eventTypeService.deleteEventType(wedding.id);
|
||||
expect(result.success).toBe(true);
|
||||
|
||||
expect(await db('event_types').where({ slug_prefix: 'wedding' }).first()).toBeFalsy();
|
||||
expect(await db('email_templates').where({ template_key: 'event_reminder_wedding' }).first()).toBeFalsy();
|
||||
|
||||
// The deleted slug must NOT stay creatable through the legacy fallback —
|
||||
// the live catalog is authoritative while it has rows.
|
||||
expect(await eventTypeService.isValidEventType('wedding')).toBe(false);
|
||||
expect(await eventTypeService.isValidEventType('birthday')).toBe(true);
|
||||
});
|
||||
|
||||
it('does not resurrect reminder templates for deleted types on the next self-heal pass', async () => {
|
||||
// The seeder caches success per process — reset the module to force a
|
||||
// genuine second pass, exactly what a backend restart would run.
|
||||
jest.resetModules();
|
||||
const fresh = require('../../src/services/eventReminderTemplates');
|
||||
await fresh.ensureEventReminderTemplatesSeeded(db);
|
||||
|
||||
expect(await db('email_templates').where({ template_key: 'event_reminder_wedding' }).first()).toBeFalsy();
|
||||
// Types still in the catalog keep their templates.
|
||||
expect(await db('email_templates').where({ template_key: 'event_reminder_birthday' }).first()).toBeTruthy();
|
||||
expect(await db('email_templates').where({ template_key: 'event_reminder_default' }).first()).toBeTruthy();
|
||||
});
|
||||
|
||||
it('re-locks system types once the wizard is marked complete', async () => {
|
||||
await setupService.markSetupWizardCompleted();
|
||||
expect(await setupService.isSetupWizardCompleted()).toBe(true);
|
||||
|
||||
const birthday = await db('event_types').where({ slug_prefix: 'birthday' }).first();
|
||||
await expect(eventTypeService.deleteEventType(birthday.id))
|
||||
.rejects.toMatchObject({ code: 'SYSTEM_TYPE' });
|
||||
|
||||
// Custom (non-system) types remain deletable as before.
|
||||
const custom = await eventTypeService.createEventType({ name: 'Family', slug_prefix: 'family' });
|
||||
const result = await eventTypeService.deleteEventType(custom.id);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('fails closed when the completion marker row is missing', async () => {
|
||||
// A portable-backup restore can replace app_settings with a set that
|
||||
// predates migration 161 (which will not rerun) — absence must mean
|
||||
// "configured instance", never an open deletion window.
|
||||
await db('app_settings').where({ setting_key: 'setup_wizard_completed' }).del();
|
||||
expect(await setupService.isSetupWizardCompleted()).toBe(true);
|
||||
await setupService.markSetupWizardCompleted();
|
||||
});
|
||||
|
||||
it('refuses to delete the last remaining event type', async () => {
|
||||
// Reduce the catalog to a single custom type via direct db writes (the
|
||||
// service paths are already covered above), then hit the guard.
|
||||
const solo = await eventTypeService.createEventType({ name: 'Solo', slug_prefix: 'solo' });
|
||||
await db('events').del();
|
||||
await db('event_types').whereNot('id', solo.id).del();
|
||||
|
||||
await expect(eventTypeService.deleteEventType(solo.id))
|
||||
.rejects.toMatchObject({ code: 'LAST_TYPE' });
|
||||
|
||||
// Deactivating it would empty the ACTIVE catalog just the same.
|
||||
await expect(eventTypeService.updateEventType(solo.id, { is_active: false }))
|
||||
.rejects.toMatchObject({ code: 'LAST_ACTIVE' });
|
||||
});
|
||||
});
|
||||
@@ -1,121 +0,0 @@
|
||||
/**
|
||||
* Gallery password invisible-Unicode fallback (#654).
|
||||
*
|
||||
* Passwords relayed through chat apps (Instagram DMs especially) pick up
|
||||
* invisible characters on copy-paste — zero-width space/joiners, word
|
||||
* joiner, BOM, soft hyphen — which fail the byte-exact bcrypt compare and
|
||||
* surface as "incorrect password" for a correct password. The verify route
|
||||
* retries the compare with those characters stripped, in the SAME request,
|
||||
* so the fallback costs no reCAPTCHA token and no failed-attempt quota.
|
||||
*
|
||||
* Pins the contract:
|
||||
* - exact submitted bytes always win first, so stored passwords that
|
||||
* legitimately contain these characters (e.g. ZWJ emoji sequences)
|
||||
* keep working
|
||||
* - paste artifacts (mid-string ZWSP, leading BOM, trailing space) are
|
||||
* rescued by the sanitized fallback compare
|
||||
* - the fallback never invents a match (missing ZWJ still 401s), and a
|
||||
* rescued login records no failed attempt
|
||||
*/
|
||||
|
||||
const request = require('supertest');
|
||||
const express = require('express');
|
||||
const cookieParser = require('cookie-parser');
|
||||
const bcrypt = require('bcrypt');
|
||||
|
||||
const { bootCrmDb, seedMinimal } = require('./helpers/crmDb');
|
||||
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'sanitize-test-secret';
|
||||
|
||||
const PLAIN_SLUG = 'sanitize-plain-event';
|
||||
const ZWJ_SLUG = 'sanitize-zwj-event';
|
||||
const PLAIN_PASSWORD = 'wedding2026';
|
||||
// Stored password legitimately containing a ZWJ emoji sequence.
|
||||
const ZWJ_PASSWORD = 'Family\u{1F468}\u200D\u{1F469}Aa1';
|
||||
|
||||
describe('gallery/verify invisible-Unicode fallback (#654)', () => {
|
||||
let db;
|
||||
let cleanup;
|
||||
let app;
|
||||
|
||||
const makeEvent = async (slug, password) => {
|
||||
const inserted = await db('events').insert({
|
||||
slug,
|
||||
event_type: 'wedding',
|
||||
event_name: `Sanitize ${slug}`,
|
||||
event_date: '2026-08-01',
|
||||
host_email: 'host@example.com',
|
||||
admin_email: 'admin@example.com',
|
||||
password_hash: await bcrypt.hash(password, 4),
|
||||
share_link: `/gallery/${slug}/share`,
|
||||
share_token: `${slug}-share`,
|
||||
expires_at: new Date(Date.now() + 7 * 24 * 3600 * 1000).toISOString(),
|
||||
is_active: 1,
|
||||
is_archived: 0,
|
||||
is_draft: 0,
|
||||
created_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
return inserted[0]?.id ?? inserted[0];
|
||||
};
|
||||
let plainEventId;
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
await seedMinimal(db);
|
||||
plainEventId = await makeEvent(PLAIN_SLUG, PLAIN_PASSWORD);
|
||||
await makeEvent(ZWJ_SLUG, ZWJ_PASSWORD);
|
||||
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use(cookieParser());
|
||||
app.use('/api/auth', require('../../src/routes/auth'));
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => {
|
||||
if (cleanup) await cleanup();
|
||||
});
|
||||
|
||||
const verify = (slug, password) =>
|
||||
request(app).post('/api/auth/gallery/verify').send({ slug, password });
|
||||
|
||||
it('accepts the exact password', async () => {
|
||||
const res = await verify(PLAIN_SLUG, PLAIN_PASSWORD);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.token).toBeTruthy();
|
||||
});
|
||||
|
||||
it('rescues a mid-string zero-width space from chat-app copy-paste', async () => {
|
||||
const res = await verify(PLAIN_SLUG, 'wedding\u200B2026');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.token).toBeTruthy();
|
||||
});
|
||||
|
||||
it('rescues leading BOM + trailing space paste artifacts', async () => {
|
||||
const res = await verify(PLAIN_SLUG, `\uFEFF${PLAIN_PASSWORD} `);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.token).toBeTruthy();
|
||||
});
|
||||
|
||||
it('records no login_fail for a rescued login (single-request fallback)', async () => {
|
||||
await verify(PLAIN_SLUG, 'wedding\u200B2026').expect(200);
|
||||
const failed = await db('access_logs')
|
||||
.where({ event_id: plainEventId, action: 'login_fail' });
|
||||
expect(failed).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('still accepts a stored password that legitimately contains a ZWJ', async () => {
|
||||
const res = await verify(ZWJ_SLUG, ZWJ_PASSWORD);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.token).toBeTruthy();
|
||||
});
|
||||
|
||||
it('does not invent a match when the ZWJ is missing from the input', async () => {
|
||||
const res = await verify(ZWJ_SLUG, 'Family\u{1F468}\u{1F469}Aa1');
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('rejects a plain wrong password', async () => {
|
||||
const res = await verify(PLAIN_SLUG, 'not-the-password');
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
});
|
||||
@@ -1,167 +0,0 @@
|
||||
/**
|
||||
* Minimal in-process OIDC provider for integration tests (#798).
|
||||
*
|
||||
* Serves just enough of the spec for openid-client's full validation to
|
||||
* pass: discovery, JWKS (RS256), authorization endpoint (immediate redirect,
|
||||
* no login UI), and token endpoint (authorization_code + PKCE). Claims for
|
||||
* the next login are scripted per test via `setNextUser()`.
|
||||
*
|
||||
* Runs on an ephemeral localhost port over plain http — the service allows
|
||||
* that in NODE_ENV=test only.
|
||||
*/
|
||||
|
||||
const http = require('http');
|
||||
const crypto = require('crypto');
|
||||
const { URL } = require('url');
|
||||
|
||||
function b64url(input) {
|
||||
return Buffer.from(input).toString('base64url');
|
||||
}
|
||||
|
||||
class MockOidcProvider {
|
||||
constructor() {
|
||||
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048 });
|
||||
this.privateKey = privateKey;
|
||||
this.publicJwk = publicKey.export({ format: 'jwk' });
|
||||
this.publicJwk.kid = 'test-key-1';
|
||||
this.publicJwk.alg = 'RS256';
|
||||
this.publicJwk.use = 'sig';
|
||||
|
||||
this.clientId = 'picpeak-test';
|
||||
this.clientSecret = 'test-client-secret';
|
||||
this.codes = new Map(); // code -> { nonce, redirectUri, codeChallenge, user }
|
||||
this.nextUser = { sub: 'user-1', email: 'sso@example.com', email_verified: true };
|
||||
// Test hooks:
|
||||
this.tamperNonce = false; // sign the ID token with a WRONG nonce
|
||||
this.emailViaUserinfoOnly = false; // omit email from the ID token; serve it on /userinfo
|
||||
this.advertiseEndSession = true; // include end_session_endpoint in discovery (#798 phase 3)
|
||||
this.accessTokens = new Map(); // access_token -> user (for /userinfo)
|
||||
this.server = null;
|
||||
this.issuer = null;
|
||||
}
|
||||
|
||||
setNextUser(user) {
|
||||
this.nextUser = user;
|
||||
}
|
||||
|
||||
signIdToken({ sub, nonce, extraClaims = {} }) {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const header = { alg: 'RS256', kid: this.publicJwk.kid, typ: 'JWT' };
|
||||
const payload = {
|
||||
iss: this.issuer,
|
||||
aud: this.clientId,
|
||||
sub,
|
||||
iat: now,
|
||||
exp: now + 300,
|
||||
nonce,
|
||||
...extraClaims,
|
||||
};
|
||||
const signingInput = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(payload))}`;
|
||||
const signature = crypto.sign('RSA-SHA256', Buffer.from(signingInput), this.privateKey);
|
||||
return `${signingInput}.${signature.toString('base64url')}`;
|
||||
}
|
||||
|
||||
async start() {
|
||||
this.server = http.createServer((req, res) => this.handle(req, res));
|
||||
await new Promise((resolve) => this.server.listen(0, '127.0.0.1', resolve));
|
||||
this.issuer = `http://127.0.0.1:${this.server.address().port}`;
|
||||
return this.issuer;
|
||||
}
|
||||
|
||||
async stop() {
|
||||
if (this.server) await new Promise((resolve) => this.server.close(resolve));
|
||||
}
|
||||
|
||||
handle(req, res) {
|
||||
const url = new URL(req.url, this.issuer);
|
||||
const json = (status, body) => {
|
||||
res.writeHead(status, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify(body));
|
||||
};
|
||||
|
||||
if (url.pathname === '/.well-known/openid-configuration') {
|
||||
return json(200, {
|
||||
issuer: this.issuer,
|
||||
authorization_endpoint: `${this.issuer}/authorize`,
|
||||
token_endpoint: `${this.issuer}/token`,
|
||||
userinfo_endpoint: `${this.issuer}/userinfo`,
|
||||
jwks_uri: `${this.issuer}/jwks`,
|
||||
...(this.advertiseEndSession ? { end_session_endpoint: `${this.issuer}/logout` } : {}),
|
||||
response_types_supported: ['code'],
|
||||
subject_types_supported: ['public'],
|
||||
id_token_signing_alg_values_supported: ['RS256'],
|
||||
code_challenge_methods_supported: ['S256'],
|
||||
token_endpoint_auth_methods_supported: ['client_secret_basic', 'client_secret_post'],
|
||||
});
|
||||
}
|
||||
|
||||
if (url.pathname === '/jwks') {
|
||||
return json(200, { keys: [this.publicJwk] });
|
||||
}
|
||||
|
||||
if (url.pathname === '/authorize') {
|
||||
// "Log in" instantly: mint a code bound to this request's params and
|
||||
// bounce back to the redirect_uri like a real IdP would.
|
||||
const code = crypto.randomBytes(16).toString('base64url');
|
||||
this.codes.set(code, {
|
||||
nonce: url.searchParams.get('nonce'),
|
||||
redirectUri: url.searchParams.get('redirect_uri'),
|
||||
codeChallenge: url.searchParams.get('code_challenge'),
|
||||
user: this.nextUser,
|
||||
});
|
||||
const back = new URL(url.searchParams.get('redirect_uri'));
|
||||
back.searchParams.set('code', code);
|
||||
back.searchParams.set('state', url.searchParams.get('state'));
|
||||
res.writeHead(302, { location: back.href });
|
||||
return res.end();
|
||||
}
|
||||
|
||||
if (url.pathname === '/token' && req.method === 'POST') {
|
||||
let body = '';
|
||||
req.on('data', (c) => { body += c; });
|
||||
req.on('end', () => {
|
||||
const params = new URLSearchParams(body);
|
||||
const stored = this.codes.get(params.get('code'));
|
||||
if (!stored) return json(400, { error: 'invalid_grant' });
|
||||
this.codes.delete(params.get('code'));
|
||||
|
||||
// PKCE check — S256(code_verifier) must match the challenge.
|
||||
const verifier = params.get('code_verifier') || '';
|
||||
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
|
||||
if (challenge !== stored.codeChallenge) {
|
||||
return json(400, { error: 'invalid_grant', error_description: 'PKCE verification failed' });
|
||||
}
|
||||
|
||||
const { sub, ...extraClaims } = stored.user;
|
||||
// Spec-compliant providers may keep profile/email claims OFF the ID
|
||||
// token and serve them from /userinfo only — this hook simulates that.
|
||||
const idTokenClaims = this.emailViaUserinfoOnly ? {} : extraClaims;
|
||||
const idToken = this.signIdToken({
|
||||
sub,
|
||||
nonce: this.tamperNonce ? 'tampered-nonce' : stored.nonce,
|
||||
extraClaims: idTokenClaims,
|
||||
});
|
||||
const accessToken = crypto.randomBytes(16).toString('base64url');
|
||||
this.accessTokens.set(accessToken, stored.user);
|
||||
return json(200, {
|
||||
access_token: accessToken,
|
||||
token_type: 'Bearer',
|
||||
expires_in: 300,
|
||||
id_token: idToken,
|
||||
});
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (url.pathname === '/userinfo') {
|
||||
const auth = req.headers.authorization || '';
|
||||
const user = this.accessTokens.get(auth.replace(/^Bearer\s+/i, ''));
|
||||
if (!user) return json(401, { error: 'invalid_token' });
|
||||
return json(200, { ...user });
|
||||
}
|
||||
|
||||
return json(404, { error: 'not_found' });
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { MockOidcProvider };
|
||||
@@ -1,284 +0,0 @@
|
||||
/**
|
||||
* OIDC logout-to-IdP integration tests (#798 phase 3).
|
||||
*
|
||||
* Same full-stack shape as oidcSso.test.js: real routes over a mock
|
||||
* in-process IdP, genuine discovery/JWKS/PKCE via openid-client. Pins:
|
||||
*
|
||||
* - the SSO callback stores the raw ID token in the oidc_id_token cookie
|
||||
* - /logout with that cookie + oidc_logout_from_idp=true returns the
|
||||
* IdP end-session URL (id_token_hint, post_logout_redirect_uri,
|
||||
* client_id) and clears the cookie
|
||||
* - feature off → no ssoLogoutUrl even for an SSO session
|
||||
* - no oidc_id_token cookie (local-password session) → no ssoLogoutUrl
|
||||
* even with the feature on — local sessions never bounce to the IdP
|
||||
* - IdP without an end_session_endpoint → no ssoLogoutUrl, logout still 200
|
||||
* - settings surface: GET exposes the flag + post_logout_redirect_uri,
|
||||
* PUT persists the flag
|
||||
*/
|
||||
|
||||
const request = require('supertest');
|
||||
const express = require('express');
|
||||
const cookieParser = require('cookie-parser');
|
||||
const bcrypt = require('bcrypt');
|
||||
|
||||
const { bootCrmDb } = require('./helpers/crmDb');
|
||||
const { MockOidcProvider } = require('./helpers/mockOidcProvider');
|
||||
|
||||
describe('OIDC logout-to-IdP (#798 phase 3)', () => {
|
||||
let db;
|
||||
let cleanup;
|
||||
let app;
|
||||
let idp;
|
||||
let oidcService;
|
||||
|
||||
beforeAll(async () => {
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'oidc-logout-test-secret';
|
||||
process.env.FRONTEND_URL = 'http://localhost:5199';
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
|
||||
idp = new MockOidcProvider();
|
||||
const issuer = await idp.start();
|
||||
|
||||
oidcService = require('../../src/services/oidcService');
|
||||
await oidcService.saveOidcSettings({
|
||||
oidc_enabled: true,
|
||||
oidc_issuer_url: issuer,
|
||||
oidc_client_id: idp.clientId,
|
||||
oidc_client_secret: idp.clientSecret,
|
||||
oidc_autoprovision: true,
|
||||
oidc_default_role: 'viewer',
|
||||
oidc_logout_from_idp: true,
|
||||
});
|
||||
|
||||
const authRouter = require('../../src/routes/auth');
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use(cookieParser());
|
||||
app.use('/api/auth', authRouter);
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => {
|
||||
if (idp) await idp.stop();
|
||||
if (cleanup) await cleanup();
|
||||
});
|
||||
|
||||
/** Drive login → IdP → callback like a browser; returns the callback response. */
|
||||
async function ssoRoundTrip() {
|
||||
const loginRes = await request(app).get('/api/auth/admin/sso/login').expect(302);
|
||||
const stateCookie = (loginRes.headers['set-cookie'] || [])
|
||||
.find((c) => c.startsWith('oidc_state='))
|
||||
.split(';')[0];
|
||||
|
||||
const idpRes = await fetch(loginRes.headers.location, { redirect: 'manual' });
|
||||
expect(idpRes.status).toBe(302);
|
||||
const back = new URL(idpRes.headers.get('location'));
|
||||
|
||||
return request(app)
|
||||
.get(`${back.pathname}?${back.searchParams.toString()}`)
|
||||
.set('Cookie', stateCookie)
|
||||
.expect(302);
|
||||
}
|
||||
|
||||
/**
|
||||
* The oidc_id_token cookie pair ("oidc_id_token=<jwt>") from a callback
|
||||
* response. The callback carries TWO Set-Cookie headers for this name —
|
||||
* establishAdminSession clears any stale marker, then the callback sets
|
||||
* the fresh one — and browsers apply them in order, so the LAST wins.
|
||||
*/
|
||||
function idTokenCookie(res) {
|
||||
const cookies = (res.headers['set-cookie'] || []).filter((c) => c.startsWith('oidc_id_token='));
|
||||
const last = cookies[cookies.length - 1];
|
||||
return last ? last.split(';')[0] : null;
|
||||
}
|
||||
|
||||
it('stores the raw ID token in the oidc_id_token cookie on SSO login', async () => {
|
||||
idp.setNextUser({ sub: 'logout-sub-1', email: 'logout@example.com', email_verified: true });
|
||||
const res = await ssoRoundTrip();
|
||||
expect(res.headers.location).toBe('http://localhost:5199/admin/dashboard');
|
||||
|
||||
const cookie = idTokenCookie(res);
|
||||
expect(cookie).toBeTruthy();
|
||||
// Raw JWT, HttpOnly, scoped to /api/auth.
|
||||
const raw = decodeURIComponent(cookie.replace('oidc_id_token=', ''));
|
||||
expect(raw.split('.')).toHaveLength(3);
|
||||
const setCookies = (res.headers['set-cookie'] || []).filter((c) => c.startsWith('oidc_id_token='));
|
||||
const full = setCookies[setCookies.length - 1];
|
||||
expect(full).toMatch(/HttpOnly/i);
|
||||
expect(full).toMatch(/Path=\/api\/auth/i);
|
||||
});
|
||||
|
||||
it('returns the IdP end-session URL on logout and clears the cookie', async () => {
|
||||
idp.setNextUser({ sub: 'logout-sub-2', email: 'logout2@example.com', email_verified: true });
|
||||
const cbRes = await ssoRoundTrip();
|
||||
const cookie = idTokenCookie(cbRes);
|
||||
const rawIdToken = decodeURIComponent(cookie.replace('oidc_id_token=', ''));
|
||||
|
||||
const res = await request(app)
|
||||
.post('/api/auth/logout')
|
||||
.set('Cookie', cookie)
|
||||
.expect(200);
|
||||
|
||||
expect(res.body.ssoLogoutUrl).toBeTruthy();
|
||||
const url = new URL(res.body.ssoLogoutUrl);
|
||||
expect(url.href.startsWith(`${idp.issuer}/logout`)).toBe(true);
|
||||
expect(url.searchParams.get('id_token_hint')).toBe(rawIdToken);
|
||||
expect(url.searchParams.get('post_logout_redirect_uri')).toBe('http://localhost:5199/admin/login');
|
||||
expect(url.searchParams.get('client_id')).toBe(idp.clientId);
|
||||
|
||||
// Cookie must be cleared so a later local-password logout in the same
|
||||
// browser doesn't bounce to the IdP again.
|
||||
const cleared = (res.headers['set-cookie'] || []).find((c) => c.startsWith('oidc_id_token='));
|
||||
expect(cleared).toBeTruthy();
|
||||
expect(cleared).toMatch(/Expires=Thu, 01 Jan 1970|Max-Age=0/i);
|
||||
});
|
||||
|
||||
it('omits ssoLogoutUrl when the feature is disabled', async () => {
|
||||
idp.setNextUser({ sub: 'logout-sub-3', email: 'logout3@example.com', email_verified: true });
|
||||
const cbRes = await ssoRoundTrip();
|
||||
const cookie = idTokenCookie(cbRes);
|
||||
|
||||
await oidcService.saveOidcSettings({ oidc_logout_from_idp: false });
|
||||
try {
|
||||
const res = await request(app)
|
||||
.post('/api/auth/logout')
|
||||
.set('Cookie', cookie)
|
||||
.expect(200);
|
||||
expect(res.body.ssoLogoutUrl).toBeUndefined();
|
||||
} finally {
|
||||
await oidcService.saveOidcSettings({ oidc_logout_from_idp: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('omits ssoLogoutUrl without an oidc_id_token cookie (local-password session)', async () => {
|
||||
const res = await request(app).post('/api/auth/logout').expect(200);
|
||||
expect(res.body.ssoLogoutUrl).toBeUndefined();
|
||||
});
|
||||
|
||||
it('omits ssoLogoutUrl when the IdP advertises no end_session_endpoint', async () => {
|
||||
// Separate provider whose discovery document lacks end_session_endpoint;
|
||||
// repointing the settings invalidates the discovery cache.
|
||||
const bareIdp = new MockOidcProvider();
|
||||
bareIdp.advertiseEndSession = false;
|
||||
const bareIssuer = await bareIdp.start();
|
||||
try {
|
||||
await oidcService.saveOidcSettings({
|
||||
oidc_issuer_url: bareIssuer,
|
||||
oidc_client_id: bareIdp.clientId,
|
||||
oidc_client_secret: bareIdp.clientSecret,
|
||||
});
|
||||
|
||||
bareIdp.setNextUser({ sub: 'logout-sub-4', email: 'logout4@example.com', email_verified: true });
|
||||
const cbRes = await ssoRoundTrip();
|
||||
const cookie = idTokenCookie(cbRes);
|
||||
expect(cookie).toBeTruthy();
|
||||
|
||||
const res = await request(app)
|
||||
.post('/api/auth/logout')
|
||||
.set('Cookie', cookie)
|
||||
.expect(200);
|
||||
expect(res.body.ssoLogoutUrl).toBeUndefined();
|
||||
} finally {
|
||||
await bareIdp.stop();
|
||||
await oidcService.saveOidcSettings({
|
||||
oidc_issuer_url: idp.issuer,
|
||||
oidc_client_id: idp.clientId,
|
||||
oidc_client_secret: idp.clientSecret,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it('stores an issuer-tagged marker for oversized ID tokens; logout still round-trips, without a hint', async () => {
|
||||
idp.setNextUser({
|
||||
sub: 'logout-sub-5',
|
||||
email: 'logout5@example.com',
|
||||
email_verified: true,
|
||||
// ~9KB of group claims — far past the 4KB cookie limit.
|
||||
groups: Array.from({ length: 300 }, (_, i) => `group-${String(i).padStart(4, '0')}-xxxxxxxxxxxxxxxx`),
|
||||
});
|
||||
const cbRes = await ssoRoundTrip();
|
||||
const cookie = idTokenCookie(cbRes);
|
||||
expect(cookie).toBeTruthy();
|
||||
// Issuer-tagged marker, not the (oversized) token itself.
|
||||
const marker = decodeURIComponent(cookie.replace('oidc_id_token=', ''));
|
||||
expect(marker.startsWith('sso.')).toBe(true);
|
||||
expect(Buffer.from(marker.split('.')[1], 'base64url').toString('utf8')).toBe(idp.issuer);
|
||||
|
||||
const res = await request(app)
|
||||
.post('/api/auth/logout')
|
||||
.set('Cookie', cookie)
|
||||
.expect(200);
|
||||
expect(res.body.ssoLogoutUrl).toBeTruthy();
|
||||
const url = new URL(res.body.ssoLogoutUrl);
|
||||
expect(url.searchParams.get('id_token_hint')).toBeNull();
|
||||
expect(url.searchParams.get('client_id')).toBe(idp.clientId);
|
||||
});
|
||||
|
||||
it('skips the round-trip for an oversized-token marker from a DIFFERENT issuer', async () => {
|
||||
const foreignMarker = `sso.${Buffer.from('http://other-idp.example').toString('base64url')}`;
|
||||
const res = await request(app)
|
||||
.post('/api/auth/logout')
|
||||
.set('Cookie', `oidc_id_token=${foreignMarker}`)
|
||||
.expect(200);
|
||||
expect(res.body.ssoLogoutUrl).toBeUndefined();
|
||||
});
|
||||
|
||||
it('a fresh local-password login clears a stale SSO marker', async () => {
|
||||
const role = await db('roles').where({ name: 'admin' }).first();
|
||||
await db('admin_users').insert({
|
||||
username: 'stale-marker-admin',
|
||||
email: 'stale-marker@example.com',
|
||||
password_hash: await bcrypt.hash('StaleMarker123!', 4),
|
||||
role_id: role.id,
|
||||
is_active: 1,
|
||||
must_change_password: 0,
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
});
|
||||
|
||||
// Stale marker from a dead SSO session rides along on the login request.
|
||||
const res = await request(app)
|
||||
.post('/api/auth/admin/login')
|
||||
.set('Cookie', 'oidc_id_token=stale.jwt.value')
|
||||
.send({ username: 'stale-marker-admin', password: 'StaleMarker123!' })
|
||||
.expect(200);
|
||||
|
||||
const cleared = (res.headers['set-cookie'] || []).find((c) => c.startsWith('oidc_id_token='));
|
||||
expect(cleared).toBeTruthy();
|
||||
expect(cleared).toMatch(/Expires=Thu, 01 Jan 1970|Max-Age=0/i);
|
||||
});
|
||||
|
||||
it('skips the round-trip when the stored hint was issued by a DIFFERENT issuer (config changed)', async () => {
|
||||
// Fake-but-well-formed JWT from another IdP — payload is all that matters,
|
||||
// buildEndSessionUrl decodes without verification for routing only.
|
||||
const b64 = (obj) => Buffer.from(JSON.stringify(obj)).toString('base64url');
|
||||
const foreignToken = `${b64({ alg: 'none' })}.${b64({ iss: 'http://other-idp.example', aud: idp.clientId })}.sig`;
|
||||
|
||||
const res = await request(app)
|
||||
.post('/api/auth/logout')
|
||||
.set('Cookie', `oidc_id_token=${foreignToken}`)
|
||||
.expect(200);
|
||||
expect(res.body.ssoLogoutUrl).toBeUndefined();
|
||||
});
|
||||
|
||||
it('drops only the hint when the issuer matches but the client changed', async () => {
|
||||
const b64 = (obj) => Buffer.from(JSON.stringify(obj)).toString('base64url');
|
||||
const oldClientToken = `${b64({ alg: 'none' })}.${b64({ iss: idp.issuer, aud: 'previous-client-id' })}.sig`;
|
||||
|
||||
const res = await request(app)
|
||||
.post('/api/auth/logout')
|
||||
.set('Cookie', `oidc_id_token=${oldClientToken}`)
|
||||
.expect(200);
|
||||
expect(res.body.ssoLogoutUrl).toBeTruthy();
|
||||
const url = new URL(res.body.ssoLogoutUrl);
|
||||
expect(url.searchParams.get('id_token_hint')).toBeNull();
|
||||
expect(url.searchParams.get('client_id')).toBe(idp.clientId);
|
||||
});
|
||||
|
||||
it('exposes the flag and post_logout_redirect_uri via getOidcConfig/getPostLogoutRedirectUri', async () => {
|
||||
// Settings-route auth chains are covered in oidcSso.test.js; here the
|
||||
// service surface the routes read from is pinned directly.
|
||||
const cfg = await oidcService.getOidcConfig();
|
||||
expect(cfg.logoutFromIdp).toBe(true);
|
||||
expect(await oidcService.getPostLogoutRedirectUri()).toBe('http://localhost:5199/admin/login');
|
||||
});
|
||||
});
|
||||
@@ -1,416 +0,0 @@
|
||||
/**
|
||||
* OIDC role mapping + login policy integration tests (#798, phase 2).
|
||||
*
|
||||
* Same harness as oidcSso.test.js: supertest over the real routes, mock
|
||||
* in-process IdP with genuine RS256/PKCE validation, fresh-SQLite DB. Pins:
|
||||
*
|
||||
* - JIT provisioning takes the MAPPED role from a nested dot-path claim
|
||||
* (Keycloak's realm_access.roles), not the static default
|
||||
* - roles are re-evaluated on every SSO login (upgrade AND downgrade)
|
||||
* - several mapped roles → the highest-priority one wins
|
||||
* - non-strict: unmapped login keeps the current role / default at JIT
|
||||
* - strict (require_mapped_role): unmapped login → sso_error=no_role
|
||||
* - the last active super_admin is never demoted by mapping
|
||||
* - space-separated string claim values work (flat `roles` claim)
|
||||
* - disable_local_login: password login → 403; OIDC_BREAK_GLASS=true
|
||||
* re-opens it; flag is inert while SSO is disabled
|
||||
* - PUT /sso validation: unknown mapping target and
|
||||
* disable-local-login-without-SSO are rejected
|
||||
*/
|
||||
|
||||
const request = require('supertest');
|
||||
const express = require('express');
|
||||
const cookieParser = require('cookie-parser');
|
||||
const bcrypt = require('bcrypt');
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
const { bootCrmDb } = require('./helpers/crmDb');
|
||||
const { MockOidcProvider } = require('./helpers/mockOidcProvider');
|
||||
|
||||
describe('OIDC role mapping + login policy (#798 phase 2)', () => {
|
||||
let db;
|
||||
let cleanup;
|
||||
let app;
|
||||
let idp;
|
||||
let oidcService;
|
||||
let superAdminToken;
|
||||
|
||||
beforeAll(async () => {
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'oidc-test-secret';
|
||||
process.env.FRONTEND_URL = 'http://localhost:5199';
|
||||
delete process.env.OIDC_BREAK_GLASS;
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
|
||||
idp = new MockOidcProvider();
|
||||
const issuer = await idp.start();
|
||||
|
||||
oidcService = require('../../src/services/oidcService');
|
||||
await oidcService.saveOidcSettings({
|
||||
oidc_enabled: true,
|
||||
oidc_issuer_url: issuer,
|
||||
oidc_client_id: idp.clientId,
|
||||
oidc_client_secret: idp.clientSecret,
|
||||
oidc_autoprovision: true,
|
||||
oidc_default_role: 'viewer',
|
||||
oidc_role_mapping_enabled: true,
|
||||
oidc_roles_claim: 'realm_access.roles',
|
||||
oidc_role_mappings: {
|
||||
'pp-super': 'super_admin',
|
||||
'pp-admins': 'admin',
|
||||
'pp-view': 'viewer',
|
||||
},
|
||||
});
|
||||
|
||||
const authRouter = require('../../src/routes/auth');
|
||||
const adminSettingsRouter = require('../../src/routes/adminSettings');
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use(cookieParser());
|
||||
app.use('/api/auth', authRouter);
|
||||
app.use('/api/admin/settings', adminSettingsRouter);
|
||||
|
||||
// A real super_admin row + token for the settings-validation tests.
|
||||
const superRole = await db('roles').where({ name: 'super_admin' }).first();
|
||||
const [rootId] = await db('admin_users').insert({
|
||||
username: 'root-admin',
|
||||
email: 'root@example.com',
|
||||
password_hash: await bcrypt.hash('RootPass123', 4),
|
||||
role_id: superRole.id,
|
||||
is_active: 1,
|
||||
auth_provider: 'local',
|
||||
created_at: new Date(),
|
||||
updated_at: new Date(),
|
||||
}).returning('id').then((r) => [r[0]?.id || r[0]]);
|
||||
superAdminToken = jwt.sign(
|
||||
{ id: rootId, username: 'root-admin', type: 'admin', role: 'super_admin', loginTime: Date.now() },
|
||||
process.env.JWT_SECRET,
|
||||
{ expiresIn: '1h', issuer: 'picpeak-auth' }
|
||||
);
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => {
|
||||
delete process.env.OIDC_BREAK_GLASS;
|
||||
if (idp) await idp.stop();
|
||||
if (cleanup) await cleanup();
|
||||
});
|
||||
|
||||
/** Drive login → IdP → callback like a browser; returns the callback response. */
|
||||
async function ssoRoundTrip() {
|
||||
const loginRes = await request(app).get('/api/auth/admin/sso/login').expect(302);
|
||||
const stateCookie = (loginRes.headers['set-cookie'] || [])
|
||||
.find((c) => c.startsWith('oidc_state=')).split(';')[0];
|
||||
const idpRes = await fetch(loginRes.headers.location, { redirect: 'manual' });
|
||||
expect(idpRes.status).toBe(302);
|
||||
const back = new URL(idpRes.headers.get('location'));
|
||||
return request(app)
|
||||
.get(`${back.pathname}?${back.searchParams.toString()}`)
|
||||
.set('Cookie', stateCookie)
|
||||
.expect(302);
|
||||
}
|
||||
|
||||
async function roleOf(email) {
|
||||
const row = await db('admin_users').where({ email }).first();
|
||||
const role = await db('roles').where({ id: row.role_id }).first();
|
||||
return role.name;
|
||||
}
|
||||
|
||||
it('JIT-provisions with the role mapped from the nested dot-path claim', async () => {
|
||||
idp.setNextUser({
|
||||
sub: 'sub-map-1',
|
||||
email: 'mapped@example.com',
|
||||
email_verified: true,
|
||||
realm_access: { roles: ['irrelevant', 'pp-admins'] },
|
||||
});
|
||||
const res = await ssoRoundTrip();
|
||||
expect(res.headers.location).toBe('http://localhost:5199/admin/dashboard');
|
||||
expect(await roleOf('mapped@example.com')).toBe('admin');
|
||||
});
|
||||
|
||||
it('re-evaluates the role on every login — downgrade lands', async () => {
|
||||
idp.setNextUser({
|
||||
sub: 'sub-map-1',
|
||||
email: 'mapped@example.com',
|
||||
email_verified: true,
|
||||
realm_access: { roles: ['pp-view'] },
|
||||
});
|
||||
const res = await ssoRoundTrip();
|
||||
expect(res.headers.location).toBe('http://localhost:5199/admin/dashboard');
|
||||
expect(await roleOf('mapped@example.com')).toBe('viewer');
|
||||
});
|
||||
|
||||
it('re-evaluates the role on every login — upgrade lands and the session JWT carries it', async () => {
|
||||
idp.setNextUser({
|
||||
sub: 'sub-map-1',
|
||||
email: 'mapped@example.com',
|
||||
email_verified: true,
|
||||
realm_access: { roles: ['pp-admins'] },
|
||||
});
|
||||
const res = await ssoRoundTrip();
|
||||
expect(await roleOf('mapped@example.com')).toBe('admin');
|
||||
|
||||
// The freshly-minted session token must already carry the NEW role —
|
||||
// the sync happens before session establishment.
|
||||
const adminCookie = (res.headers['set-cookie'] || []).find((c) => c.startsWith('admin_token='));
|
||||
const token = decodeURIComponent(adminCookie.split(';')[0].replace('admin_token=', ''));
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET, { issuer: 'picpeak-auth' });
|
||||
expect(decoded.role).toBe('admin');
|
||||
});
|
||||
|
||||
it('picks the highest-priority role when several IdP values map', async () => {
|
||||
idp.setNextUser({
|
||||
sub: 'sub-multi',
|
||||
email: 'multi@example.com',
|
||||
email_verified: true,
|
||||
realm_access: { roles: ['pp-view', 'pp-admins'] },
|
||||
});
|
||||
await ssoRoundTrip();
|
||||
expect(await roleOf('multi@example.com')).toBe('admin');
|
||||
});
|
||||
|
||||
it('non-strict: an unmapped login keeps the current role / gets the default at JIT', async () => {
|
||||
// Existing admin keeps its role.
|
||||
idp.setNextUser({
|
||||
sub: 'sub-map-1',
|
||||
email: 'mapped@example.com',
|
||||
email_verified: true,
|
||||
realm_access: { roles: ['nothing-mapped'] },
|
||||
});
|
||||
let res = await ssoRoundTrip();
|
||||
expect(res.headers.location).toBe('http://localhost:5199/admin/dashboard');
|
||||
expect(await roleOf('mapped@example.com')).toBe('admin');
|
||||
|
||||
// JIT falls back to the configured default role.
|
||||
idp.setNextUser({
|
||||
sub: 'sub-unmapped-jit',
|
||||
email: 'unmapped@example.com',
|
||||
email_verified: true,
|
||||
realm_access: { roles: ['nothing-mapped'] },
|
||||
});
|
||||
res = await ssoRoundTrip();
|
||||
expect(res.headers.location).toBe('http://localhost:5199/admin/dashboard');
|
||||
expect(await roleOf('unmapped@example.com')).toBe('viewer');
|
||||
});
|
||||
|
||||
it('strict mode refuses unmapped logins with sso_error=no_role and no session', async () => {
|
||||
await oidcService.saveOidcSettings({ oidc_require_mapped_role: true });
|
||||
idp.setNextUser({
|
||||
sub: 'sub-map-1',
|
||||
email: 'mapped@example.com',
|
||||
email_verified: true,
|
||||
realm_access: { roles: ['nothing-mapped'] },
|
||||
});
|
||||
const res = await ssoRoundTrip();
|
||||
await oidcService.saveOidcSettings({ oidc_require_mapped_role: false });
|
||||
|
||||
expect(res.headers.location).toBe('http://localhost:5199/admin/login?sso_error=no_role');
|
||||
expect((res.headers['set-cookie'] || []).find((c) => c.startsWith('admin_token='))).toBeFalsy();
|
||||
// Role untouched by the refused attempt.
|
||||
expect(await roleOf('mapped@example.com')).toBe('admin');
|
||||
});
|
||||
|
||||
it('never demotes the last active super_admin', async () => {
|
||||
// Make the SSO admin the ONLY active super_admin.
|
||||
const superRole = await db('roles').where({ name: 'super_admin' }).first();
|
||||
const ssoAdmin = await db('admin_users').where({ email: 'mapped@example.com' }).first();
|
||||
await db('admin_users').where({ role_id: superRole.id }).update({ is_active: 0 });
|
||||
await db('admin_users').where({ id: ssoAdmin.id }).update({ role_id: superRole.id, is_active: 1 });
|
||||
|
||||
idp.setNextUser({
|
||||
sub: 'sub-map-1',
|
||||
email: 'mapped@example.com',
|
||||
email_verified: true,
|
||||
realm_access: { roles: ['pp-view'] },
|
||||
});
|
||||
const res = await ssoRoundTrip();
|
||||
expect(res.headers.location).toBe('http://localhost:5199/admin/dashboard');
|
||||
// Still super_admin — the demotion was refused, the login was not.
|
||||
expect(await roleOf('mapped@example.com')).toBe('super_admin');
|
||||
|
||||
// Restore: root admin back to active super_admin, SSO admin back to admin.
|
||||
const adminRole = await db('roles').where({ name: 'admin' }).first();
|
||||
await db('admin_users').where({ email: 'root@example.com' }).update({ is_active: 1 });
|
||||
await db('admin_users').where({ id: ssoAdmin.id }).update({ role_id: adminRole.id });
|
||||
|
||||
// With ANOTHER active super_admin present the same downgrade goes through.
|
||||
idp.setNextUser({
|
||||
sub: 'sub-map-1',
|
||||
email: 'mapped@example.com',
|
||||
email_verified: true,
|
||||
realm_access: { roles: ['pp-view'] },
|
||||
});
|
||||
await db('admin_users').where({ id: ssoAdmin.id }).update({ role_id: superRole.id });
|
||||
await ssoRoundTrip();
|
||||
expect(await roleOf('mapped@example.com')).toBe('viewer');
|
||||
});
|
||||
|
||||
it('never demotes the last LOCAL-password super_admin even when an OIDC-owned super exists', async () => {
|
||||
const superRole = await db('roles').where({ name: 'super_admin' }).first();
|
||||
const viewerRole = await db('roles').where({ name: 'viewer' }).first();
|
||||
|
||||
// A local-password super admin, SSO-linked via verified email so role
|
||||
// sync applies to it.
|
||||
const [localId] = await db('admin_users').insert({
|
||||
username: 'local-super',
|
||||
email: 'local-super@example.com',
|
||||
password_hash: await bcrypt.hash('LocalSuper123', 4),
|
||||
role_id: superRole.id,
|
||||
is_active: 1,
|
||||
auth_provider: 'local',
|
||||
created_at: new Date(),
|
||||
updated_at: new Date(),
|
||||
}).returning('id').then((r) => [r[0]?.id || r[0]]);
|
||||
|
||||
// The only OTHER active super is OIDC-owned (root goes inactive) — the
|
||||
// plain last-super guard would allow the demotion, the break-glass
|
||||
// guard must not.
|
||||
const ssoAdmin = await db('admin_users').where({ email: 'mapped@example.com' }).first();
|
||||
await db('admin_users').where({ id: ssoAdmin.id }).update({ role_id: superRole.id });
|
||||
await db('admin_users').where({ email: 'root@example.com' }).update({ is_active: 0 });
|
||||
|
||||
idp.setNextUser({
|
||||
sub: 'sub-local-super',
|
||||
email: 'local-super@example.com',
|
||||
email_verified: true,
|
||||
realm_access: { roles: ['pp-view'] },
|
||||
});
|
||||
const res = await ssoRoundTrip();
|
||||
|
||||
const row = await db('admin_users').where({ id: localId }).first();
|
||||
// Restore the fixture state before asserting.
|
||||
await db('admin_users').where({ email: 'root@example.com' }).update({ is_active: 1 });
|
||||
await db('admin_users').where({ id: ssoAdmin.id }).update({ role_id: viewerRole.id });
|
||||
await db('admin_users').where({ id: localId }).update({ is_active: 0 });
|
||||
|
||||
expect(res.headers.location).toBe('http://localhost:5199/admin/dashboard');
|
||||
expect(row.role_id).toBe(superRole.id); // kept — it is the break-glass account
|
||||
});
|
||||
|
||||
it('treats prototype-property IdP values (constructor/toString) as unmapped, not as an error', async () => {
|
||||
idp.setNextUser({
|
||||
sub: 'sub-proto',
|
||||
email: 'proto@example.com',
|
||||
email_verified: true,
|
||||
realm_access: { roles: ['constructor', 'toString', '__proto__'] },
|
||||
});
|
||||
const res = await ssoRoundTrip();
|
||||
// Non-strict: unmapped → JIT with the default role, login succeeds.
|
||||
expect(res.headers.location).toBe('http://localhost:5199/admin/dashboard');
|
||||
expect(await roleOf('proto@example.com')).toBe('viewer');
|
||||
});
|
||||
|
||||
it('accepts a space-separated string value on a flat claim', async () => {
|
||||
await oidcService.saveOidcSettings({ oidc_roles_claim: 'roles' });
|
||||
idp.setNextUser({
|
||||
sub: 'sub-flat',
|
||||
email: 'flat@example.com',
|
||||
email_verified: true,
|
||||
roles: 'other pp-admins',
|
||||
});
|
||||
const res = await ssoRoundTrip();
|
||||
await oidcService.saveOidcSettings({ oidc_roles_claim: 'realm_access.roles' });
|
||||
|
||||
expect(res.headers.location).toBe('http://localhost:5199/admin/dashboard');
|
||||
expect(await roleOf('flat@example.com')).toBe('admin');
|
||||
});
|
||||
|
||||
it('refuses local password login while disable_local_login is effective', async () => {
|
||||
await oidcService.saveOidcSettings({ oidc_disable_local_login: true });
|
||||
const res = await request(app)
|
||||
.post('/api/auth/admin/login')
|
||||
.send({ username: 'root@example.com', password: 'RootPass123' });
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body.code).toBe('LOCAL_LOGIN_DISABLED');
|
||||
});
|
||||
|
||||
it('OIDC_BREAK_GLASS=true re-opens local login despite the policy', async () => {
|
||||
process.env.OIDC_BREAK_GLASS = 'true';
|
||||
const res = await request(app)
|
||||
.post('/api/auth/admin/login')
|
||||
.send({ username: 'root@example.com', password: 'RootPass123' });
|
||||
delete process.env.OIDC_BREAK_GLASS;
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.user).toBeTruthy();
|
||||
});
|
||||
|
||||
it('the stored flag is inert while SSO is disabled', async () => {
|
||||
// Simulate a torn-down SSO config with the stale flag still set — the
|
||||
// runtime check must ignore it (no lockout).
|
||||
await db('app_settings').where({ setting_key: 'oidc_enabled' })
|
||||
.update({ setting_value: JSON.stringify(false) });
|
||||
expect(await oidcService.isLocalLoginDisabled()).toBe(false);
|
||||
await db('app_settings').where({ setting_key: 'oidc_enabled' })
|
||||
.update({ setting_value: JSON.stringify(true) });
|
||||
expect(await oidcService.isLocalLoginDisabled()).toBe(true);
|
||||
await oidcService.saveOidcSettings({ oidc_disable_local_login: false });
|
||||
});
|
||||
|
||||
it('the policy disarms itself when no active local-password super admin remains', async () => {
|
||||
await oidcService.saveOidcSettings({ oidc_disable_local_login: true });
|
||||
expect(await oidcService.isLocalLoginDisabled()).toBe(true);
|
||||
// The break-glass account disappears (e.g. manual demotion/deactivation
|
||||
// while the policy is on) → local login must re-open by itself.
|
||||
await db('admin_users').where({ email: 'root@example.com' }).update({ auth_provider: 'oidc' });
|
||||
expect(await oidcService.isLocalLoginDisabled()).toBe(false);
|
||||
await db('admin_users').where({ email: 'root@example.com' }).update({ auth_provider: 'local' });
|
||||
await oidcService.saveOidcSettings({ oidc_disable_local_login: false });
|
||||
});
|
||||
|
||||
it('PUT /sso rejects a mapping onto an unknown role', async () => {
|
||||
const res = await request(app)
|
||||
.put('/api/admin/settings/sso')
|
||||
.set('Authorization', `Bearer ${superAdminToken}`)
|
||||
.send({ oidc_role_mappings: { 'pp-admins': 'does_not_exist' } });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error).toMatch(/does_not_exist/);
|
||||
// Stored mapping unchanged.
|
||||
const cfg = await oidcService.getOidcConfig();
|
||||
expect(cfg.roleMappings['pp-admins']).toBe('admin');
|
||||
});
|
||||
|
||||
it('PUT /sso rejects disabling local login while SSO is (being turned) off', async () => {
|
||||
const res = await request(app)
|
||||
.put('/api/admin/settings/sso')
|
||||
.set('Authorization', `Bearer ${superAdminToken}`)
|
||||
.send({ oidc_enabled: false, oidc_disable_local_login: true });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error).toMatch(/while SSO is enabled/);
|
||||
});
|
||||
|
||||
it('PUT /sso refuses SSO-only mode without an active local-password super admin', async () => {
|
||||
// Make every active super_admin OIDC-owned — break-glass would then
|
||||
// re-open a password route that no account can use.
|
||||
const superRole = await db('roles').where({ name: 'super_admin' }).first();
|
||||
await db('admin_users').where({ role_id: superRole.id }).update({ auth_provider: 'oidc' });
|
||||
const denied = await request(app)
|
||||
.put('/api/admin/settings/sso')
|
||||
.set('Authorization', `Bearer ${superAdminToken}`)
|
||||
.send({ oidc_disable_local_login: true });
|
||||
// Restore the local break-glass account, then the same request passes.
|
||||
await db('admin_users').where({ email: 'root@example.com' }).update({ auth_provider: 'local' });
|
||||
expect(denied.status).toBe(400);
|
||||
expect(denied.body.error).toMatch(/break-glass/);
|
||||
|
||||
const allowed = await request(app)
|
||||
.put('/api/admin/settings/sso')
|
||||
.set('Authorization', `Bearer ${superAdminToken}`)
|
||||
.send({ oidc_disable_local_login: true });
|
||||
expect(allowed.status).toBe(200);
|
||||
await oidcService.saveOidcSettings({ oidc_disable_local_login: false });
|
||||
});
|
||||
|
||||
it('GET /sso returns the phase-2 fields', async () => {
|
||||
const res = await request(app)
|
||||
.get('/api/admin/settings/sso')
|
||||
.set('Authorization', `Bearer ${superAdminToken}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.oidc_role_mapping_enabled).toBe(true);
|
||||
expect(res.body.oidc_roles_claim).toBe('realm_access.roles');
|
||||
expect(res.body.oidc_role_mappings).toEqual({
|
||||
'pp-super': 'super_admin',
|
||||
'pp-admins': 'admin',
|
||||
'pp-view': 'viewer',
|
||||
});
|
||||
expect(res.body.oidc_require_mapped_role).toBe(false);
|
||||
expect(res.body.oidc_disable_local_login).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,302 +0,0 @@
|
||||
/**
|
||||
* OIDC SSO integration tests (#798, phase 1).
|
||||
*
|
||||
* Full-stack over a mock in-process IdP (mockOidcProvider): supertest drives
|
||||
* the real /admin/sso/login and /admin/sso/callback routes on a fresh-SQLite
|
||||
* database, openid-client does genuine discovery/JWKS/PKCE/ID-token
|
||||
* validation against the mock issuer. Pins:
|
||||
*
|
||||
* - happy path: JIT provisioning creates an admin and sets the session cookie
|
||||
* - JIT off → not_provisioned redirect, no row created
|
||||
* - repeat login matches by sub, not email (email change ≠ new account)
|
||||
* - verified-email one-time link onto an existing local admin
|
||||
* - unverified email must NOT link (falls through to JIT/or error)
|
||||
* - deactivated admin → inactive redirect
|
||||
* - missing/forged state cookie → state redirect
|
||||
* - nonce tamper from the IdP → idp redirect
|
||||
* - settings endpoints: secret write-only, generic /general upsert cannot
|
||||
* clobber oidc_client_secret
|
||||
*/
|
||||
|
||||
const request = require('supertest');
|
||||
const express = require('express');
|
||||
const cookieParser = require('cookie-parser');
|
||||
const bcrypt = require('bcrypt');
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
const { bootCrmDb } = require('./helpers/crmDb');
|
||||
const { MockOidcProvider } = require('./helpers/mockOidcProvider');
|
||||
|
||||
describe('OIDC SSO (#798)', () => {
|
||||
let db;
|
||||
let cleanup;
|
||||
let app;
|
||||
let idp;
|
||||
let oidcService;
|
||||
|
||||
const agentCookies = {};
|
||||
|
||||
beforeAll(async () => {
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'oidc-test-secret';
|
||||
// The redirect_uri derives from the public base URL — pin it explicitly:
|
||||
// CI has no backend/.env, and getFrontendBaseUrl() returning '' makes
|
||||
// buildAuthorizationRequest fail (by design) with OIDC_BAD_CONFIG.
|
||||
process.env.FRONTEND_URL = 'http://localhost:5199';
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
|
||||
idp = new MockOidcProvider();
|
||||
const issuer = await idp.start();
|
||||
|
||||
// Require AFTER bootCrmDb so services share this db instance.
|
||||
oidcService = require('../../src/services/oidcService');
|
||||
await oidcService.saveOidcSettings({
|
||||
oidc_enabled: true,
|
||||
oidc_issuer_url: issuer,
|
||||
oidc_client_id: idp.clientId,
|
||||
oidc_client_secret: idp.clientSecret,
|
||||
oidc_autoprovision: true,
|
||||
oidc_default_role: 'viewer',
|
||||
});
|
||||
|
||||
const authRouter = require('../../src/routes/auth');
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use(cookieParser());
|
||||
app.use('/api/auth', authRouter);
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => {
|
||||
if (idp) await idp.stop();
|
||||
if (cleanup) await cleanup();
|
||||
});
|
||||
|
||||
/** Drive login → IdP → callback like a browser; returns the callback response. */
|
||||
async function ssoRoundTrip({ mutateState } = {}) {
|
||||
const loginRes = await request(app).get('/api/auth/admin/sso/login').expect(302);
|
||||
const idpUrl = loginRes.headers.location;
|
||||
expect(idpUrl.startsWith(idp.issuer)).toBe(true);
|
||||
|
||||
let stateCookie = (loginRes.headers['set-cookie'] || [])
|
||||
.find((c) => c.startsWith('oidc_state='));
|
||||
expect(stateCookie).toBeTruthy();
|
||||
stateCookie = stateCookie.split(';')[0];
|
||||
if (mutateState === 'drop') stateCookie = null;
|
||||
if (mutateState === 'forge') {
|
||||
stateCookie = `oidc_state=${jwt.sign({ type: 'oidc_state', s: 'x', n: 'y', cv: 'z' }, 'wrong-secret', { issuer: 'picpeak-auth' })}`;
|
||||
}
|
||||
|
||||
// "Browser" follows the redirect to the IdP, which instantly bounces back.
|
||||
const idpRes = await fetch(idpUrl, { redirect: 'manual' });
|
||||
expect(idpRes.status).toBe(302);
|
||||
const back = new URL(idpRes.headers.get('location'));
|
||||
|
||||
let cb = request(app).get(`${back.pathname}?${back.searchParams.toString()}`);
|
||||
if (stateCookie) cb = cb.set('Cookie', stateCookie);
|
||||
return cb.expect(302);
|
||||
}
|
||||
|
||||
it('JIT-provisions an unknown user and establishes an admin session', async () => {
|
||||
idp.setNextUser({ sub: 'sub-jit-1', email: 'jit@example.com', email_verified: true });
|
||||
const res = await ssoRoundTrip();
|
||||
|
||||
expect(res.headers.location).toBe('http://localhost:5199/admin/dashboard');
|
||||
const adminCookie = (res.headers['set-cookie'] || []).find((c) => c.startsWith('admin_token='));
|
||||
expect(adminCookie).toBeTruthy();
|
||||
|
||||
const row = await db('admin_users').where({ email: 'jit@example.com' }).first();
|
||||
expect(row).toBeTruthy();
|
||||
expect(row.auth_provider).toBe('oidc');
|
||||
expect(row.external_subject).toBe('sub-jit-1');
|
||||
|
||||
const role = await db('roles').where('id', row.role_id).first();
|
||||
expect(role.name).toBe('viewer');
|
||||
|
||||
// The session JWT must be a normal admin token.
|
||||
const token = adminCookie.split(';')[0].replace('admin_token=', '');
|
||||
const decoded = jwt.verify(decodeURIComponent(token), process.env.JWT_SECRET, { issuer: 'picpeak-auth' });
|
||||
expect(decoded.type).toBe('admin');
|
||||
expect(decoded.id).toBe(row.id);
|
||||
agentCookies.jitAdminId = row.id;
|
||||
});
|
||||
|
||||
it('matches repeat logins by sub even when the email changed at the IdP', async () => {
|
||||
idp.setNextUser({ sub: 'sub-jit-1', email: 'renamed@example.com', email_verified: true });
|
||||
const res = await ssoRoundTrip();
|
||||
expect(res.headers.location).toBe('http://localhost:5199/admin/dashboard');
|
||||
|
||||
// No second row — resolved via external_subject.
|
||||
expect(await db('admin_users').where({ email: 'renamed@example.com' }).first()).toBeFalsy();
|
||||
const byId = await db('admin_users').where({ id: agentCookies.jitAdminId }).first();
|
||||
expect(byId.external_subject).toBe('sub-jit-1');
|
||||
});
|
||||
|
||||
it('links an existing local admin one-time via VERIFIED email and stamps the sub', async () => {
|
||||
const role = await db('roles').where({ name: 'admin' }).first();
|
||||
const [localId] = await db('admin_users').insert({
|
||||
username: 'local-admin',
|
||||
email: 'local@example.com',
|
||||
password_hash: await bcrypt.hash('LocalPass123', 4),
|
||||
role_id: role.id,
|
||||
is_active: 1,
|
||||
auth_provider: 'local',
|
||||
created_at: new Date(),
|
||||
updated_at: new Date(),
|
||||
}).returning('id').then((r) => [r[0]?.id || r[0]]);
|
||||
|
||||
idp.setNextUser({ sub: 'sub-local-1', email: 'local@example.com', email_verified: true });
|
||||
const res = await ssoRoundTrip();
|
||||
expect(res.headers.location).toBe('http://localhost:5199/admin/dashboard');
|
||||
|
||||
const row = await db('admin_users').where({ id: localId }).first();
|
||||
expect(row.external_subject).toBe('sub-local-1');
|
||||
expect(row.auth_provider).toBe('local'); // password keeps working
|
||||
});
|
||||
|
||||
it('does NOT link by unverified email — provisions a separate account instead', async () => {
|
||||
const role = await db('roles').where({ name: 'admin' }).first();
|
||||
await db('admin_users').insert({
|
||||
username: 'victim-admin',
|
||||
email: 'victim@example.com',
|
||||
password_hash: await bcrypt.hash('VictimPass123', 4),
|
||||
role_id: role.id,
|
||||
is_active: 1,
|
||||
auth_provider: 'local',
|
||||
created_at: new Date(),
|
||||
updated_at: new Date(),
|
||||
});
|
||||
|
||||
idp.setNextUser({ sub: 'sub-attacker', email: 'victim@example.com', email_verified: false });
|
||||
// JIT would need this email but the victim row owns it (unique) — the
|
||||
// insert fails and the flow must land on an error, never on the
|
||||
// victim's session.
|
||||
const res = await ssoRoundTrip();
|
||||
expect(res.headers.location).toMatch(/sso_error=/);
|
||||
|
||||
const victim = await db('admin_users').where({ email: 'victim@example.com' }).first();
|
||||
expect(victim.external_subject).toBeNull();
|
||||
});
|
||||
|
||||
it('refuses a deactivated admin with sso_error=inactive', async () => {
|
||||
await db('admin_users').where({ id: agentCookies.jitAdminId }).update({ is_active: 0 });
|
||||
idp.setNextUser({ sub: 'sub-jit-1', email: 'renamed@example.com', email_verified: true });
|
||||
const res = await ssoRoundTrip();
|
||||
expect(res.headers.location).toBe('http://localhost:5199/admin/login?sso_error=inactive');
|
||||
await db('admin_users').where({ id: agentCookies.jitAdminId }).update({ is_active: 1 });
|
||||
});
|
||||
|
||||
it('rejects a callback without the state cookie', async () => {
|
||||
const res = await ssoRoundTrip({ mutateState: 'drop' });
|
||||
expect(res.headers.location).toBe('http://localhost:5199/admin/login?sso_error=state');
|
||||
});
|
||||
|
||||
it('rejects a forged state cookie (wrong signing key)', async () => {
|
||||
const res = await ssoRoundTrip({ mutateState: 'forge' });
|
||||
expect(res.headers.location).toBe('http://localhost:5199/admin/login?sso_error=state');
|
||||
});
|
||||
|
||||
it('rejects an ID token whose nonce does not match', async () => {
|
||||
idp.tamperNonce = true;
|
||||
idp.setNextUser({ sub: 'sub-nonce', email: 'nonce@example.com', email_verified: true });
|
||||
const res = await ssoRoundTrip();
|
||||
idp.tamperNonce = false;
|
||||
expect(res.headers.location).toBe('http://localhost:5199/admin/login?sso_error=idp');
|
||||
expect(await db('admin_users').where({ email: 'nonce@example.com' }).first()).toBeFalsy();
|
||||
});
|
||||
|
||||
it('blocks JIT with sso_error=not_provisioned when autoprovision is off', async () => {
|
||||
await oidcService.saveOidcSettings({ oidc_autoprovision: false });
|
||||
idp.setNextUser({ sub: 'sub-new-user', email: 'new@example.com', email_verified: true });
|
||||
const res = await ssoRoundTrip();
|
||||
expect(res.headers.location).toBe('http://localhost:5199/admin/login?sso_error=not_provisioned');
|
||||
expect(await db('admin_users').where({ email: 'new@example.com' }).first()).toBeFalsy();
|
||||
await oidcService.saveOidcSettings({ oidc_autoprovision: true });
|
||||
});
|
||||
|
||||
it('stores the client secret encrypted and survives a config round-trip', async () => {
|
||||
const row = await db('app_settings').where({ setting_key: 'oidc_client_secret' }).first();
|
||||
const stored = JSON.parse(row.setting_value);
|
||||
expect(stored).not.toContain(idp.clientSecret);
|
||||
expect(oidcService.decryptSecret(stored)).toBe(idp.clientSecret);
|
||||
|
||||
const cfg = await oidcService.getOidcConfig();
|
||||
expect(cfg.clientSecret).toBe(idp.clientSecret);
|
||||
});
|
||||
|
||||
it('refuses local password login for OIDC-owned accounts', async () => {
|
||||
// Give the JIT admin a KNOWN password hash directly in the DB — the
|
||||
// auth_provider check must reject the login even with valid credentials
|
||||
// (otherwise a password reset would mint an IdP-bypassing local login).
|
||||
await db('admin_users').where({ id: agentCookies.jitAdminId }).update({
|
||||
password_hash: await bcrypt.hash('KnownPass123', 4),
|
||||
});
|
||||
const row = await db('admin_users').where({ id: agentCookies.jitAdminId }).first();
|
||||
|
||||
const res = await request(app)
|
||||
.post('/api/auth/admin/login')
|
||||
.send({ username: row.email, password: 'KnownPass123' });
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('returns 404 from /sso/login when SSO is disabled', async () => {
|
||||
await oidcService.saveOidcSettings({ oidc_enabled: false });
|
||||
await request(app).get('/api/auth/admin/sso/login').expect(404);
|
||||
await oidcService.saveOidcSettings({ oidc_enabled: true });
|
||||
});
|
||||
|
||||
it('merges email from the UserInfo endpoint when the ID token omits it', async () => {
|
||||
idp.emailViaUserinfoOnly = true;
|
||||
idp.setNextUser({ sub: 'sub-userinfo', email: 'userinfo@example.com', email_verified: true });
|
||||
const res = await ssoRoundTrip();
|
||||
idp.emailViaUserinfoOnly = false;
|
||||
|
||||
expect(res.headers.location).toBe('http://localhost:5199/admin/dashboard');
|
||||
const row = await db('admin_users').where({ email: 'userinfo@example.com' }).first();
|
||||
expect(row).toBeTruthy();
|
||||
expect(row.external_subject).toBe('sub-userinfo');
|
||||
});
|
||||
|
||||
it('binds identities per ISSUER — a sub collision on a new IdP must not inherit the old account', async () => {
|
||||
// The JIT admin from the first test is bound to (issuer A, 'sub-jit-1').
|
||||
const boundAdmin = await db('admin_users').where({ id: agentCookies.jitAdminId }).first();
|
||||
expect(boundAdmin.external_issuer).toBe(idp.issuer);
|
||||
|
||||
// Same sub, DIFFERENT issuer: a second IdP the instance switches to.
|
||||
const idp2 = new MockOidcProvider();
|
||||
await idp2.start();
|
||||
try {
|
||||
await oidcService.saveOidcSettings({
|
||||
oidc_issuer_url: idp2.issuer,
|
||||
oidc_client_id: idp2.clientId,
|
||||
oidc_client_secret: idp2.clientSecret,
|
||||
});
|
||||
idp2.setNextUser({ sub: 'sub-jit-1', email: 'colliding@example.com', email_verified: true });
|
||||
|
||||
const loginRes = await request(app).get('/api/auth/admin/sso/login').expect(302);
|
||||
const stateCookie = (loginRes.headers['set-cookie'] || [])
|
||||
.find((c) => c.startsWith('oidc_state=')).split(';')[0];
|
||||
const idpRes = await fetch(loginRes.headers.location, { redirect: 'manual' });
|
||||
const back = new URL(idpRes.headers.get('location'));
|
||||
const res = await request(app)
|
||||
.get(`${back.pathname}?${back.searchParams.toString()}`)
|
||||
.set('Cookie', stateCookie)
|
||||
.expect(302);
|
||||
expect(res.headers.location).toBe('http://localhost:5199/admin/dashboard');
|
||||
|
||||
// A NEW row bound to issuer B — the issuer-A admin is untouched and
|
||||
// its role was not inherited.
|
||||
const collider = await db('admin_users').where({ email: 'colliding@example.com' }).first();
|
||||
expect(collider).toBeTruthy();
|
||||
expect(collider.id).not.toBe(agentCookies.jitAdminId);
|
||||
expect(collider.external_issuer).toBe(idp2.issuer);
|
||||
const original = await db('admin_users').where({ id: agentCookies.jitAdminId }).first();
|
||||
expect(original.external_issuer).toBe(idp.issuer);
|
||||
} finally {
|
||||
await idp2.stop();
|
||||
await oidcService.saveOidcSettings({
|
||||
oidc_issuer_url: idp.issuer,
|
||||
oidc_client_id: idp.clientId,
|
||||
oidc_client_secret: idp.clientSecret,
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,197 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Cross-engine .picpeak restore policy (#1041): a SQLite archive restored onto
|
||||
* a PostgreSQL instance — the official small-install → full-stack upgrade
|
||||
* path — now allowed by validateManifest's direction rule instead of the
|
||||
* former CLI-only allowEngineSwitch flag. The coercion engine itself
|
||||
* (typedColumnsFor / epochToIso / coerceForTargetEngine) landed with #1039;
|
||||
* these tests pin the direction policy and the coercion's cross-engine
|
||||
* value-correctness.
|
||||
*
|
||||
* Ungated: validateManifest direction rules and the pure coercion units.
|
||||
* The reverse direction (pg backup onto a sqlite instance) staying blocked is
|
||||
* pinned by picpeakRoundtrip.test.js, which runs on the real sqlite harness.
|
||||
*
|
||||
* Gated on PICPEAK_PG_TEST_URL (same contract as picpeakRestorePg.test.js):
|
||||
* sqlite-shaped NDJSON rows land in real Postgres with correct stored VALUES,
|
||||
* not just row counts, e.g.
|
||||
* PICPEAK_PG_TEST_URL="postgres://picpeak:pw@127.0.0.1:7102/picpeak_xengine_test" \
|
||||
* npx jest __tests__/integration/picpeakCrossEngine.test.js
|
||||
*/
|
||||
const knexLib = require('knex');
|
||||
|
||||
describe('validateManifest cross-engine direction (pg target)', () => {
|
||||
let validateManifest;
|
||||
|
||||
beforeAll(() => {
|
||||
jest.resetModules();
|
||||
jest.doMock('../../knexfile', () => ({ client: 'pg' }));
|
||||
// validateManifest wraps its knex_migrations lookup in try/catch — a
|
||||
// throwing stub simply skips the forward-only check, which is not under
|
||||
// test here.
|
||||
jest.doMock('../../src/database/db', () => ({ db: () => { throw new Error('stub'); } }));
|
||||
({ validateManifest } = require('../../src/services/picpeakImportService'));
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
jest.dontMock('../../src/database/db');
|
||||
jest.dontMock('../../knexfile');
|
||||
jest.resetModules();
|
||||
});
|
||||
|
||||
it('allows a sqlite backup onto a pg instance (upgrade direction)', async () => {
|
||||
const blockers = await validateManifest({
|
||||
kind: 'picpeak-backup', format: 1, database: { engine: 'sqlite' }, tables: {},
|
||||
});
|
||||
expect(blockers.filter((b) => /engine/i.test(b))).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('still allows same-engine pg → pg', async () => {
|
||||
const blockers = await validateManifest({
|
||||
kind: 'picpeak-backup', format: 1, database: { engine: 'pg' }, tables: {},
|
||||
});
|
||||
expect(blockers.filter((b) => /engine/i.test(b))).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('epochToIso (landed with #1039)', () => {
|
||||
let epochToIso;
|
||||
|
||||
beforeAll(() => {
|
||||
jest.resetModules();
|
||||
({ epochToIso } = require('../../src/services/picpeakImportService'));
|
||||
});
|
||||
|
||||
it('converts epoch milliseconds', () => {
|
||||
expect(epochToIso(1723400000000)).toBe('2024-08-11T18:13:20.000Z');
|
||||
});
|
||||
|
||||
it('converts epoch SECONDS to the same instant, not January 1970', () => {
|
||||
expect(epochToIso(1723400000)).toBe('2024-08-11T18:13:20.000Z');
|
||||
});
|
||||
|
||||
it('converts numeric strings', () => {
|
||||
expect(epochToIso('1723400000000')).toBe('2024-08-11T18:13:20.000Z');
|
||||
});
|
||||
|
||||
it('passes non-numeric values through untouched', () => {
|
||||
expect(epochToIso('2026-08-12 10:00:00')).toBe('2026-08-12 10:00:00');
|
||||
});
|
||||
});
|
||||
|
||||
describe('coerceForTargetEngine on sqlite-shaped rows', () => {
|
||||
let coerceForTargetEngine;
|
||||
|
||||
beforeAll(() => {
|
||||
jest.resetModules();
|
||||
({ coerceForTargetEngine } = require('../../src/services/picpeakImportService'));
|
||||
});
|
||||
|
||||
const types = { timestamps: ['created_at', 'expires_at'], booleans: ['is_active'] };
|
||||
|
||||
it('coerces 0/1 booleans and epoch timestamps, leaves date strings alone', () => {
|
||||
const [row] = coerceForTargetEngine(
|
||||
[{ id: 1, is_active: 1, created_at: 1723400000000, expires_at: '2026-09-01 12:00:00' }],
|
||||
types
|
||||
);
|
||||
expect(row.is_active).toBe(true);
|
||||
expect(row.created_at).toBe('2024-08-11T18:13:20.000Z');
|
||||
expect(row.expires_at).toBe('2026-09-01 12:00:00'); // pg parses this natively
|
||||
});
|
||||
|
||||
it('coerces falsy variants and passes null/empty through', () => {
|
||||
const [row] = coerceForTargetEngine(
|
||||
[{ is_active: 0, created_at: null, expires_at: '' }],
|
||||
types
|
||||
);
|
||||
expect(row.is_active).toBe(false);
|
||||
expect(row.created_at).toBeNull();
|
||||
expect(row.expires_at).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
// ── Real-Postgres integration (gated) ────────────────────────────────────────
|
||||
const PG_URL = process.env.PICPEAK_PG_TEST_URL;
|
||||
const maybe = PG_URL ? describe : describe.skip;
|
||||
|
||||
maybe('sqlite-shaped rows land correctly in real Postgres', () => {
|
||||
let pgDb;
|
||||
let svc;
|
||||
|
||||
beforeAll(async () => {
|
||||
pgDb = knexLib({ client: 'pg', connection: PG_URL });
|
||||
await pgDb.raw('DROP TABLE IF EXISTS xengine_events, xengine_settings CASCADE');
|
||||
await pgDb.schema.createTable('xengine_events', (t) => {
|
||||
t.increments('id');
|
||||
t.string('slug');
|
||||
t.boolean('is_active').defaultTo(true);
|
||||
t.boolean('allow_downloads').defaultTo(true);
|
||||
t.timestamp('created_at');
|
||||
t.timestamp('expires_at');
|
||||
});
|
||||
await pgDb.schema.createTable('xengine_settings', (t) => {
|
||||
t.increments('id');
|
||||
t.string('setting_key').notNullable().unique();
|
||||
t.jsonb('setting_value');
|
||||
});
|
||||
|
||||
jest.resetModules();
|
||||
jest.doMock('../../knexfile', () => ({ client: 'pg' }));
|
||||
jest.doMock('../../src/database/db', () => ({ db: pgDb }));
|
||||
svc = require('../../src/services/picpeakImportService');
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
jest.dontMock('../../src/database/db');
|
||||
jest.dontMock('../../knexfile');
|
||||
if (pgDb) {
|
||||
await pgDb.raw('DROP TABLE IF EXISTS xengine_events, xengine_settings CASCADE');
|
||||
await pgDb.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
it('typedColumnsFor classifies boolean and timestamp columns via columnInfo()', async () => {
|
||||
const types = await svc.typedColumnsFor(pgDb, 'xengine_events');
|
||||
expect(types.booleans.sort()).toEqual(['allow_downloads', 'is_active']);
|
||||
expect(types.timestamps.sort()).toEqual(['created_at', 'expires_at']);
|
||||
});
|
||||
|
||||
it('inserts a sqlite archive row (0/1 booleans, epoch dates, json text) with correct stored values', async () => {
|
||||
// Exactly what a sqlite-created .picpeak carries: integers for booleans,
|
||||
// epoch numbers for #485-shape timestamps (ms here, seconds covered by the
|
||||
// epochToIso unit), a "YYYY-MM-DD HH:MM:SS" string for clean ones, and
|
||||
// json columns as TEXT (the crossEngine path skips serialiseJsonColumns —
|
||||
// the text is already what pg wants).
|
||||
const epoch = 1723400000000;
|
||||
const eventRows = [
|
||||
{ id: 1, slug: 'wedding', is_active: 1, allow_downloads: 0, created_at: epoch, expires_at: '2026-09-01 12:00:00' },
|
||||
];
|
||||
const settingRows = [{ id: 1, setting_key: 'brand', setting_value: '{"name":"PicPeak","dark":true}' }];
|
||||
|
||||
await pgDb.transaction(async (trx) => {
|
||||
const evTypes = await svc.typedColumnsFor(trx, 'xengine_events');
|
||||
await trx.batchInsert('xengine_events', svc.coerceForTargetEngine(eventRows, evTypes), 100);
|
||||
const stTypes = await svc.typedColumnsFor(trx, 'xengine_settings');
|
||||
await trx.batchInsert('xengine_settings', svc.coerceForTargetEngine(settingRows, stTypes), 100);
|
||||
});
|
||||
|
||||
const ev = await pgDb('xengine_events').where({ id: 1 }).first();
|
||||
expect(ev.is_active).toBe(true); // 1 → true, not backwards (#1028 class)
|
||||
expect(ev.allow_downloads).toBe(false); // 0 → false
|
||||
expect(new Date(ev.created_at).getTime()).toBe(epoch);
|
||||
expect(new Date(ev.expires_at).toISOString().slice(0, 10)).toBe('2026-09-01');
|
||||
|
||||
const st = await pgDb('xengine_settings').where({ id: 1 }).first();
|
||||
// jsonb parsed back by the driver — value intact, no double encoding.
|
||||
expect(st.setting_value).toEqual({ name: 'PicPeak', dark: true });
|
||||
});
|
||||
|
||||
it('id sequence works after explicit-id insert + resync (next natural insert)', async () => {
|
||||
await svc.resyncSequences(['xengine_events']);
|
||||
const [next] = await pgDb('xengine_events')
|
||||
.insert({ slug: 'fresh', is_active: true })
|
||||
.returning('id');
|
||||
expect(Number(next.id || next)).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -1,190 +0,0 @@
|
||||
/**
|
||||
* PostgreSQL integration tests for the .picpeak restore robustness fixes.
|
||||
* Gated: runs only when PICPEAK_PG_TEST_URL points at a throwaway Postgres DB,
|
||||
* e.g.
|
||||
* PICPEAK_PG_TEST_URL="postgres://picpeak:picpeak_secure_pass_2024@127.0.0.1:7102/picpeak_restore_test" \
|
||||
* npx jest __tests__/integration/picpeakRestorePg.test.js
|
||||
*
|
||||
* Validates the Postgres-specific paths that SQLite can't exercise: identity
|
||||
* sequences left stale by explicit-id inserts, pg_get_serial_sequence raising on
|
||||
* id-less tables, reinject/role-recreate explicit-id inserts, and FK integrity.
|
||||
*/
|
||||
const knex = require('knex');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
const PG_URL = process.env.PICPEAK_PG_TEST_URL;
|
||||
const maybe = PG_URL ? describe : describe.skip;
|
||||
|
||||
maybe('picpeak restore on Postgres', () => {
|
||||
let pgDb;
|
||||
let svc;
|
||||
|
||||
beforeAll(async () => {
|
||||
pgDb = knex({ client: 'pg', connection: PG_URL });
|
||||
|
||||
await pgDb.raw('DROP TABLE IF EXISTS role_permissions, events, admin_users, roles, permissions, app_settings CASCADE');
|
||||
await pgDb.schema.createTable('roles', (t) => {
|
||||
t.increments('id');
|
||||
t.string('name', 50).notNullable().unique();
|
||||
t.string('display_name', 100);
|
||||
t.integer('priority').defaultTo(0);
|
||||
t.boolean('is_system').defaultTo(false);
|
||||
});
|
||||
await pgDb.schema.createTable('permissions', (t) => {
|
||||
t.increments('id');
|
||||
t.string('name', 100).notNullable().unique();
|
||||
t.string('display_name', 150);
|
||||
t.string('category', 50);
|
||||
});
|
||||
await pgDb.schema.createTable('role_permissions', (t) => {
|
||||
t.integer('role_id').notNullable().references('id').inTable('roles').onDelete('CASCADE');
|
||||
t.integer('permission_id').notNullable().references('id').inTable('permissions').onDelete('CASCADE');
|
||||
t.primary(['role_id', 'permission_id']);
|
||||
});
|
||||
await pgDb.schema.createTable('admin_users', (t) => {
|
||||
t.increments('id');
|
||||
t.string('username').notNullable().unique();
|
||||
t.string('email').notNullable().unique();
|
||||
t.string('password_hash');
|
||||
t.boolean('is_active').defaultTo(true);
|
||||
t.boolean('must_change_password').defaultTo(false);
|
||||
t.integer('role_id').references('id').inTable('roles').onDelete('SET NULL');
|
||||
t.integer('created_by').references('id').inTable('admin_users').onDelete('SET NULL');
|
||||
t.boolean('two_factor_enabled').defaultTo(false);
|
||||
t.string('two_factor_secret');
|
||||
t.text('two_factor_recovery_codes');
|
||||
});
|
||||
await pgDb.schema.createTable('events', (t) => {
|
||||
t.increments('id');
|
||||
t.string('slug');
|
||||
t.integer('created_by').references('id').inTable('admin_users').onDelete('SET NULL');
|
||||
});
|
||||
await pgDb.schema.createTable('app_settings', (t) => {
|
||||
t.increments('id');
|
||||
t.string('setting_key').notNullable().unique();
|
||||
t.json('setting_value');
|
||||
t.string('setting_type');
|
||||
t.timestamp('updated_at').defaultTo(pgDb.fn.now());
|
||||
});
|
||||
|
||||
jest.resetModules();
|
||||
jest.doMock('../../knexfile', () => ({ client: 'pg' }));
|
||||
jest.doMock('../../src/database/db', () => ({ db: pgDb }));
|
||||
svc = require('../../src/services/picpeakImportService');
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
jest.dontMock('../../src/database/db');
|
||||
jest.dontMock('../../knexfile');
|
||||
if (pgDb) await pgDb.destroy();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await pgDb('role_permissions').del();
|
||||
await pgDb('events').del();
|
||||
await pgDb('admin_users').del();
|
||||
await pgDb('roles').del();
|
||||
await pgDb('permissions').del();
|
||||
});
|
||||
|
||||
test('resyncSequences fast-forwards stale sequences and skips id-less tables', async () => {
|
||||
// Simulate a restore: explicit-id inserts leave the sequence at 1.
|
||||
await pgDb('roles').insert([{ id: 5, name: 'super_admin', display_name: 'SA' }]);
|
||||
await pgDb('admin_users').insert([{ id: 9, username: 'a', email: 'a@x.io', password_hash: 'h' }]);
|
||||
await pgDb('permissions').insert([{ id: 3, name: 'events.create', display_name: 'C', category: 'events' }]);
|
||||
await pgDb('role_permissions').insert([{ role_id: 5, permission_id: 3 }]); // id-less table
|
||||
|
||||
// Must not throw on role_permissions (no `id` column → pg_get_serial_sequence raises unguarded).
|
||||
await expect(svc.resyncSequences(['roles', 'admin_users', 'permissions', 'role_permissions'])).resolves.toBeUndefined();
|
||||
|
||||
// Natural inserts (no explicit id) now avoid the restored ids.
|
||||
const [adminId] = await pgDb('admin_users').insert({ username: 'b', email: 'b@x.io', password_hash: 'h' }).returning('id');
|
||||
expect(Number(adminId.id || adminId)).toBe(10); // max(9)+1, no duplicate-key error
|
||||
const [roleId] = await pgDb('roles').insert({ name: 'editor', display_name: 'Ed' }).returning('id');
|
||||
expect(Number(roleId.id || roleId)).toBe(6);
|
||||
});
|
||||
|
||||
test('reinjectCurrentAdmin insert branch works with a stale sequence (explicit max+1)', async () => {
|
||||
await pgDb('admin_users').insert({ id: 9, username: 'backup', email: 'backup@x.io', password_hash: 'h' });
|
||||
const operator = { id: 1, username: 'admin', email: 'op@x.io', password_hash: 'OP', is_active: true, created_by: 42 };
|
||||
|
||||
await pgDb.transaction((trx) => svc.reinjectCurrentAdmin(trx, operator));
|
||||
|
||||
const op = await pgDb('admin_users').where({ email: 'op@x.io' }).first();
|
||||
expect(op.id).toBe(10); // max(9)+1
|
||||
expect(op.password_hash).toBe('OP');
|
||||
expect(op.created_by).toBeNull(); // self-ref FK nulled so the insert can't dangle
|
||||
});
|
||||
|
||||
test('preserveOperatorRole re-creates a missing role on Postgres and keeps FK integrity', async () => {
|
||||
await pgDb('permissions').insert([{ id: 3, name: 'events.create', display_name: 'C', category: 'events' }]);
|
||||
await pgDb('roles').insert([{ id: 2, name: 'viewer', display_name: 'V' }]);
|
||||
await pgDb('admin_users').insert({ id: 1, username: 'admin', email: 'op@x.io', password_hash: 'h', role_id: null });
|
||||
const snapshot = { role: { name: 'super_admin', display_name: 'SA', priority: 100, is_system: true }, permissions: ['events.create', 'missing.perm'] };
|
||||
|
||||
await pgDb.transaction((trx) => svc.preserveOperatorRole(trx, 1, snapshot));
|
||||
await svc.resyncSequences(['roles']); // post-commit, mirrors importFromPicpeak
|
||||
|
||||
const role = await pgDb('roles').where({ name: 'super_admin' }).first();
|
||||
expect(role).toBeTruthy();
|
||||
const op = await pgDb('admin_users').where({ id: 1 }).first();
|
||||
expect(op.role_id).toBe(role.id); // FK valid, operator not downgraded
|
||||
const grants = await pgDb('role_permissions').where({ role_id: role.id }).pluck('permission_id');
|
||||
expect(grants).toEqual([3]); // existing perm granted, missing.perm skipped
|
||||
});
|
||||
|
||||
test('full replaceAllTables: cross-instance backup preserves the operator, role, FKs, and sequences', async () => {
|
||||
// A backup from ANOTHER instance: omits the operator's email AND their
|
||||
// super_admin role; uses explicit ids that leave sequences stale.
|
||||
const staging = fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-pgtest-'));
|
||||
const dataDir = path.join(staging, 'data');
|
||||
fs.mkdirSync(dataDir);
|
||||
const write = (t, rows) => fs.writeFileSync(path.join(dataDir, `${t}.ndjson`), rows.map((r) => JSON.stringify(r)).join('\n'));
|
||||
write('roles', [{ id: 5, name: 'admin', display_name: 'Admin', priority: 50, is_system: true }]);
|
||||
write('permissions', [{ id: 3, name: 'events.create', display_name: 'C', category: 'events' }]);
|
||||
write('role_permissions', [{ role_id: 5, permission_id: 3 }]);
|
||||
write('admin_users', [{ id: 9, username: 'backupadmin', email: 'backup@x.io', password_hash: 'h', role_id: 5, is_active: true }]);
|
||||
write('events', [{ id: 2, slug: 'restored-ev', created_by: 9 }]);
|
||||
|
||||
const operator = { id: 1, username: 'admin', email: 'op@x.io', password_hash: 'OP', is_active: true, role_id: 999, created_by: null };
|
||||
const roleSnapshot = { role: { name: 'super_admin', display_name: 'Super Admin', priority: 100, is_system: true }, permissions: ['events.create'] };
|
||||
const tables = ['roles', 'permissions', 'role_permissions', 'admin_users', 'events'];
|
||||
|
||||
// replaceAllTables isn't exported, so drive its exact transaction sequence
|
||||
// (suspend FKs, wipe, batchInsert, reinject, preserve role) through the
|
||||
// exported units against real Postgres.
|
||||
const importSvc = svc;
|
||||
await pgDb.transaction(async (trx) => {
|
||||
await trx.raw('SET session_replication_role = \'replica\'');
|
||||
for (const t of tables) await trx(t).del();
|
||||
for (const t of tables) {
|
||||
const rows = fs.readFileSync(path.join(dataDir, `${t}.ndjson`), 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l));
|
||||
if (rows.length) await trx.batchInsert(t, rows, 100);
|
||||
}
|
||||
const opId = await importSvc.reinjectCurrentAdmin(trx, operator);
|
||||
await importSvc.preserveOperatorRole(trx, opId, roleSnapshot);
|
||||
await trx.raw('SET session_replication_role = \'origin\'');
|
||||
});
|
||||
await importSvc.resyncSequences(tables);
|
||||
|
||||
// Operator preserved (inserted, since email absent from backup).
|
||||
const op = await pgDb('admin_users').where({ email: 'op@x.io' }).first();
|
||||
expect(op).toBeTruthy();
|
||||
expect(op.password_hash).toBe('OP');
|
||||
// super_admin role re-created and the operator bound to it.
|
||||
const sa = await pgDb('roles').where({ name: 'super_admin' }).first();
|
||||
expect(sa).toBeTruthy();
|
||||
expect(op.role_id).toBe(sa.id);
|
||||
expect(await pgDb('role_permissions').where({ role_id: sa.id }).pluck('permission_id')).toEqual([3]);
|
||||
// Restored event's created_by FK to the backup admin still valid.
|
||||
const ev = await pgDb('events').where({ slug: 'restored-ev' }).first();
|
||||
expect(ev.created_by).toBe(9);
|
||||
// Sequences resynced → natural inserts don't collide.
|
||||
const [newAdmin] = await pgDb('admin_users').insert({ username: 'fresh', email: 'fresh@x.io', password_hash: 'h' }).returning('id');
|
||||
expect(Number(newAdmin.id || newAdmin)).toBeGreaterThan(op.id);
|
||||
|
||||
fs.rmSync(staging, { recursive: true, force: true });
|
||||
});
|
||||
});
|
||||
@@ -1,256 +0,0 @@
|
||||
/**
|
||||
* Issue #866 — the createInvoice-free halves of the re-bill proof + CRM panel
|
||||
* feature, against a real SQLite schema:
|
||||
*
|
||||
* • listCustomerRebills — status DERIVED from the linked invoice lifecycle
|
||||
* (open / sent / paid; a cancelled/Storno'd cover drops back to open) plus
|
||||
* cost-vs-rebilled math and mode.
|
||||
* • collectRebillProofAttachments — the Send-dialog per-file selection, the
|
||||
* all-or-none default resolution (per-customer override else global), the
|
||||
* Beleg-<inv#> filename (suffix only when >1), and the missing-file marker.
|
||||
*
|
||||
* The invoice-MINTING paths (billCombinedForCustomer / billPendingRebills) call
|
||||
* createInvoice inside a db.transaction, which deadlocks on the SQLite harness
|
||||
* (global-db sequence write vs. held write lock) — same limitation the sibling
|
||||
* incomingInvoiceRebill.test.js documents. They're covered by the existing
|
||||
* billPendingRebills / billUnbilledEntries suites; here we hand-craft billed
|
||||
* state instead.
|
||||
*/
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { bootCrmDb, seedMinimal } = require('./helpers/crmDb');
|
||||
|
||||
jest.setTimeout(120000);
|
||||
|
||||
describe('#866 re-bill proof attachment + CRM panel', () => {
|
||||
let db;
|
||||
let cleanup;
|
||||
let adminId;
|
||||
let expenseService;
|
||||
let rebillProofs;
|
||||
let flagCache;
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
const dbModule = require('../../src/database/db');
|
||||
dbModule.logActivity = async () => {};
|
||||
({ adminId } = await seedMinimal(db));
|
||||
expenseService = require('../../src/services/expenseService');
|
||||
rebillProofs = require('../../src/services/invoice/rebillProofs');
|
||||
flagCache = require('../../src/middleware/requireFeatureFlag');
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => {
|
||||
if (cleanup) await cleanup();
|
||||
});
|
||||
|
||||
const unwrapId = (ins) => (typeof ins[0] === 'object' ? ins[0].id : ins[0]);
|
||||
let seq = 0;
|
||||
|
||||
async function makeCustomer(overrides = {}) {
|
||||
seq += 1;
|
||||
const ins = await db('customer_accounts').insert({
|
||||
email: `c866-${seq}@example.com`,
|
||||
display_name: `C866 ${seq}`,
|
||||
password_hash: 'x',
|
||||
preferred_language: 'de',
|
||||
is_active: 1,
|
||||
billing_cadence: 'per_event',
|
||||
created_at: new Date(),
|
||||
...overrides,
|
||||
}).returning('id');
|
||||
return unwrapId(ins);
|
||||
}
|
||||
|
||||
async function makeDoc(customerId, overrides = {}) {
|
||||
const ins = await db('inbound_documents').insert({
|
||||
source: 'upload', status: 'categorized', parse_status: 'parsed', parse_method: 'none',
|
||||
supplier_name: 'ACME AG', currency: 'CHF', total_amount_minor: 10000,
|
||||
invoice_date: '2026-06-01', disposition: 'rebill', customer_account_id: customerId,
|
||||
created_at: new Date(), updated_at: new Date(),
|
||||
...overrides,
|
||||
}).returning('id');
|
||||
return unwrapId(ins);
|
||||
}
|
||||
|
||||
async function makeInvoice(customerId, status, number) {
|
||||
const ins = await db('invoices').insert({
|
||||
invoice_number: number,
|
||||
customer_account_id: customerId,
|
||||
status,
|
||||
currency: 'CHF',
|
||||
issue_date: '2026-06-01', due_date: '2026-07-01',
|
||||
vat_rate: 0, net_amount_minor: 10000, vat_amount_minor: 0, total_amount_minor: 10000,
|
||||
created_at: new Date(), updated_at: new Date(),
|
||||
}).returning('id');
|
||||
return unwrapId(ins);
|
||||
}
|
||||
|
||||
describe('listCustomerRebills', () => {
|
||||
it('derives open / sent / paid and open→cost==rebilled for passthrough, +markup for rebill', async () => {
|
||||
const customerId = await makeCustomer();
|
||||
|
||||
// Open re-bill (10% markup): rebilled = 11000.
|
||||
await makeDoc(customerId, { total_amount_minor: 10000, markup_type: 'percent', markup_percent: 10 });
|
||||
// Open passthrough: no markup, rebilled == cost.
|
||||
await makeDoc(customerId, { disposition: 'durchlaufend', total_amount_minor: 5000, markup_type: 'none' });
|
||||
// Sent (on a 'sent' invoice).
|
||||
const sentInv = await makeInvoice(customerId, 'sent', 'R-2026-0001');
|
||||
await makeDoc(customerId, { total_amount_minor: 8000, markup_type: 'none', billed_invoice_id: sentInv });
|
||||
// Paid.
|
||||
const paidInv = await makeInvoice(customerId, 'paid', 'R-2026-0002');
|
||||
await makeDoc(customerId, { total_amount_minor: 8000, markup_type: 'none', billed_invoice_id: paidInv });
|
||||
// Cancelled cover → drops back to 'open', no invoice link surfaced.
|
||||
const cancInv = await makeInvoice(customerId, 'cancelled', 'R-2026-0003');
|
||||
await makeDoc(customerId, { total_amount_minor: 8000, markup_type: 'none', billed_invoice_id: cancInv });
|
||||
|
||||
const items = await expenseService.listCustomerRebills(customerId);
|
||||
const byStatus = (s) => items.filter((r) => r.status === s);
|
||||
|
||||
expect(items).toHaveLength(5);
|
||||
expect(byStatus('open')).toHaveLength(3); // 2 genuinely-open + 1 cancelled-cover
|
||||
expect(byStatus('sent')).toHaveLength(1);
|
||||
expect(byStatus('paid')).toHaveLength(1);
|
||||
|
||||
const rebill = items.find((r) => r.mode === 'rebill' && r.costMinor === 10000);
|
||||
expect(rebill.rebilledMinor).toBe(11000);
|
||||
const passthrough = items.find((r) => r.mode === 'passthrough');
|
||||
expect(passthrough.rebilledMinor).toBe(passthrough.costMinor);
|
||||
|
||||
const sent = byStatus('sent')[0];
|
||||
expect(sent.invoiceNumber).toBe('R-2026-0001');
|
||||
expect(sent.invoiceId).toBe(sentInv);
|
||||
|
||||
const cancelledCover = items.find((r) => r.status === 'open' && r.invoiceNumber === null && r.costMinor === 8000);
|
||||
expect(cancelledCover).toBeDefined(); // cancelled cover isn't shown as a live invoice link
|
||||
});
|
||||
});
|
||||
|
||||
describe('storno releases the re-bill linkage (#866 review)', () => {
|
||||
it("clears billed_invoice_id so a Storno'd cover returns to the billable pool", async () => {
|
||||
const invoiceService = require('../../src/services/invoiceService');
|
||||
const customerId = await makeCustomer();
|
||||
const invId = await makeInvoice(customerId, 'sent', 'R-2026-9000');
|
||||
const lineIns = await db('invoice_line_items').insert({
|
||||
invoice_id: invId, position: 1, quantity: 1, description: 'Rebill',
|
||||
unit_price_minor: 8000, discount_percent: 0, line_total_minor: 8000,
|
||||
}).returning('id');
|
||||
const lineId = unwrapId(lineIns);
|
||||
const docId = await makeDoc(customerId, {
|
||||
total_amount_minor: 8000, markup_type: 'none', billed_invoice_id: invId, billed_invoice_line_item_id: lineId,
|
||||
});
|
||||
|
||||
// Storno claims a fresh number from document_sequences; the other tests
|
||||
// seed explicit R-2026-000x numbers without advancing it, so push the
|
||||
// counter past them to avoid a number collision (a test artifact — real
|
||||
// invoices always claim through the sequence).
|
||||
await db('document_sequences').insert({ kind: 'invoice', year: 2026, current_value: 9000, created_at: new Date(), updated_at: new Date() })
|
||||
.onConflict(['kind', 'year']).ignore();
|
||||
await db('document_sequences').where({ kind: 'invoice', year: 2026 }).update({ current_value: 9000 });
|
||||
|
||||
// Storno the covering invoice (the issued-cancel path).
|
||||
await db.transaction(async (trx) => invoiceService.createStorno(invId, adminId, trx));
|
||||
|
||||
const doc = await db('inbound_documents').where({ id: docId }).first();
|
||||
expect(doc.billed_invoice_id).toBeNull();
|
||||
expect(doc.billed_invoice_line_item_id).toBeNull();
|
||||
|
||||
// It now surfaces as a genuinely-open item AND the pending pool picks it up.
|
||||
const items = await expenseService.listCustomerRebills(customerId);
|
||||
const row = items.find((r) => r.id === docId);
|
||||
expect(row.status).toBe('open');
|
||||
expect(row.invoiceId).toBeNull();
|
||||
const pending = await db('inbound_documents')
|
||||
.where({ customer_account_id: customerId }).whereNull('billed_invoice_id')
|
||||
.whereIn('disposition', ['rebill', 'durchlaufend']).where('status', 'categorized');
|
||||
expect(pending.map((p) => p.id)).toContain(docId);
|
||||
});
|
||||
});
|
||||
|
||||
describe('collectRebillProofAttachments', () => {
|
||||
const businessDocs = () => path.join(process.env.STORAGE_PATH, 'business-docs', 'inbound', '2026');
|
||||
|
||||
async function enableIncoming() {
|
||||
const existing = await db('feature_flags').where({ key: 'incomingInvoices' }).first();
|
||||
if (existing) await db('feature_flags').where({ key: 'incomingInvoices' }).update({ value: 1 });
|
||||
else await db('feature_flags').insert({ key: 'incomingInvoices', value: 1 });
|
||||
flagCache.invalidateFeatureFlagCache();
|
||||
}
|
||||
|
||||
function writeProof(name) {
|
||||
fs.mkdirSync(businessDocs(), { recursive: true });
|
||||
const p = path.join(businessDocs(), name);
|
||||
fs.writeFileSync(p, '%PDF-1.4\n% test proof\n');
|
||||
return p;
|
||||
}
|
||||
|
||||
it('honours explicit selection, names Beleg-<inv#>, and marks a missing file', async () => {
|
||||
await enableIncoming();
|
||||
const customerId = await makeCustomer();
|
||||
const invId = await makeInvoice(customerId, 'scheduled', 'R-2026-1000');
|
||||
const invoice = await db('invoices').where({ id: invId }).first();
|
||||
|
||||
const good1 = await makeDoc(customerId, { billed_invoice_id: invId, file_path: writeProof('p1.pdf') });
|
||||
const good2 = await makeDoc(customerId, { billed_invoice_id: invId, file_path: writeProof('p2.pdf') });
|
||||
const missing = await makeDoc(customerId, { billed_invoice_id: invId, file_path: path.join(businessDocs(), 'nope.pdf') });
|
||||
|
||||
// Select the two good proofs → two attachments, suffixed because >1.
|
||||
const both = await rebillProofs.collectRebillProofAttachments(invoice, null, [good1, good2]);
|
||||
expect(both.map((a) => a.filename).sort()).toEqual(['Beleg-R-2026-1000-1.pdf', 'Beleg-R-2026-1000-2.pdf']);
|
||||
|
||||
// Select exactly one → single, unsuffixed.
|
||||
const one = await rebillProofs.collectRebillProofAttachments(invoice, null, [good1]);
|
||||
expect(one).toHaveLength(1);
|
||||
expect(one[0].filename).toBe('Beleg-R-2026-1000.pdf');
|
||||
|
||||
// Select the missing-file doc → no attachment, but a marker is persisted.
|
||||
const none = await rebillProofs.collectRebillProofAttachments(invoice, null, [missing]);
|
||||
expect(none).toHaveLength(0);
|
||||
const markerRow = await db('inbound_documents').where({ id: missing }).first('proof_attach_error');
|
||||
expect(markerRow.proof_attach_error).toBeTruthy();
|
||||
// A successful attach clears any prior marker.
|
||||
await rebillProofs.collectRebillProofAttachments(invoice, null, [good1]);
|
||||
const cleared = await db('inbound_documents').where({ id: good1 }).first('proof_attach_error');
|
||||
expect(cleared.proof_attach_error).toBeNull();
|
||||
});
|
||||
|
||||
it('resolves the all-or-none default from the per-customer override then global', async () => {
|
||||
await enableIncoming();
|
||||
const customerId = await makeCustomer();
|
||||
const invId = await makeInvoice(customerId, 'scheduled', 'R-2026-2000');
|
||||
const invoice = await db('invoices').where({ id: invId }).first();
|
||||
await makeDoc(customerId, { billed_invoice_id: invId, file_path: writeProof('d1.pdf') });
|
||||
|
||||
// Global default off, no override → none.
|
||||
const off = await rebillProofs.collectRebillProofAttachments(invoice, { rebill_attach_proof: null }, undefined);
|
||||
expect(off).toHaveLength(0);
|
||||
|
||||
// Per-customer override ON → all, regardless of the (off) global.
|
||||
const on = await rebillProofs.collectRebillProofAttachments(invoice, { rebill_attach_proof: true }, undefined);
|
||||
expect(on).toHaveLength(1);
|
||||
|
||||
// Global ON (no override) → all.
|
||||
await db('app_settings').insert({ setting_key: 'accounting_rebill_attach_proof', setting_value: JSON.stringify(true), setting_type: 'accounting' });
|
||||
const globalOn = await rebillProofs.collectRebillProofAttachments(invoice, { rebill_attach_proof: null }, undefined);
|
||||
expect(globalOn).toHaveLength(1);
|
||||
// Override OFF beats global ON.
|
||||
const overrideOff = await rebillProofs.collectRebillProofAttachments(invoice, { rebill_attach_proof: false }, undefined);
|
||||
expect(overrideOff).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('attaches nothing when the incoming-invoices flag is off', async () => {
|
||||
const existing = await db('feature_flags').where({ key: 'incomingInvoices' }).first();
|
||||
if (existing) await db('feature_flags').where({ key: 'incomingInvoices' }).update({ value: 0 });
|
||||
else await db('feature_flags').insert({ key: 'incomingInvoices', value: 0 });
|
||||
flagCache.invalidateFeatureFlagCache();
|
||||
|
||||
const customerId = await makeCustomer();
|
||||
const invId = await makeInvoice(customerId, 'scheduled', 'R-2026-3000');
|
||||
const invoice = await db('invoices').where({ id: invId }).first();
|
||||
const doc = await makeDoc(customerId, { billed_invoice_id: invId, file_path: writeProof('f1.pdf') });
|
||||
|
||||
const res = await rebillProofs.collectRebillProofAttachments(invoice, { rebill_attach_proof: true }, [doc]);
|
||||
expect(res).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,406 +0,0 @@
|
||||
/**
|
||||
* Reveal mode integration tests (#838).
|
||||
*
|
||||
* Pins the contract:
|
||||
* - effective visibility is computed at request time (isGalleryHidden):
|
||||
* reveal_at in the past opens the gate even before the scheduler stamps
|
||||
* - /photos returns the event shell with photos: [] + hidden_until_reveal
|
||||
* for plain guests; slideshow / client / admin-preview see everything
|
||||
* - image + download endpoints 403 with GALLERY_HIDDEN for plain guests
|
||||
* - the guest upload route is NOT gated (uploading while hidden is the point)
|
||||
* - the scheduler stamps revealed_at for due events, exactly once
|
||||
* - POST /events/:id/reveal stamps revealed_at (idempotent, 400 when the
|
||||
* mode is off); re-enabling reveal_mode clears revealed_at (re-hide)
|
||||
*/
|
||||
|
||||
const request = require('supertest');
|
||||
const express = require('express');
|
||||
const cookieParser = require('cookie-parser');
|
||||
const bcrypt = require('bcrypt');
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
const { bootCrmDb, seedMinimal } = require('./helpers/crmDb');
|
||||
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'reveal-test-secret';
|
||||
|
||||
const SLUG = 'reveal-test-event';
|
||||
|
||||
describe('Reveal mode (#838)', () => {
|
||||
let db;
|
||||
let cleanup;
|
||||
let app;
|
||||
let eventId;
|
||||
let photoIds;
|
||||
let adminToken;
|
||||
const { isGalleryHidden } = require('../../src/utils/revealMode');
|
||||
|
||||
const galleryToken = (extra = {}) => jwt.sign(
|
||||
{ eventId, eventSlug: SLUG, type: 'gallery', ...extra },
|
||||
process.env.JWT_SECRET,
|
||||
{ expiresIn: '1h', issuer: 'picpeak-auth' }
|
||||
);
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
await seedMinimal(db);
|
||||
|
||||
const inserted = await db('events').insert({
|
||||
slug: SLUG,
|
||||
event_type: 'wedding',
|
||||
event_name: 'Reveal Test',
|
||||
event_date: '2026-08-01',
|
||||
host_email: 'host@example.com',
|
||||
admin_email: 'admin@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: `/gallery/${SLUG}/share`,
|
||||
share_token: 'reveal-test-share',
|
||||
expires_at: new Date(Date.now() + 7 * 24 * 3600 * 1000).toISOString(),
|
||||
is_active: 1,
|
||||
is_archived: 0,
|
||||
is_draft: 0,
|
||||
allow_user_uploads: 1,
|
||||
reveal_mode: 1,
|
||||
created_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
eventId = inserted[0]?.id ?? inserted[0];
|
||||
|
||||
photoIds = [];
|
||||
for (let i = 0; i < 2; i++) {
|
||||
const p = await db('photos').insert({
|
||||
event_id: eventId,
|
||||
filename: `photo-${i}.jpg`,
|
||||
path: `events/reveal/${i}.jpg`,
|
||||
type: 'individual',
|
||||
uploaded_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
photoIds.push(p[0]?.id ?? p[0]);
|
||||
}
|
||||
|
||||
// Super admin for the admin routes.
|
||||
const superRole = await db('roles').where({ name: 'super_admin' }).first();
|
||||
const [rootId] = await db('admin_users').insert({
|
||||
username: 'reveal-admin',
|
||||
email: 'reveal-admin@example.com',
|
||||
password_hash: await bcrypt.hash('RevealAdmin123', 4),
|
||||
role_id: superRole.id,
|
||||
is_active: 1,
|
||||
created_at: new Date(),
|
||||
updated_at: new Date(),
|
||||
}).returning('id').then((r) => [r[0]?.id || r[0]]);
|
||||
adminToken = jwt.sign(
|
||||
{ id: rootId, username: 'reveal-admin', type: 'admin', role: 'super_admin', loginTime: Date.now() },
|
||||
process.env.JWT_SECRET,
|
||||
{ expiresIn: '1h', issuer: 'picpeak-auth' }
|
||||
);
|
||||
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use(cookieParser());
|
||||
app.use('/api/gallery', require('../../src/routes/gallery'));
|
||||
app.use('/api/secure-images', require('../../src/routes/secureImages'));
|
||||
app.use('/api/images', require('../../src/routes/protectedImages'));
|
||||
app.use('/api/gallery', require('../../src/routes/galleryFeedback'));
|
||||
app.use('/api/admin/events', require('../../src/routes/adminEvents'));
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => {
|
||||
if (cleanup) await cleanup();
|
||||
});
|
||||
|
||||
describe('effective visibility math (isGalleryHidden)', () => {
|
||||
const base = { reveal_mode: true, revealed_at: null, reveal_at: null };
|
||||
it('is hidden while armed and unrevealed, visible otherwise', () => {
|
||||
expect(isGalleryHidden({ ...base })).toBe(true);
|
||||
expect(isGalleryHidden({ ...base, reveal_mode: false })).toBe(false);
|
||||
expect(isGalleryHidden({ ...base, revealed_at: new Date() })).toBe(false);
|
||||
// reveal_at in the past opens the gate WITHOUT any stamp — time-exact.
|
||||
expect(isGalleryHidden({ ...base, reveal_at: new Date(Date.now() - 60_000) })).toBe(false);
|
||||
expect(isGalleryHidden({ ...base, reveal_at: new Date(Date.now() + 60_000) })).toBe(true);
|
||||
// SQLite 0/1 booleans
|
||||
expect(isGalleryHidden({ reveal_mode: 1, revealed_at: null, reveal_at: null })).toBe(true);
|
||||
expect(isGalleryHidden({ reveal_mode: 0, revealed_at: null, reveal_at: null })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('gallery routes while hidden', () => {
|
||||
it('/photos gives plain guests the shell with no photos and the flag', async () => {
|
||||
const res = await request(app)
|
||||
.get(`/api/gallery/${SLUG}/photos`)
|
||||
.set('Authorization', `Bearer ${galleryToken()}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.hidden_until_reveal).toBe(true);
|
||||
expect(res.body.photos).toEqual([]);
|
||||
expect(res.body.categories).toEqual([]);
|
||||
expect(res.body.event.event_name).toBe('Reveal Test');
|
||||
});
|
||||
|
||||
it('/photos serves the slideshow token everything (surprise beamer)', async () => {
|
||||
const res = await request(app)
|
||||
.get(`/api/gallery/${SLUG}/photos`)
|
||||
.set('Authorization', `Bearer ${galleryToken({ accessLevel: 'slideshow' })}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.hidden_until_reveal).toBe(false);
|
||||
expect(res.body.photos).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('/photos serves client access everything (host review)', async () => {
|
||||
const res = await request(app)
|
||||
.get(`/api/gallery/${SLUG}/photos`)
|
||||
.set('Authorization', `Bearer ${galleryToken({ accessLevel: 'client' })}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.hidden_until_reveal).toBe(false);
|
||||
expect(res.body.photos).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('/photos serves the admin preview everything (new transport: ?admin_preview=1 + admin cookie, even with a coexisting gallery session)', async () => {
|
||||
// #868/#981: reveal-mode hiding is bypassed for an admin preview via the
|
||||
// new transport (explicit flag + httpOnly admin_token cookie), NOT the
|
||||
// retired ?preview=<jwt>. The coexisting gallery Bearer must not shadow it.
|
||||
const res = await request(app)
|
||||
.get(`/api/gallery/${SLUG}/photos?admin_preview=1`)
|
||||
.set('Cookie', [`admin_token=${adminToken}`])
|
||||
.set('Authorization', `Bearer ${galleryToken()}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.hidden_until_reveal).toBe(false);
|
||||
expect(res.body.photos).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('image and download endpoints 403 with GALLERY_HIDDEN for plain guests', async () => {
|
||||
for (const url of [
|
||||
`/api/gallery/${SLUG}/thumbnail/${photoIds[0]}`,
|
||||
`/api/gallery/${SLUG}/photo/${photoIds[0]}`,
|
||||
`/api/gallery/${SLUG}/download/${photoIds[0]}`,
|
||||
`/api/gallery/${SLUG}/download-all`,
|
||||
`/api/gallery/${SLUG}/stats`,
|
||||
`/api/gallery/${SLUG}/hero/${photoIds[0]}`,
|
||||
]) {
|
||||
const res = await request(app).get(url).set('Authorization', `Bearer ${galleryToken()}`);
|
||||
expect(`${url}:${res.status}`).toBe(`${url}:403`);
|
||||
expect(res.body.code).toBe('GALLERY_HIDDEN');
|
||||
}
|
||||
});
|
||||
|
||||
it('image endpoints are NOT reveal-blocked for the slideshow token', async () => {
|
||||
const res = await request(app)
|
||||
.get(`/api/gallery/${SLUG}/thumbnail/${photoIds[0]}`)
|
||||
.set('Authorization', `Bearer ${galleryToken({ accessLevel: 'slideshow' })}`);
|
||||
// The seeded file doesn't exist on disk, so anything but the reveal
|
||||
// gate's 403 is fine here.
|
||||
expect(res.body.code).not.toBe('GALLERY_HIDDEN');
|
||||
});
|
||||
|
||||
it('/info exposes the effective hidden state without auth', async () => {
|
||||
const res = await request(app).get(`/api/gallery/${SLUG}/info`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.hidden_until_reveal).toBe(true);
|
||||
});
|
||||
|
||||
it('the guest upload route is not gated', async () => {
|
||||
const res = await request(app)
|
||||
.post(`/api/gallery/${eventId}/upload`)
|
||||
.set('Authorization', `Bearer ${galleryToken()}`)
|
||||
.send({});
|
||||
// Fails later for other reasons (no multipart body) — but never on the
|
||||
// reveal gate.
|
||||
expect(res.body.code).not.toBe('GALLERY_HIDDEN');
|
||||
});
|
||||
|
||||
it('legacy protected-image routes are reveal-gated for plain guests', async () => {
|
||||
for (const [method, url] of [
|
||||
['get', `/api/images/${SLUG}/photo/${photoIds[0]}/view`],
|
||||
['post', `/api/images/${SLUG}/photo/${photoIds[0]}/generate-secure-token`],
|
||||
['post', `/api/images/${SLUG}/photo/${photoIds[0]}/generate-url`],
|
||||
]) {
|
||||
const res = await request(app)[method](url).set('Authorization', `Bearer ${galleryToken()}`);
|
||||
expect(`${url}:${res.status}`).toBe(`${url}:403`);
|
||||
expect(res.body.code).toBe('GALLERY_HIDDEN');
|
||||
}
|
||||
});
|
||||
|
||||
it('feedback endpoints are reveal-gated; my-feedback degrades to empty', async () => {
|
||||
// Feedback must be enabled for the routes to get past their own gate.
|
||||
await db('event_feedback_settings').insert({
|
||||
event_id: eventId, feedback_enabled: 1, allow_likes: 1,
|
||||
created_at: new Date().toISOString(), updated_at: new Date().toISOString(),
|
||||
});
|
||||
const getRes = await request(app)
|
||||
.get(`/api/gallery/${SLUG}/photos/${photoIds[0]}/feedback`)
|
||||
.set('Authorization', `Bearer ${galleryToken()}`);
|
||||
expect(getRes.status).toBe(403);
|
||||
expect(getRes.body.code).toBe('GALLERY_HIDDEN');
|
||||
|
||||
const postRes = await request(app)
|
||||
.post(`/api/gallery/${SLUG}/photos/${photoIds[0]}/feedback`)
|
||||
.set('Authorization', `Bearer ${galleryToken()}`)
|
||||
.send({ feedback_type: 'like' });
|
||||
expect(postRes.status).toBe(403);
|
||||
expect(postRes.body.code).toBe('GALLERY_HIDDEN');
|
||||
|
||||
const mine = await request(app)
|
||||
.get(`/api/gallery/${SLUG}/my-feedback`)
|
||||
.set('Authorization', `Bearer ${galleryToken()}`);
|
||||
expect(mine.status).toBe(200);
|
||||
expect(mine.body).toEqual([]);
|
||||
});
|
||||
|
||||
it('secure-image token minting is reveal-gated for plain guests', async () => {
|
||||
const res = await request(app)
|
||||
.post(`/api/secure-images/${SLUG}/generate-token`)
|
||||
.set('Authorization', `Bearer ${galleryToken()}`)
|
||||
.send({ photoId: photoIds[0] });
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body.code).toBe('GALLERY_HIDDEN');
|
||||
});
|
||||
|
||||
it('customer-portal tokens (via:customer, no accessLevel) bypass reveal mode', async () => {
|
||||
const acct = await db('customer_accounts').insert({
|
||||
email: 'portal-customer@example.com',
|
||||
password_hash: 'x',
|
||||
is_active: 1,
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
const customerId = acct[0]?.id ?? acct[0];
|
||||
await db('event_customer_assignments').insert({
|
||||
event_id: eventId,
|
||||
customer_account_id: customerId,
|
||||
});
|
||||
|
||||
const res = await request(app)
|
||||
.get(`/api/gallery/${SLUG}/photos`)
|
||||
.set('Authorization', `Bearer ${galleryToken({ via: 'customer', customerId })}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.hidden_until_reveal).toBe(false);
|
||||
expect(res.body.photos).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('a reveal_at in the past opens the gate without any stamp', async () => {
|
||||
await db('events').where('id', eventId).update({ reveal_at: new Date(Date.now() - 60_000).toISOString() });
|
||||
const res = await request(app)
|
||||
.get(`/api/gallery/${SLUG}/photos`)
|
||||
.set('Authorization', `Bearer ${galleryToken()}`);
|
||||
expect(res.body.hidden_until_reveal).toBe(false);
|
||||
expect(res.body.photos).toHaveLength(2);
|
||||
await db('events').where('id', eventId).update({ reveal_at: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe('scheduler and admin reveal', () => {
|
||||
it('the scheduler stamps revealed_at for due events exactly once', async () => {
|
||||
const revealAt = new Date(Date.now() - 5 * 60_000);
|
||||
await db('events').where('id', eventId).update({ reveal_at: revealAt.toISOString(), revealed_at: null });
|
||||
|
||||
const { checkScheduledReveals } = require('../../src/services/revealScheduler');
|
||||
await checkScheduledReveals();
|
||||
|
||||
const asMs = (v) => new Date(v).getTime();
|
||||
const row = await db('events').where('id', eventId).first();
|
||||
expect(row.revealed_at).not.toBeNull();
|
||||
expect(asMs(row.revealed_at)).toBe(revealAt.getTime());
|
||||
expect(row.reveal_at).toBeNull(); // schedule consumed, like "Reveal now"
|
||||
|
||||
// Second pass no-ops (revealed_at already set).
|
||||
await checkScheduledReveals();
|
||||
const again = await db('events').where('id', eventId).first();
|
||||
expect(asMs(again.revealed_at)).toBe(revealAt.getTime());
|
||||
|
||||
await db('events').where('id', eventId).update({ reveal_at: null, revealed_at: null });
|
||||
});
|
||||
|
||||
it('POST /:id/reveal stamps revealed_at, clears the schedule, and is idempotent', async () => {
|
||||
await db('events').where('id', eventId).update({ reveal_at: new Date(Date.now() + 3600_000).toISOString() });
|
||||
const res = await request(app)
|
||||
.post(`/api/admin/events/${eventId}/reveal`)
|
||||
.set('Authorization', `Bearer ${adminToken}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.revealed_at).toBeTruthy();
|
||||
// "Reveal now" consumes the pending schedule.
|
||||
const cleared = await db('events').where('id', eventId).first();
|
||||
expect(cleared.reveal_at).toBeNull();
|
||||
|
||||
const first = res.body.revealed_at;
|
||||
const res2 = await request(app)
|
||||
.post(`/api/admin/events/${eventId}/reveal`)
|
||||
.set('Authorization', `Bearer ${adminToken}`);
|
||||
expect(res2.status).toBe(200);
|
||||
expect(res2.body.revealed_at).toBe(first);
|
||||
|
||||
// Guests see photos now.
|
||||
const gallery = await request(app)
|
||||
.get(`/api/gallery/${SLUG}/photos`)
|
||||
.set('Authorization', `Bearer ${galleryToken()}`);
|
||||
expect(gallery.body.hidden_until_reveal).toBe(false);
|
||||
expect(gallery.body.photos).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('re-enabling reveal_mode clears revealed_at (re-hide)', async () => {
|
||||
await db('events').where('id', eventId).update({ reveal_mode: 0 });
|
||||
const res = await request(app)
|
||||
.put(`/api/admin/events/${eventId}`)
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.send({ reveal_mode: true });
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
const row = await db('events').where('id', eventId).first();
|
||||
expect(row.revealed_at).toBeNull();
|
||||
|
||||
const gallery = await request(app)
|
||||
.get(`/api/gallery/${SLUG}/photos`)
|
||||
.set('Authorization', `Bearer ${galleryToken()}`);
|
||||
expect(gallery.body.hidden_until_reveal).toBe(true);
|
||||
});
|
||||
|
||||
it('scheduling a FUTURE reveal on a revealed gallery re-arms hiding', async () => {
|
||||
// State: revealed (previous tests). Saving a future schedule re-hides.
|
||||
await db('events').where('id', eventId).update({ revealed_at: new Date().toISOString() });
|
||||
const res = await request(app)
|
||||
.put(`/api/admin/events/${eventId}`)
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.send({ reveal_mode: true, reveal_at: new Date(Date.now() + 3600_000).toISOString() });
|
||||
expect(res.status).toBe(200);
|
||||
const row = await db('events').where('id', eventId).first();
|
||||
expect(row.revealed_at).toBeNull();
|
||||
|
||||
const gallery = await request(app)
|
||||
.get(`/api/gallery/${SLUG}/photos`)
|
||||
.set('Authorization', `Bearer ${galleryToken()}`);
|
||||
expect(gallery.body.hidden_until_reveal).toBe(true);
|
||||
await db('events').where('id', eventId).update({ reveal_at: null });
|
||||
});
|
||||
|
||||
it('re-arming without a schedule clears a stale PAST reveal_at', async () => {
|
||||
// Legacy/partial-API state: revealed with the old past schedule still
|
||||
// stored. {reveal_mode:false} then {reveal_mode:true} without
|
||||
// reveal_at must re-hide, not instantly re-open via the stale date.
|
||||
await db('events').where('id', eventId).update({
|
||||
reveal_mode: 0,
|
||||
revealed_at: new Date().toISOString(),
|
||||
reveal_at: new Date(Date.now() - 3600_000).toISOString(),
|
||||
});
|
||||
const res = await request(app)
|
||||
.put(`/api/admin/events/${eventId}`)
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.send({ reveal_mode: true });
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
const row = await db('events').where('id', eventId).first();
|
||||
expect(row.revealed_at).toBeNull();
|
||||
expect(row.reveal_at).toBeNull();
|
||||
|
||||
const gallery = await request(app)
|
||||
.get(`/api/gallery/${SLUG}/photos`)
|
||||
.set('Authorization', `Bearer ${galleryToken()}`);
|
||||
expect(gallery.body.hidden_until_reveal).toBe(true);
|
||||
expect(gallery.body.photos).toEqual([]);
|
||||
});
|
||||
|
||||
it('POST /:id/reveal 400s while reveal mode is off', async () => {
|
||||
await db('events').where('id', eventId).update({ reveal_mode: 0, revealed_at: null });
|
||||
const res = await request(app)
|
||||
.post(`/api/admin/events/${eventId}/reveal`)
|
||||
.set('Authorization', `Bearer ${adminToken}`);
|
||||
expect(res.status).toBe(400);
|
||||
await db('events').where('id', eventId).update({ reveal_mode: 1 });
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,150 +0,0 @@
|
||||
/**
|
||||
* Slideshow photo source (#1015).
|
||||
*
|
||||
* The bug: with `lightbox_preview_enabled` off (the default), /photos emitted
|
||||
* `preview_url: null`, so the slideshow's `preview_url || hero_url || url`
|
||||
* chain fell through to `hero_url` — a 1920x1080 `fit: 'cover'` centre crop
|
||||
* meant for gallery header banners. With the "Black Bars (No crop)" fit the
|
||||
* show then letterboxed an already-cropped frame: portrait photos lost their
|
||||
* top and bottom and the setting looked broken.
|
||||
*
|
||||
* The contract pinned here: `slideshow_url` points at the aspect-preserved
|
||||
* preview tier and is emitted for image photos REGARDLESS of the lightbox
|
||||
* toggle, so the slideshow never has a reason to reach for `hero_url`.
|
||||
* `preview_url` itself must stay gated — the lightbox opt-in is unchanged.
|
||||
*/
|
||||
|
||||
const request = require('supertest');
|
||||
const express = require('express');
|
||||
const cookieParser = require('cookie-parser');
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
const { bootCrmDb, seedMinimal } = require('./helpers/crmDb');
|
||||
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'slideshow-src-test-secret';
|
||||
|
||||
const SLUG = 'slideshow-source-event';
|
||||
|
||||
describe('Slideshow photo source (#1015)', () => {
|
||||
let db;
|
||||
let cleanup;
|
||||
let app;
|
||||
let eventId;
|
||||
let imagePhotoId;
|
||||
let videoPhotoId;
|
||||
|
||||
const galleryToken = () => jwt.sign(
|
||||
{ eventId, eventSlug: SLUG, type: 'gallery' },
|
||||
process.env.JWT_SECRET,
|
||||
{ expiresIn: '1h', issuer: 'picpeak-auth' }
|
||||
);
|
||||
|
||||
const setLightboxPreview = async (on) => {
|
||||
await db('app_settings').where({ setting_key: 'lightbox_preview_enabled' }).del();
|
||||
await db('app_settings').insert({
|
||||
setting_key: 'lightbox_preview_enabled',
|
||||
setting_value: JSON.stringify(on),
|
||||
setting_type: 'general',
|
||||
updated_at: new Date().toISOString(),
|
||||
});
|
||||
};
|
||||
|
||||
const fetchPhotos = async () => {
|
||||
const res = await request(app)
|
||||
.get(`/api/gallery/${SLUG}/photos`)
|
||||
.set('Authorization', `Bearer ${galleryToken()}`)
|
||||
.expect(200);
|
||||
return res.body.photos;
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
await seedMinimal(db);
|
||||
|
||||
const inserted = await db('events').insert({
|
||||
slug: SLUG,
|
||||
event_type: 'wedding',
|
||||
event_name: 'Slideshow Source Test',
|
||||
event_date: '2026-08-01',
|
||||
host_email: 'host@example.com',
|
||||
admin_email: 'admin@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: `/gallery/${SLUG}/share`,
|
||||
share_token: 'slideshow-source-share',
|
||||
expires_at: new Date(Date.now() + 7 * 24 * 3600 * 1000).toISOString(),
|
||||
is_active: 1,
|
||||
is_archived: 0,
|
||||
is_draft: 0,
|
||||
created_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
eventId = inserted[0]?.id ?? inserted[0];
|
||||
|
||||
const img = await db('photos').insert({
|
||||
event_id: eventId,
|
||||
filename: 'portrait.jpg',
|
||||
path: 'events/slideshow-source/portrait.jpg',
|
||||
type: 'individual',
|
||||
mime_type: 'image/jpeg',
|
||||
uploaded_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
imagePhotoId = img[0]?.id ?? img[0];
|
||||
|
||||
const vid = await db('photos').insert({
|
||||
event_id: eventId,
|
||||
filename: 'clip.mp4',
|
||||
path: 'events/slideshow-source/clip.mp4',
|
||||
type: 'individual',
|
||||
media_type: 'video',
|
||||
mime_type: 'video/mp4',
|
||||
uploaded_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
videoPhotoId = vid[0]?.id ?? vid[0];
|
||||
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use(cookieParser());
|
||||
app.use('/api/gallery', require('../../src/routes/gallery'));
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => {
|
||||
if (cleanup) await cleanup();
|
||||
});
|
||||
|
||||
it('emits slideshow_url for image photos even when lightbox previews are OFF', async () => {
|
||||
await setLightboxPreview(false);
|
||||
const photos = await fetchPhotos();
|
||||
const image = photos.find((p) => p.id === imagePhotoId);
|
||||
|
||||
expect(image.slideshow_url).toBe(`/api/gallery/${SLUG}/preview/${imagePhotoId}`);
|
||||
// The regression: this is what used to be null, pushing the show to hero.
|
||||
expect(image.preview_url).toBeNull();
|
||||
});
|
||||
|
||||
it('leaves preview_url gated so the lightbox opt-in is unchanged', async () => {
|
||||
await setLightboxPreview(true);
|
||||
const photos = await fetchPhotos();
|
||||
const image = photos.find((p) => p.id === imagePhotoId);
|
||||
|
||||
expect(image.preview_url).toBe(`/api/gallery/${SLUG}/preview/${imagePhotoId}`);
|
||||
expect(image.slideshow_url).toBe(image.preview_url);
|
||||
});
|
||||
|
||||
it('never points the slideshow at the cover-cropped hero tier', async () => {
|
||||
await setLightboxPreview(false);
|
||||
const photos = await fetchPhotos();
|
||||
const image = photos.find((p) => p.id === imagePhotoId);
|
||||
|
||||
// hero_url still ships (the gallery header uses it) — it just must not be
|
||||
// what the slideshow resolves to.
|
||||
expect(image.hero_url).toBe(`/api/gallery/${SLUG}/hero/${imagePhotoId}`);
|
||||
expect(image.slideshow_url).not.toBe(image.hero_url);
|
||||
});
|
||||
|
||||
it('emits slideshow_url: null for videos, which have no preview tier', async () => {
|
||||
await setLightboxPreview(false);
|
||||
const photos = await fetchPhotos();
|
||||
const video = photos.find((p) => p.id === videoPhotoId);
|
||||
|
||||
expect(video.slideshow_url).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,136 +0,0 @@
|
||||
/**
|
||||
* SQLite epoch-timestamp normalization (#485 follow-up).
|
||||
*
|
||||
* On SQLite, timestamp columns written with a raw `new Date()` through knex
|
||||
* hold epoch-millisecond numbers. Postgres returns ISO strings, so frontend
|
||||
* code written against Postgres calls parseISO() and crashes on native
|
||||
* (SQLite) installs — the exact class fixed for admin Users in #485, which
|
||||
* listed api tokens / photos / activity as an out-of-scope follow-up.
|
||||
*
|
||||
* Pins:
|
||||
* - gallery /photos serializes uploaded_at / captured_at as ISO strings
|
||||
* even when the row holds an epoch number (pre-fix archive restores)
|
||||
* - the api-tokens list serializes created_at / expires_at / last_used_at /
|
||||
* revoked_at as ISO strings for epoch-stored rows
|
||||
*/
|
||||
|
||||
const request = require('supertest');
|
||||
const express = require('express');
|
||||
const cookieParser = require('cookie-parser');
|
||||
const bcrypt = require('bcrypt');
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
const { bootCrmDb, seedMinimal } = require('./helpers/crmDb');
|
||||
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'epoch-test-secret';
|
||||
|
||||
const SLUG = 'epoch-test-event';
|
||||
const ISO_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/;
|
||||
|
||||
describe('SQLite epoch timestamp normalization', () => {
|
||||
let db;
|
||||
let cleanup;
|
||||
let app;
|
||||
let eventId;
|
||||
let adminToken;
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
await seedMinimal(db);
|
||||
|
||||
const inserted = await db('events').insert({
|
||||
slug: SLUG,
|
||||
event_type: 'wedding',
|
||||
event_name: 'Epoch Test',
|
||||
event_date: '2026-08-01',
|
||||
host_email: 'host@example.com',
|
||||
admin_email: 'admin@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: `/gallery/${SLUG}/share`,
|
||||
share_token: 'epoch-test-share',
|
||||
expires_at: new Date(Date.now() + 7 * 24 * 3600 * 1000).toISOString(),
|
||||
is_active: 1,
|
||||
is_archived: 0,
|
||||
is_draft: 0,
|
||||
created_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
eventId = inserted[0]?.id ?? inserted[0];
|
||||
|
||||
// The pre-fix corruption shape: epoch numbers in timestamp columns.
|
||||
await db('photos').insert({
|
||||
event_id: eventId,
|
||||
filename: 'restored.jpg',
|
||||
path: 'events/epoch/restored.jpg',
|
||||
type: 'individual',
|
||||
uploaded_at: Date.now() - 3600_000,
|
||||
captured_at: Date.now() - 7200_000,
|
||||
});
|
||||
|
||||
const superRole = await db('roles').where({ name: 'super_admin' }).first();
|
||||
const [rootId] = await db('admin_users').insert({
|
||||
username: 'epoch-admin',
|
||||
email: 'epoch-admin@example.com',
|
||||
password_hash: await bcrypt.hash('EpochAdmin123', 4),
|
||||
role_id: superRole.id,
|
||||
is_active: 1,
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
}).returning('id').then((r) => [r[0]?.id || r[0]]);
|
||||
adminToken = jwt.sign(
|
||||
{ id: rootId, username: 'epoch-admin', type: 'admin', role: 'super_admin', loginTime: Date.now() },
|
||||
process.env.JWT_SECRET,
|
||||
{ expiresIn: '1h', issuer: 'picpeak-auth' }
|
||||
);
|
||||
|
||||
await db('api_tokens').insert({
|
||||
name: 'epoch-token',
|
||||
hashed_token: 'x'.repeat(64),
|
||||
preview: 'pk_test…abcd',
|
||||
scopes: JSON.stringify(['events:read']),
|
||||
created_by: rootId,
|
||||
created_at: Date.now() - 86400_000,
|
||||
last_used_at: Date.now() - 3600_000,
|
||||
revoked_at: Date.now() - 60_000,
|
||||
});
|
||||
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use(cookieParser());
|
||||
app.use('/api/gallery', require('../../src/routes/gallery'));
|
||||
app.use('/api/admin/api-tokens', require('../../src/routes/adminApiTokens'));
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => {
|
||||
if (cleanup) await cleanup();
|
||||
});
|
||||
|
||||
it('gallery /photos serializes epoch-stored uploaded_at/captured_at as ISO strings', async () => {
|
||||
const galleryToken = jwt.sign(
|
||||
{ eventId, eventSlug: SLUG, type: 'gallery' },
|
||||
process.env.JWT_SECRET,
|
||||
{ expiresIn: '1h', issuer: 'picpeak-auth' }
|
||||
);
|
||||
const res = await request(app)
|
||||
.get(`/api/gallery/${SLUG}/photos`)
|
||||
.set('Authorization', `Bearer ${galleryToken}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.photos).toHaveLength(1);
|
||||
const photo = res.body.photos[0];
|
||||
expect(typeof photo.uploaded_at).toBe('string');
|
||||
expect(photo.uploaded_at).toMatch(ISO_RE);
|
||||
expect(photo.captured_at).toMatch(ISO_RE);
|
||||
});
|
||||
|
||||
it('api-tokens list serializes epoch-stored timestamps as ISO strings', async () => {
|
||||
const res = await request(app)
|
||||
.get('/api/admin/api-tokens')
|
||||
.set('Authorization', `Bearer ${adminToken}`);
|
||||
expect(res.status).toBe(200);
|
||||
const token = res.body.find((t) => t.name === 'epoch-token');
|
||||
expect(token).toBeTruthy();
|
||||
for (const field of ['created_at', 'last_used_at', 'revoked_at']) {
|
||||
expect(`${field}:${typeof token[field]}`).toBe(`${field}:string`);
|
||||
expect(token[field]).toMatch(ISO_RE);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -14,7 +14,6 @@
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
jest.mock('../../src/utils/tokenRevocation', () => ({ isTokenRevoked: jest.fn().mockResolvedValue(false) }));
|
||||
jest.mock('../../src/utils/sessionCutoff', () => ({ isTokenBeforeCutoff: jest.fn().mockResolvedValue(false) }));
|
||||
jest.mock('../../src/utils/logger', () => ({ warn: jest.fn(), error: jest.fn(), debug: jest.fn(), info: jest.fn() }));
|
||||
|
||||
// The joined query throws whatever the test stages; the role-less fallback
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
/**
|
||||
* #868 — the admin gallery-preview gate. isAdminPreview must fail CLOSED: it
|
||||
* grants the draft/password bypass only for an explicit `?admin_preview=1` flag
|
||||
* AND a verified admin JWT (type 'admin', issuer 'picpeak-auth') read from the
|
||||
* httpOnly admin_token cookie or a Bearer header — never from the URL, never for
|
||||
* a guest/gallery token.
|
||||
*/
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'admin-preview-test-secret';
|
||||
const jwt = require('jsonwebtoken');
|
||||
const { isAdminPreview } = require('../../src/middleware/gallery');
|
||||
|
||||
// Read the secret at call time — a jest setup file can set JWT_SECRET after this
|
||||
// module loads, and isAdminPreview verifies against the live value.
|
||||
const adminToken = () => jwt.sign({ type: 'admin', id: 1 }, process.env.JWT_SECRET, { issuer: 'picpeak-auth' });
|
||||
const galleryToken = () => jwt.sign({ type: 'gallery', eventId: 1 }, process.env.JWT_SECRET, { issuer: 'picpeak-auth' });
|
||||
|
||||
function req({ flag, cookie, bearer } = {}) {
|
||||
return {
|
||||
query: flag === undefined ? {} : { admin_preview: flag },
|
||||
cookies: cookie ? { admin_token: cookie } : {},
|
||||
headers: bearer ? { authorization: `Bearer ${bearer}` } : {},
|
||||
};
|
||||
}
|
||||
|
||||
describe('isAdminPreview (#868) fails closed', () => {
|
||||
it('false without the explicit flag, even with a valid admin cookie (plain link stays guest-identical)', () => {
|
||||
expect(isAdminPreview(req({ cookie: adminToken() }))).toBe(false);
|
||||
});
|
||||
|
||||
it('false with the flag but no session token', () => {
|
||||
expect(isAdminPreview(req({ flag: '1' }))).toBe(false);
|
||||
});
|
||||
|
||||
it('true with the flag + a valid admin cookie', () => {
|
||||
expect(isAdminPreview(req({ flag: '1', cookie: adminToken() }))).toBe(true);
|
||||
});
|
||||
|
||||
it('true with the flag + a valid admin Bearer header', () => {
|
||||
expect(isAdminPreview(req({ flag: '1', bearer: adminToken() }))).toBe(true);
|
||||
});
|
||||
|
||||
it('false for a gallery (guest) token — must be type admin', () => {
|
||||
expect(isAdminPreview(req({ flag: '1', cookie: galleryToken() }))).toBe(false);
|
||||
});
|
||||
|
||||
it('true from the admin cookie even when a gallery Bearer is also present (#981 coexisting session)', () => {
|
||||
expect(isAdminPreview(req({ flag: '1', cookie: adminToken(), bearer: galleryToken() }))).toBe(true);
|
||||
});
|
||||
|
||||
it('false when only a gallery Bearer is present — a gallery header can never satisfy it (#981)', () => {
|
||||
expect(isAdminPreview(req({ flag: '1', bearer: galleryToken() }))).toBe(false);
|
||||
});
|
||||
|
||||
it('false on a tampered token', () => {
|
||||
expect(isAdminPreview(req({ flag: '1', cookie: `${adminToken()}x` }))).toBe(false);
|
||||
});
|
||||
|
||||
it('false on the wrong issuer', () => {
|
||||
const t = jwt.sign({ type: 'admin' }, process.env.JWT_SECRET, { issuer: 'not-picpeak' });
|
||||
expect(isAdminPreview(req({ flag: '1', cookie: t }))).toBe(false);
|
||||
});
|
||||
|
||||
it('false when the flag is anything other than exactly "1"', () => {
|
||||
expect(isAdminPreview(req({ flag: 'true', cookie: adminToken() }))).toBe(false);
|
||||
expect(isAdminPreview(req({ flag: '0', cookie: adminToken() }))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,122 +0,0 @@
|
||||
/**
|
||||
* HTTP tests for the gallery QR endpoints (#836):
|
||||
* GET /api/admin/events/:id/qr (PNG / SVG)
|
||||
* GET /api/admin/events/:id/qr-print (table-card / poster PDF)
|
||||
* Same real-SQLite harness as adminEvents.smoke.test.js.
|
||||
*/
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.TEST_DATABASE_PATH = path.join(
|
||||
fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-events-qr-')), 'db.sqlite'
|
||||
);
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'admin-events-qr-test-secret';
|
||||
|
||||
const express = require('express');
|
||||
const cookieParser = require('cookie-parser');
|
||||
const request = require('supertest');
|
||||
const { bootCrmDb, seedMinimal, assignAdminRole, mintAdminToken } = require('../integration/helpers/crmDb');
|
||||
|
||||
async function insertEvent(db, adminId, over = {}) {
|
||||
const base = {
|
||||
slug: `ev-${Math.random().toString(16).slice(2)}`,
|
||||
event_type: 'wedding',
|
||||
event_name: 'QR Test Wedding',
|
||||
event_date: '2026-05-29',
|
||||
host_email: 'host@example.com',
|
||||
admin_email: 'admin@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: `/gallery/share-${Math.random().toString(16).slice(2)}`,
|
||||
share_token: `st-${Math.random().toString(16).slice(2)}`,
|
||||
expires_at: new Date(Date.now() + 7 * 24 * 3600 * 1000).toISOString(),
|
||||
is_active: 1, is_archived: 0, is_draft: 0,
|
||||
created_by: adminId,
|
||||
created_at: new Date().toISOString(),
|
||||
...over,
|
||||
};
|
||||
const r = await db('events').insert(base).returning('id');
|
||||
return r[0]?.id ?? r[0];
|
||||
}
|
||||
|
||||
describe('admin event QR endpoints', () => {
|
||||
let db; let cleanup; let app; let adminId; let token;
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
({ adminId } = await seedMinimal(db));
|
||||
await assignAdminRole(db, adminId, 'super_admin');
|
||||
token = mintAdminToken(adminId);
|
||||
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use(cookieParser());
|
||||
app.use('/api/admin/events', require('../../src/routes/adminEvents'));
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
app.use((err, req, res, next) => {
|
||||
res.status(err.statusCode || err.status || 500).json({ error: err.message, code: err.code });
|
||||
});
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => { await cleanup(); });
|
||||
|
||||
beforeEach(async () => { await db('events').del(); });
|
||||
|
||||
const auth = (req) => req.set('Authorization', `Bearer ${token}`);
|
||||
|
||||
it('401s without an admin token', async () => {
|
||||
const eventId = await insertEvent(db, adminId);
|
||||
const res = await request(app).get(`/api/admin/events/${eventId}/qr`);
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('returns a PNG QR by default', async () => {
|
||||
const eventId = await insertEvent(db, adminId);
|
||||
const res = await auth(request(app).get(`/api/admin/events/${eventId}/qr`)).buffer();
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers['content-type']).toBe('image/png');
|
||||
// PNG magic bytes
|
||||
expect(res.body.slice(0, 4)).toEqual(Buffer.from([0x89, 0x50, 0x4e, 0x47]));
|
||||
});
|
||||
|
||||
it('returns an SVG QR when requested', async () => {
|
||||
const eventId = await insertEvent(db, adminId);
|
||||
// supertest doesn't text-parse image/svg+xml — buffer and decode manually.
|
||||
const res = await auth(request(app).get(`/api/admin/events/${eventId}/qr?format=svg`)).buffer();
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers['content-type']).toMatch(/image\/svg\+xml/);
|
||||
expect(Buffer.from(res.body).toString('utf8')).toContain('<svg');
|
||||
});
|
||||
|
||||
it('sets attachment disposition with download=1', async () => {
|
||||
const eventId = await insertEvent(db, adminId);
|
||||
const res = await auth(request(app).get(`/api/admin/events/${eventId}/qr?download=1`)).buffer();
|
||||
expect(res.headers['content-disposition']).toMatch(/^attachment/);
|
||||
});
|
||||
|
||||
// 30s: the print PDFs embed the full IBM Plex Sans TTFs (~200 KB each) —
|
||||
// font parsing + subsetting exceeds jest's 5s default on slower CI runners.
|
||||
it.each(['table-card', 'poster'])('renders the %s print PDF', async (template) => {
|
||||
const eventId = await insertEvent(db, adminId);
|
||||
const res = await auth(
|
||||
request(app).get(`/api/admin/events/${eventId}/qr-print?template=${template}&lang=de`)
|
||||
).buffer();
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers['content-type']).toBe('application/pdf');
|
||||
expect(res.body.slice(0, 4).toString()).toBe('%PDF');
|
||||
}, 120000);
|
||||
|
||||
it('409s when the event has no share link', async () => {
|
||||
// events.share_link is NOT NULL — an empty string is the closest real-world
|
||||
// "no share link" shape (no token extractable from it either).
|
||||
const eventId = await insertEvent(db, adminId, { share_link: '', share_token: null });
|
||||
const res = await auth(request(app).get(`/api/admin/events/${eventId}/qr`));
|
||||
expect(res.status).toBe(409);
|
||||
});
|
||||
|
||||
it('404s for a non-existent event', async () => {
|
||||
const res = await auth(request(app).get('/api/admin/events/999999/qr'));
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
});
|
||||
@@ -201,34 +201,6 @@ describe('admin events CRUD endpoints (smoke)', () => {
|
||||
});
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
// #894 — per-event password-page logo toggle: false hides, null
|
||||
// restores the default (show).
|
||||
it('stores login_logo_visible: false and clears it back to NULL', async () => {
|
||||
const id = await insertEvent(db, adminId);
|
||||
const hide = await auth(request(app).put(`/api/admin/events/${id}`)).send({
|
||||
login_logo_visible: false,
|
||||
});
|
||||
expect(hide.status).toBe(200);
|
||||
let row = await db('events').where({ id }).first();
|
||||
expect([false, 0]).toContain(row.login_logo_visible);
|
||||
|
||||
const clear = await auth(request(app).put(`/api/admin/events/${id}`)).send({
|
||||
login_logo_visible: null,
|
||||
});
|
||||
expect(clear.status).toBe(200);
|
||||
row = await db('events').where({ id }).first();
|
||||
expect(row.login_logo_visible).toBeNull();
|
||||
|
||||
// The string "false" passes isBoolean() validation — it must be
|
||||
// parsed, not treated as a truthy string (would store 1 = show).
|
||||
const hideStr = await auth(request(app).put(`/api/admin/events/${id}`)).send({
|
||||
login_logo_visible: 'false',
|
||||
});
|
||||
expect(hideStr.status).toBe(200);
|
||||
row = await db('events').where({ id }).first();
|
||||
expect([false, 0]).toContain(row.login_logo_visible);
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /:id', () => {
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
/**
|
||||
* Role-editor self-amplification guard (migration 175 / adminRoles).
|
||||
*
|
||||
* `roles.manage` must be a DELEGATION primitive, not root escalation: a
|
||||
* non-super_admin holder can only grant permissions their OWN role already
|
||||
* holds, and can't edit their own role. super_admin bypasses. Pins
|
||||
* userManagementService.createRole / updateRole (assertActorMayGrant).
|
||||
*/
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.TEST_DATABASE_PATH = path.join(
|
||||
fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-roleguard-')), 'db.sqlite',
|
||||
);
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'roleguard-test-secret';
|
||||
process.env.STORAGE_PATH = fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-roleguard-storage-'));
|
||||
|
||||
const { bootCrmDb, seedMinimal, assignAdminRole } = require('../integration/helpers/crmDb');
|
||||
const svc = require('../../src/services/userManagementService');
|
||||
const { clearPermissionCache } = require('../../src/middleware/permissions');
|
||||
|
||||
describe('role editor — self-amplification guard', () => {
|
||||
let db; let cleanup;
|
||||
let superId; let mgrRoleId; let mgrId;
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
({ adminId: superId } = await seedMinimal(db));
|
||||
await assignAdminRole(db, superId, 'super_admin');
|
||||
|
||||
// A non-super role that CAN manage roles but only holds a couple of perms.
|
||||
const mgrRole = await svc.createRole(
|
||||
{ name: 'limited_mgr', permissions: ['roles.manage', 'events.view'] },
|
||||
superId,
|
||||
);
|
||||
mgrRoleId = mgrRole.id;
|
||||
const ins = await db('admin_users').insert({
|
||||
username: 'mgr', email: 'mgr@example.com', password_hash: 'x',
|
||||
role_id: mgrRoleId, must_change_password: false, created_at: new Date(),
|
||||
}).returning('id');
|
||||
mgrId = ins[0]?.id ?? ins[0];
|
||||
clearPermissionCache();
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => { if (cleanup) await cleanup(); });
|
||||
|
||||
it('super_admin can grant any permission', async () => {
|
||||
const r = await svc.createRole(
|
||||
{ name: 'power_role', permissions: ['settings.banking', 'users.delete'] },
|
||||
superId,
|
||||
);
|
||||
expect(r.permissions).toEqual(expect.arrayContaining(['settings.banking', 'users.delete']));
|
||||
});
|
||||
|
||||
it('non-super cannot grant a permission its own role lacks', async () => {
|
||||
await expect(
|
||||
svc.createRole({ name: 'sneaky', permissions: ['events.view', 'settings.banking'] }, mgrId),
|
||||
).rejects.toThrow(/only grant permissions your own role/i);
|
||||
});
|
||||
|
||||
it('non-super can create a role within its own permissions', async () => {
|
||||
const r = await svc.createRole({ name: 'viewer_lite', permissions: ['events.view'] }, mgrId);
|
||||
expect(r.permissions).toEqual(['events.view']);
|
||||
});
|
||||
|
||||
it('non-super cannot edit its own role', async () => {
|
||||
await expect(
|
||||
svc.updateRole(mgrRoleId, { permissions: ['roles.manage', 'events.view'] }, mgrId),
|
||||
).rejects.toThrow(/cannot edit your own role/i);
|
||||
});
|
||||
|
||||
it('non-super cannot escalate another role beyond its own permissions', async () => {
|
||||
const adminRole = await db('roles').where({ name: 'admin' }).first();
|
||||
await expect(
|
||||
svc.updateRole(adminRole.id, { permissions: ['settings.banking'] }, mgrId),
|
||||
).rejects.toThrow(/only grant permissions your own role/i);
|
||||
});
|
||||
|
||||
it('the built-in team_photographer name is reserved', async () => {
|
||||
await expect(
|
||||
svc.createRole({ name: 'team_photographer', permissions: [] }, superId),
|
||||
).rejects.toThrow(/reserved/i);
|
||||
});
|
||||
});
|
||||
@@ -1,95 +0,0 @@
|
||||
/**
|
||||
* Protected-key boundary on the generic settings writers (migration 175).
|
||||
*
|
||||
* A role with settings.edit but NOT settings.domains (the "office manager" this
|
||||
* PR enables) must be able to save the General tab — which re-posts
|
||||
* general_site_url on every save — as long as the URL is UNCHANGED, and must be
|
||||
* 403'd only when it actually tries to change a protected key. Regression pin for
|
||||
* the change-detection fix (the presence-only check over-fired on every save).
|
||||
*/
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.TEST_DATABASE_PATH = path.join(
|
||||
fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-setkeys-')), 'db.sqlite',
|
||||
);
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'setkeys-test-secret';
|
||||
process.env.STORAGE_PATH = fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-setkeys-storage-'));
|
||||
|
||||
const request = require('supertest');
|
||||
const express = require('express');
|
||||
const cookieParser = require('cookie-parser');
|
||||
const {
|
||||
bootCrmDb, seedMinimal, assignAdminRole, mintAdminToken,
|
||||
} = require('../integration/helpers/crmDb');
|
||||
const svc = require('../../src/services/userManagementService');
|
||||
const { clearPermissionCache } = require('../../src/middleware/permissions');
|
||||
|
||||
const STORED_URL = 'https://stored.example';
|
||||
|
||||
describe('settings protected-key boundary (/general)', () => {
|
||||
let db; let cleanup; let app;
|
||||
let superTok; let mgrTok;
|
||||
|
||||
const auth = (req, tok) => req.set('Authorization', `Bearer ${tok}`);
|
||||
const readSiteUrl = async () => {
|
||||
const row = await db('app_settings').where({ setting_key: 'general_site_url' }).first();
|
||||
return row ? JSON.parse(row.setting_value) : null;
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
const { adminId: superId } = await seedMinimal(db);
|
||||
await assignAdminRole(db, superId, 'super_admin');
|
||||
superTok = mintAdminToken(superId);
|
||||
|
||||
// Office-manager role: settings.view + settings.edit, NOT settings.domains.
|
||||
const mgrRole = await svc.createRole(
|
||||
{ name: 'office_mgr', permissions: ['settings.view', 'settings.edit'] },
|
||||
superId,
|
||||
);
|
||||
const ins = await db('admin_users').insert({
|
||||
username: 'office', email: 'office@example.com', password_hash: 'x',
|
||||
role_id: mgrRole.id, must_change_password: false, created_at: new Date(),
|
||||
}).returning('id');
|
||||
mgrTok = mintAdminToken(ins[0]?.id ?? ins[0]);
|
||||
|
||||
await db('app_settings').insert({
|
||||
setting_key: 'general_site_url', setting_value: JSON.stringify(STORED_URL), setting_type: 'general',
|
||||
});
|
||||
clearPermissionCache();
|
||||
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use(cookieParser());
|
||||
app.use('/api/admin/settings', require('../../src/routes/adminSettings'));
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => { if (cleanup) await cleanup(); });
|
||||
|
||||
it('settings.edit role can save /general when general_site_url is unchanged', async () => {
|
||||
const res = await auth(request(app).put('/api/admin/settings/general'), mgrTok)
|
||||
.send({ general_site_url: STORED_URL, general_max_file_size_mb: 50 });
|
||||
expect(res.status).not.toBe(403);
|
||||
expect(res.status).toBe(200);
|
||||
expect(await readSiteUrl()).toBe(STORED_URL);
|
||||
});
|
||||
|
||||
it('settings.edit role is 403d when it actually changes general_site_url', async () => {
|
||||
const res = await auth(request(app).put('/api/admin/settings/general'), mgrTok)
|
||||
.send({ general_site_url: 'https://evil.example' });
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body.code).toBe('FORBIDDEN');
|
||||
expect(res.body.keys.map((k) => k.key)).toContain('general_site_url');
|
||||
expect(await readSiteUrl()).toBe(STORED_URL); // unchanged
|
||||
});
|
||||
|
||||
it('super_admin can change general_site_url', async () => {
|
||||
const res = await auth(request(app).put('/api/admin/settings/general'), superTok)
|
||||
.send({ general_site_url: 'https://new.example' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(await readSiteUrl()).toBe('https://new.example');
|
||||
});
|
||||
});
|
||||
@@ -32,17 +32,9 @@ jest.mock('../../src/database/db', () => {
|
||||
if (table === 'admin_users') {
|
||||
let rowFilter = () => true;
|
||||
return {
|
||||
// The session route joins roles for the adminUser payload (#798);
|
||||
// fake rows carry no role fields, so the join is a pass-through.
|
||||
leftJoin() {
|
||||
return this;
|
||||
},
|
||||
where(criteria) {
|
||||
rowFilter = (row) => {
|
||||
return Object.entries(criteria).every(([rawKey, v]) => {
|
||||
// Joined queries prefix columns ('admin_users.id') — the fake
|
||||
// rows use bare names.
|
||||
const k = rawKey.replace(/^admin_users\./, '');
|
||||
return Object.entries(criteria).every(([k, v]) => {
|
||||
if (k === 'is_active') return Boolean(row.is_active) === Boolean(v);
|
||||
return row[k] === v;
|
||||
});
|
||||
@@ -58,12 +50,7 @@ jest.mock('../../src/database/db', () => {
|
||||
if (!row) return undefined;
|
||||
if (!this._cols) return row;
|
||||
const out = {};
|
||||
for (const c of this._cols) {
|
||||
// Support 'table.col' and 'table.col as alias' shapes.
|
||||
const [source, alias] = c.split(/\s+as\s+/i);
|
||||
const bare = source.includes('.') ? source.split('.').pop() : source;
|
||||
out[alias || bare] = row[bare];
|
||||
}
|
||||
for (const c of this._cols) out[c] = row[c];
|
||||
return out;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -51,13 +51,11 @@ describe('authorization / ownership gaps', () => {
|
||||
}).returning('id');
|
||||
adminId = ins[0]?.id ?? ins[0];
|
||||
await assignAdminRole(db, adminId, 'admin');
|
||||
// Grant settings.integrations to the admin role BEFORE any request populates
|
||||
// the 60s permission cache, so the revoke test exercises the ownership check
|
||||
// (404) rather than the missing-permission gate (403). Migration 174 split
|
||||
// API-token management out of the catch-all settings.edit into the dedicated
|
||||
// settings.integrations perm; this models a custom role that carries it —
|
||||
// the scenario GHSA-gprq needs.
|
||||
await grantPermissionToRole('admin', 'settings.integrations');
|
||||
// Grant settings.edit to the admin role BEFORE any request populates the
|
||||
// 60s permission cache, so the revoke test exercises the ownership check
|
||||
// (404) rather than the missing-permission gate (403). This models a
|
||||
// custom role that carries settings.edit — the scenario GHSA-gprq needs.
|
||||
await grantPermissionToRole('admin', 'settings.edit');
|
||||
adminTok = mintAdminToken(adminId);
|
||||
|
||||
app = express();
|
||||
@@ -98,7 +96,7 @@ describe('authorization / ownership gaps', () => {
|
||||
expect(res.body.find((t) => t.id === superTokenId)).toBeDefined();
|
||||
});
|
||||
|
||||
it('a non-owner (with settings.integrations) cannot revoke another admin\'s token', async () => {
|
||||
it('a non-owner (with settings.edit) cannot revoke another admin\'s token', async () => {
|
||||
const res = await auth(request(app).delete(`/api/admin/api-tokens/${superTokenId}`), adminTok);
|
||||
expect(res.status).toBe(404);
|
||||
const row = await db('api_tokens').where({ id: superTokenId }).first();
|
||||
|
||||
@@ -1,190 +0,0 @@
|
||||
/**
|
||||
* SQLite boolean coercion in the guest gallery surface (#1028).
|
||||
*
|
||||
* SQLite stores booleans as 0/1; Postgres stores true/false. The /photos
|
||||
* payload and every download guard compared strictly against `true`/`false`,
|
||||
* so on SQLite:
|
||||
*
|
||||
* allow_downloads: 0 !== false → true (button shown while disabled)
|
||||
* allow_user_uploads: 1 === true → false (button hidden while enabled)
|
||||
* if (allow_downloads === false) → never fires, so ALL download endpoints
|
||||
* kept serving with downloads switched off
|
||||
*
|
||||
* The harness runs on SQLite, so these assertions exercise the real engine
|
||||
* values rather than a mock. Every test here fails on the unfixed code.
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.TEST_DATABASE_PATH = path.join(
|
||||
fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-sqlite-flags-')), 'db.sqlite',
|
||||
);
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'sqlite-flags-test-secret';
|
||||
process.env.STORAGE_PATH = fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-sqlite-flags-storage-'));
|
||||
|
||||
const request = require('supertest');
|
||||
const express = require('express');
|
||||
const cookieParser = require('cookie-parser');
|
||||
const { bootCrmDb, seedMinimal } = require('../integration/helpers/crmDb');
|
||||
|
||||
const SLUG = 'sqlite-flags-gallery';
|
||||
|
||||
describe('gallery flags survive SQLite 0/1 storage (#1028)', () => {
|
||||
let db; let cleanup; let app; let eventId; let photoId;
|
||||
|
||||
async function setEventFlags(patch) {
|
||||
await db('events').where('id', eventId).update(patch);
|
||||
}
|
||||
|
||||
async function getPayload() {
|
||||
const res = await request(app).get(`/api/gallery/${SLUG}/photos`);
|
||||
expect(res.status).toBe(200);
|
||||
return res.body.event;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
await seedMinimal(db);
|
||||
|
||||
const ev = await db('events').insert({
|
||||
slug: SLUG,
|
||||
event_type: 'wedding',
|
||||
event_name: 'SQLite Flags',
|
||||
event_date: '2026-08-01',
|
||||
host_email: 'h@example.com',
|
||||
admin_email: 'a@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: `/gallery/${SLUG}/s`,
|
||||
share_token: 'sqlite-flags-share',
|
||||
expires_at: new Date(Date.now() + 7 * 864e5).toISOString(),
|
||||
is_active: 1,
|
||||
is_archived: 0,
|
||||
is_draft: 0,
|
||||
// Password-free so verifyGalleryAccess takes the public path and loads
|
||||
// the row with SELECT * — i.e. the raw 0/1 values, same as production.
|
||||
require_password: 0,
|
||||
created_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
eventId = ev[0]?.id ?? ev[0];
|
||||
|
||||
const ph = await db('photos').insert({
|
||||
event_id: eventId,
|
||||
filename: 'p.jpg',
|
||||
path: `${SLUG}/p.jpg`,
|
||||
type: 'individual',
|
||||
uploaded_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
photoId = ph[0]?.id ?? ph[0];
|
||||
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use(cookieParser());
|
||||
app.use('/api/gallery', require('../../src/routes/gallery'));
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => { if (cleanup) await cleanup(); });
|
||||
|
||||
test('the engine under test really is SQLite storing 0/1', async () => {
|
||||
expect(['sqlite3', 'better-sqlite3']).toContain(db.client.config.client);
|
||||
await setEventFlags({ allow_downloads: 0 });
|
||||
const row = await db('events').where('id', eventId).first('allow_downloads');
|
||||
expect(row.allow_downloads).toBe(0);
|
||||
});
|
||||
|
||||
describe('with downloads disabled (allow_downloads = 0)', () => {
|
||||
beforeAll(async () => {
|
||||
await setEventFlags({ allow_downloads: 0, allow_user_uploads: 1 });
|
||||
});
|
||||
|
||||
test('payload reports allow_downloads false (was true — header button shown)', async () => {
|
||||
expect((await getPayload()).allow_downloads).toBe(false);
|
||||
});
|
||||
|
||||
test('payload reports allow_user_uploads true (was false — upload button hidden)', async () => {
|
||||
expect((await getPayload()).allow_user_uploads).toBe(true);
|
||||
});
|
||||
|
||||
test('single-photo download is refused', async () => {
|
||||
const res = await request(app).get(`/api/gallery/${SLUG}/download/${photoId}`);
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
test('download-all is refused', async () => {
|
||||
const res = await request(app).get(`/api/gallery/${SLUG}/download-all`);
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
test('download-selected is refused', async () => {
|
||||
const res = await request(app)
|
||||
.post(`/api/gallery/${SLUG}/download-selected`)
|
||||
.send({ photo_ids: [photoId] });
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
test('download-jobs is refused', async () => {
|
||||
const res = await request(app).post(`/api/gallery/${SLUG}/download-jobs`).send({});
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe('with downloads enabled (allow_downloads = 1)', () => {
|
||||
beforeAll(async () => {
|
||||
await setEventFlags({ allow_downloads: 1, allow_user_uploads: 0 });
|
||||
});
|
||||
|
||||
test('payload reports allow_downloads true / allow_user_uploads false', async () => {
|
||||
const event = await getPayload();
|
||||
expect(event.allow_downloads).toBe(true);
|
||||
expect(event.allow_user_uploads).toBe(false);
|
||||
});
|
||||
|
||||
test('download-all is no longer refused', async () => {
|
||||
const res = await request(app).get(`/api/gallery/${SLUG}/download-all`);
|
||||
expect(res.status).not.toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe('protection flags', () => {
|
||||
test('0/1 protection toggles are reported the way they are stored', async () => {
|
||||
await setEventFlags({
|
||||
disable_right_click: 1,
|
||||
enable_devtools_protection: 1,
|
||||
use_canvas_rendering: 1,
|
||||
watermark_downloads: 1,
|
||||
overlay_protection: 0,
|
||||
});
|
||||
const event = await getPayload();
|
||||
expect(event.disable_right_click).toBe(true);
|
||||
expect(event.enable_devtools_protection).toBe(true);
|
||||
expect(event.use_canvas_rendering).toBe(true);
|
||||
expect(event.watermark_downloads).toBe(true);
|
||||
expect(event.overlay_protection).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('per-category download blocking (#640) on SQLite', () => {
|
||||
test('a category with allow_downloads = 0 is reported as blocked', async () => {
|
||||
const cat = await db('photo_categories').insert({
|
||||
name: 'Blocked', slug: 'blocked', event_id: eventId, is_global: 0, allow_downloads: 0,
|
||||
}).returning('id');
|
||||
const categoryId = cat[0]?.id ?? cat[0];
|
||||
await db('photos').where('id', photoId).update({ category_id: categoryId });
|
||||
|
||||
await setEventFlags({ allow_downloads: 1 });
|
||||
const res = await request(app).get(`/api/gallery/${SLUG}/photos`);
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
const category = res.body.categories.find((c) => c.id === categoryId);
|
||||
expect(category.allow_downloads).toBe(false);
|
||||
const photo = res.body.photos.find((p) => p.id === photoId);
|
||||
expect(photo.category_allow_downloads).toBe(false);
|
||||
|
||||
// …and the per-category guard on the single-photo route fires.
|
||||
const dl = await request(app).get(`/api/gallery/${SLUG}/download/${photoId}`);
|
||||
expect(dl.status).toBe(403);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -67,11 +67,10 @@ async function insertEvent(db, over = {}) {
|
||||
describe('public Live Slideshow routes', () => {
|
||||
let db; let cleanup; let app;
|
||||
|
||||
// bootCrmDb runs the full migration set against a fresh SQLite file. The
|
||||
// chain keeps growing, and a 30s pin here blocked the 3.97.0-beta.0
|
||||
// release PR on a slow runner. Hook-argument timeouts OVERRIDE the 120s
|
||||
// jest.config default (same trap as the jest.setTimeout pins raised in
|
||||
// #860) — keep this at 120000, matching the config.
|
||||
// bootCrmDb runs the full migration set against a fresh SQLite file and the
|
||||
// chain keeps growing via backports. Hook-argument timeouts OVERRIDE the
|
||||
// 120s jest.config default (same trap as the jest.setTimeout pins) — keep
|
||||
// this at 120000, matching the config.
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
await seedMinimal(db);
|
||||
@@ -99,12 +98,7 @@ describe('public Live Slideshow routes', () => {
|
||||
await setFlag(db, 'slideshow', true);
|
||||
});
|
||||
|
||||
// QR overlay: supertest's Host is loopback, and a loopback base is now
|
||||
// suppressed rather than encoded — the kiosk passes its reachable
|
||||
// window.location.origin, so the QR tests do the same.
|
||||
const KIOSK_ORIGIN = 'https://gallery.example.com';
|
||||
const stateUrl = (token = TOKEN) => `/api/gallery/${SLUG}/show/${token}/state?origin=${encodeURIComponent(KIOSK_ORIGIN)}`;
|
||||
const stateUrlNoOrigin = (token = TOKEN) => `/api/gallery/${SLUG}/show/${token}/state`;
|
||||
const stateUrl = (token = TOKEN) => `/api/gallery/${SLUG}/show/${token}/state`;
|
||||
|
||||
describe('resolveSlideshow guards', () => {
|
||||
it('200 + per-event display settings on a live link', async () => {
|
||||
@@ -233,58 +227,6 @@ describe('public Live Slideshow routes', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('slideshowSettings — QR overlay cascade (#837)', () => {
|
||||
async function enableGlobalQr() {
|
||||
await setSetting(db, 'slideshow_qr_enabled', true);
|
||||
await setSetting(db, 'slideshow_qr_position', 'top-right');
|
||||
await setSetting(db, 'slideshow_qr_opacity', 80);
|
||||
await setSetting(db, 'slideshow_qr_size', 18);
|
||||
}
|
||||
|
||||
it('inherits the global QR overlay when show_qr is NULL', async () => {
|
||||
await insertEvent(db, { show_qr: null });
|
||||
await enableGlobalQr();
|
||||
const res = await request(app).get(stateUrl());
|
||||
expect(res.body.qr).toMatchObject({
|
||||
position: 'top-right',
|
||||
opacity: 80,
|
||||
size: 18,
|
||||
});
|
||||
// Share-link QR ships as a PNG data URI — no client QR lib needed.
|
||||
expect(res.body.qr.data_url).toMatch(/^data:image\/png;base64,/);
|
||||
});
|
||||
|
||||
it('is null by default (global off, no override)', async () => {
|
||||
await insertEvent(db, { show_qr: null });
|
||||
const res = await request(app).get(stateUrl());
|
||||
expect(res.body.qr).toBeNull();
|
||||
});
|
||||
|
||||
it('per-event OFF override hides the QR even when the global is on', async () => {
|
||||
await insertEvent(db, { show_qr: 0 });
|
||||
await enableGlobalQr();
|
||||
const res = await request(app).get(stateUrl());
|
||||
expect(res.body.qr).toBeNull();
|
||||
});
|
||||
|
||||
it('per-event ON override shows the QR even when the global is off', async () => {
|
||||
await insertEvent(db, { show_qr: 1 });
|
||||
const res = await request(app).get(stateUrl());
|
||||
expect(res.body.qr).not.toBeNull();
|
||||
expect(res.body.qr.data_url).toMatch(/^data:image\/png;base64,/);
|
||||
// Look falls back to the global defaults.
|
||||
expect(res.body.qr.position).toBe('bottom-left');
|
||||
});
|
||||
|
||||
it('suppresses the QR when no guest-reachable origin exists (loopback base, no kiosk origin)', async () => {
|
||||
await insertEvent(db, { show_qr: 1 });
|
||||
const res = await request(app).get(stateUrlNoOrigin());
|
||||
// Encoding localhost would send scanning phones to THEIR localhost —
|
||||
// no QR beats a broken QR (codex review of #848, confirmation round).
|
||||
expect(res.body.qr).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('display-only token guards (#646 review concern 1)', () => {
|
||||
// Mint a real slideshow JWT, then prove it is denied on the
|
||||
// download / upload / feedback routes (display-only contract).
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
/**
|
||||
* Regression tests for the file-watcher concurrency bound.
|
||||
*
|
||||
* chokidar fires 'add' once per file — with no ignoreInitial option the boot
|
||||
* scan fires it for every existing file, and a bulk drop fires it for every
|
||||
* new one at once. Unbounded handlers each run DB lookups plus a full sharp
|
||||
* pipeline (sharp.concurrency(2) only caps libvips threads WITHIN one
|
||||
* operation), which can OOM small hosts. Both 'add' and 'unlink' must go
|
||||
* through the shared p-limit gate.
|
||||
*
|
||||
* Adapted from the filpgame fork (426ca491), extended to cover 'unlink'.
|
||||
*/
|
||||
|
||||
const mockLimit = jest.fn((operation) => Promise.resolve().then(operation));
|
||||
const mockPLimit = jest.fn(() => mockLimit);
|
||||
const mockHandlers = {};
|
||||
const mockWatcher = {
|
||||
on: jest.fn((event, handler) => {
|
||||
mockHandlers[event] = handler;
|
||||
return mockWatcher;
|
||||
}),
|
||||
};
|
||||
|
||||
// Shared instances captured by the mock factories: jest.isolateModules re-runs
|
||||
// each factory in a fresh registry, so the factories must return these same
|
||||
// objects for the test to observe calls made inside the isolated module.
|
||||
const mockLogger = { error: jest.fn(), warn: jest.fn(), info: jest.fn(), debug: jest.fn() };
|
||||
// Chainable no-row query — enough for removePhoto's lookup/delete calls.
|
||||
const mockDb = jest.fn(() => ({
|
||||
where: jest.fn().mockReturnThis(),
|
||||
first: jest.fn().mockResolvedValue(null),
|
||||
delete: jest.fn().mockResolvedValue(0),
|
||||
}));
|
||||
|
||||
jest.mock('p-limit', () => mockPLimit);
|
||||
jest.mock('chokidar', () => ({
|
||||
watch: jest.fn(() => mockWatcher),
|
||||
}));
|
||||
jest.mock('../../src/database/db', () => ({ db: mockDb }));
|
||||
jest.mock('../../src/utils/logger', () => mockLogger);
|
||||
jest.mock('../../src/services/imageProcessor', () => ({
|
||||
generateThumbnail: jest.fn(),
|
||||
generateVideoPlaceholder: jest.fn(),
|
||||
}));
|
||||
jest.mock('../../src/services/videoProcessor', () => ({
|
||||
isVideoMimeType: jest.fn(() => false),
|
||||
}));
|
||||
jest.mock('../../src/services/downloadZipService', () => ({ invalidate: jest.fn() }));
|
||||
jest.mock('../../src/utils/dbCompat', () => ({
|
||||
formatBoolean: jest.fn((value) => value),
|
||||
}));
|
||||
|
||||
const loadFileWatcher = () => {
|
||||
let fileWatcher;
|
||||
jest.isolateModules(() => {
|
||||
fileWatcher = require('../../src/services/fileWatcher');
|
||||
});
|
||||
return fileWatcher;
|
||||
};
|
||||
|
||||
describe('fileWatcher concurrency bound', () => {
|
||||
const originalBackend = process.env.STORAGE_BACKEND;
|
||||
const originalConcurrency = process.env.FILE_WATCHER_CONCURRENCY;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
Object.keys(mockHandlers).forEach((key) => delete mockHandlers[key]);
|
||||
process.env.STORAGE_BACKEND = 'local';
|
||||
delete process.env.FILE_WATCHER_CONCURRENCY;
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
if (originalBackend === undefined) delete process.env.STORAGE_BACKEND;
|
||||
else process.env.STORAGE_BACKEND = originalBackend;
|
||||
if (originalConcurrency === undefined) delete process.env.FILE_WATCHER_CONCURRENCY;
|
||||
else process.env.FILE_WATCHER_CONCURRENCY = originalConcurrency;
|
||||
});
|
||||
|
||||
it.each([
|
||||
[undefined, 2], // default
|
||||
['3', 3], // explicit
|
||||
['0', 1], // floored to 1
|
||||
['-4', 1], // floored to 1
|
||||
['invalid', 2], // falls back to default
|
||||
])('configures the limiter with FILE_WATCHER_CONCURRENCY=%s as %i', (configured, expected) => {
|
||||
if (configured === undefined) delete process.env.FILE_WATCHER_CONCURRENCY;
|
||||
else process.env.FILE_WATCHER_CONCURRENCY = configured;
|
||||
|
||||
loadFileWatcher().startFileWatcher();
|
||||
|
||||
expect(mockPLimit).toHaveBeenCalledWith(expected);
|
||||
});
|
||||
|
||||
it('routes add events through the shared limiter', async () => {
|
||||
loadFileWatcher().startFileWatcher();
|
||||
|
||||
expect(mockHandlers.add).toEqual(expect.any(Function));
|
||||
mockHandlers.add('/outside-watch-root'); // early-returns inside processNewPhoto
|
||||
|
||||
expect(mockLimit).toHaveBeenCalledTimes(1);
|
||||
expect(mockLimit).toHaveBeenCalledWith(expect.any(Function));
|
||||
await mockLimit.mock.results[0].value;
|
||||
});
|
||||
|
||||
it('routes unlink events through the same limiter', async () => {
|
||||
loadFileWatcher().startFileWatcher();
|
||||
|
||||
expect(mockHandlers.unlink).toEqual(expect.any(Function));
|
||||
mockHandlers.unlink('/outside-watch-root'); // early-returns inside removePhoto
|
||||
|
||||
expect(mockLimit).toHaveBeenCalledTimes(1);
|
||||
await mockLimit.mock.results[0].value;
|
||||
});
|
||||
|
||||
it('logs instead of rejecting when a queued handler throws', async () => {
|
||||
loadFileWatcher().startFileWatcher();
|
||||
|
||||
const failure = new Error('boom');
|
||||
mockLimit.mockImplementationOnce(() => Promise.reject(failure));
|
||||
mockHandlers.add('/whatever');
|
||||
|
||||
await new Promise(process.nextTick);
|
||||
expect(mockLogger.error).toHaveBeenCalledWith('Error processing new photo:', failure);
|
||||
});
|
||||
});
|
||||
@@ -1,30 +0,0 @@
|
||||
/**
|
||||
* Locks the process-wide Sharp memory guards. The file-watcher concurrency
|
||||
* bound (FILE_WATCHER_CONCURRENCY) assumes these caps stay in place — they
|
||||
* limit libvips threads/cache WITHIN one operation while p-limit bounds the
|
||||
* number of parallel pipelines. From the filpgame fork (426ca491).
|
||||
*/
|
||||
|
||||
const mockSharp = jest.fn();
|
||||
mockSharp.cache = jest.fn();
|
||||
mockSharp.concurrency = jest.fn();
|
||||
|
||||
jest.mock('sharp', () => mockSharp);
|
||||
|
||||
jest.mock('../../src/utils/logger', () => ({
|
||||
error: jest.fn(),
|
||||
warn: jest.fn(),
|
||||
info: jest.fn(),
|
||||
debug: jest.fn(),
|
||||
}));
|
||||
|
||||
describe('imageProcessor Sharp configuration', () => {
|
||||
it('disables the Sharp cache and caps libvips concurrency', () => {
|
||||
jest.isolateModules(() => {
|
||||
require('../../src/services/imageProcessor');
|
||||
});
|
||||
|
||||
expect(mockSharp.cache).toHaveBeenCalledWith(false);
|
||||
expect(mockSharp.concurrency).toHaveBeenCalledWith(2);
|
||||
});
|
||||
});
|
||||
@@ -1,50 +0,0 @@
|
||||
/**
|
||||
* Unit tests for the RAW/DNG handling helpers (#821). The actual exiftool
|
||||
* extraction can only be exercised in the built image (exiftool isn't a dev
|
||||
* dependency), so these cover the gating logic: which files are treated as RAW,
|
||||
* and that ordinary images pass through untouched (zero cost / no extraction).
|
||||
*/
|
||||
const path = require('path');
|
||||
const { isRawFilename, withProcessableImage, RAW_EXTENSIONS } = require('../../src/services/imageProcessor');
|
||||
|
||||
describe('isRawFilename', () => {
|
||||
it('recognises common RAW / DNG extensions', () => {
|
||||
for (const ext of ['dng', 'cr2', 'cr3', 'nef', 'arw', 'raf', 'rw2', 'orf']) {
|
||||
expect(isRawFilename(`IMG_1234.${ext}`)).toBe(true);
|
||||
expect(isRawFilename(`IMG_1234.${ext.toUpperCase()}`)).toBe(true); // case-insensitive
|
||||
}
|
||||
});
|
||||
|
||||
it('does not treat ordinary images/videos as RAW', () => {
|
||||
for (const name of ['photo.jpg', 'photo.jpeg', 'photo.png', 'photo.webp', 'clip.mp4', 'clip.mov', 'photo.heic']) {
|
||||
expect(isRawFilename(name)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('is null/empty safe', () => {
|
||||
expect(isRawFilename(null)).toBe(false);
|
||||
expect(isRawFilename('')).toBe(false);
|
||||
expect(isRawFilename('noextension')).toBe(false);
|
||||
});
|
||||
|
||||
it('RAW_EXTENSIONS includes dng (Apple ProRAW)', () => {
|
||||
expect(RAW_EXTENSIONS.has('dng')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('withProcessableImage', () => {
|
||||
it('passes ordinary images through with no extraction and a no-op cleanup', async () => {
|
||||
const localPath = '/tmp/whatever/photo.jpg';
|
||||
const proc = await withProcessableImage(localPath, 'photo.jpg');
|
||||
expect(proc.path).toBe(localPath); // unchanged — sharp reads it directly
|
||||
expect(proc.outputBasename).toBeUndefined(); // generators keep their default naming
|
||||
await expect(Promise.resolve(proc.cleanup())).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('routes RAW files to extraction (which fails cleanly without exiftool/preview)', async () => {
|
||||
// In the dev sandbox exiftool isn't installed, so extraction throws — the
|
||||
// caller turns that into a normal processing failure. In the built image
|
||||
// (exiftool present) this instead returns the embedded JPEG preview.
|
||||
await expect(withProcessableImage('/tmp/whatever/IMG_1234.dng', 'IMG_1234.dng')).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,155 +0,0 @@
|
||||
/**
|
||||
* Regression tests for logActivity calls inside transactions (#850 review
|
||||
* find). createContract / updateContract / createStorno / reissueInvoice
|
||||
* called logActivity() (and contract paths also adminActor()) from inside
|
||||
* a knex transaction WITHOUT the trx executor. On single-connection SQLite
|
||||
* the audit insert then waits on a second pool connection while the trx
|
||||
* holds the only one — a 60s acquire-timeout stall per call, after which
|
||||
* logActivity's catch swallows the failure and the audit row is silently
|
||||
* lost. Postgres was unaffected.
|
||||
*
|
||||
* The observable fix: the activity_logs rows now exist, and the calls
|
||||
* complete without waiting on the pool. The shrunken acquire timeout
|
||||
* below makes any reintroduced deadlock fail the test quickly instead
|
||||
* of appearing to pass after a long stall.
|
||||
*/
|
||||
const path = require('path');
|
||||
const {
|
||||
bootCrmDb, seedMinimal, assignAdminRole,
|
||||
} = require('../integration/helpers/crmDb');
|
||||
|
||||
jest.setTimeout(120000);
|
||||
|
||||
let db;
|
||||
let cleanup;
|
||||
let tmpDir;
|
||||
let adminId;
|
||||
let customerId;
|
||||
let contractService;
|
||||
let invoiceService;
|
||||
|
||||
const prevCwd = process.cwd();
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup, tmpDir } = await bootCrmDb());
|
||||
// Business-doc artifacts land under process.cwd()/storage — isolate.
|
||||
process.chdir(tmpDir);
|
||||
|
||||
// A reintroduced in-trx pool grab should fail fast (2s), not stall 60s.
|
||||
db.client.pool.acquireTimeoutMillis = 2000;
|
||||
|
||||
// node-sqlite3 detects Date bindings via the NATIVE realm's Date —
|
||||
// under jest's vm sandbox that check fails and Dates stringify to
|
||||
// "[object Object]". Normalize to ISO strings on the client prototype
|
||||
// (transaction clients are Object.create()d from it). Same shim as
|
||||
// crmMintPaths.test.js.
|
||||
const clientProto = Object.getPrototypeOf(db.client);
|
||||
const origQuery = clientProto._query;
|
||||
clientProto._query = function patchedQuery(connection, obj) {
|
||||
if (obj && Array.isArray(obj.bindings)) {
|
||||
obj.bindings = obj.bindings.map(
|
||||
(b) => (b && typeof b === 'object' && typeof b.toISOString === 'function' ? b.toISOString() : b),
|
||||
);
|
||||
}
|
||||
return origQuery.call(this, connection, obj);
|
||||
};
|
||||
|
||||
({ adminId, customerId } = await seedMinimal(db));
|
||||
await assignAdminRole(db, adminId, 'super_admin');
|
||||
|
||||
contractService = require('../../src/services/contractService');
|
||||
invoiceService = require('../../src/services/invoiceService');
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => {
|
||||
process.chdir(prevCwd);
|
||||
if (cleanup) await cleanup();
|
||||
});
|
||||
|
||||
test('createContract persists the contract_created audit row (was silently lost on SQLite)', async () => {
|
||||
const contractId = await contractService.createContract({
|
||||
customerAccountId: customerId,
|
||||
title: 'Audit-Trail-Vertrag',
|
||||
}, adminId);
|
||||
|
||||
const row = await db('activity_logs')
|
||||
.where({ activity_type: 'contract_created' })
|
||||
.orderBy('id', 'desc')
|
||||
.first();
|
||||
expect(row).toBeTruthy();
|
||||
expect(JSON.parse(row.metadata).contractId).toBe(contractId);
|
||||
expect(row.actor_type).toBe('admin');
|
||||
});
|
||||
|
||||
test('updateContract persists the contract_updated audit row', async () => {
|
||||
const contractId = await contractService.createContract({
|
||||
customerAccountId: customerId,
|
||||
title: 'Vorher',
|
||||
}, adminId);
|
||||
|
||||
await contractService.updateContract(contractId, { title: 'Nachher' }, adminId);
|
||||
|
||||
const row = await db('activity_logs')
|
||||
.where({ activity_type: 'contract_updated' })
|
||||
.orderBy('id', 'desc')
|
||||
.first();
|
||||
expect(row).toBeTruthy();
|
||||
expect(JSON.parse(row.metadata).contractId).toBe(contractId);
|
||||
});
|
||||
|
||||
test('cancelInvoice (Storno mint) persists the invoice_cancelled_via_storno audit row', async () => {
|
||||
const { invoiceIds } = await invoiceService.createInvoice({
|
||||
customerAccountId: customerId,
|
||||
currency: 'CHF',
|
||||
vatRate: 0,
|
||||
lineItems: [
|
||||
{ position: 1, quantity: 1, description: 'Coverage', unit_price_minor: 100000, discount_percent: 0 },
|
||||
],
|
||||
}, adminId);
|
||||
const id = invoiceIds[0];
|
||||
await db('invoices').where({ id }).update({ status: 'sent', sent_at: new Date(), updated_at: new Date() });
|
||||
|
||||
const result = await invoiceService.cancelInvoice(id, adminId);
|
||||
expect(result.cancelled).toBe(true);
|
||||
|
||||
const row = await db('activity_logs')
|
||||
.where({ activity_type: 'invoice_cancelled_via_storno' })
|
||||
.orderBy('id', 'desc')
|
||||
.first();
|
||||
expect(row).toBeTruthy();
|
||||
const meta = JSON.parse(row.metadata);
|
||||
expect(meta.invoiceId).toBe(id);
|
||||
expect(meta.stornoId).toBe(result.stornoId);
|
||||
});
|
||||
|
||||
test('reissueInvoice completes on SQLite and persists the invoice_reissued audit row', async () => {
|
||||
const { invoiceIds } = await invoiceService.createInvoice({
|
||||
customerAccountId: customerId,
|
||||
currency: 'CHF',
|
||||
vatRate: 0,
|
||||
lineItems: [
|
||||
{ position: 1, quantity: 1, description: 'Album', unit_price_minor: 50000, discount_percent: 0 },
|
||||
],
|
||||
}, adminId);
|
||||
const id = invoiceIds[0];
|
||||
await db('invoices').where({ id }).update({ status: 'sent', sent_at: new Date(), updated_at: new Date() });
|
||||
|
||||
// Pre-fix this stalled inside the wrapping transaction (createInvoice's
|
||||
// global-connection reads vs. the single-connection pool) and aborted
|
||||
// before the replacement existed — with the Storno already committed.
|
||||
const result = await invoiceService.reissueInvoice(id, adminId);
|
||||
expect(result.id).toBeGreaterThan(0);
|
||||
expect(result.replaces).toBe(id);
|
||||
|
||||
const replacement = await db('invoices').where({ id: result.id }).first();
|
||||
expect(replacement.replaces_invoice_id).toBe(id);
|
||||
|
||||
const row = await db('activity_logs')
|
||||
.where({ activity_type: 'invoice_reissued' })
|
||||
.orderBy('id', 'desc')
|
||||
.first();
|
||||
expect(row).toBeTruthy();
|
||||
expect(JSON.parse(row.metadata).newInvoiceId).toBe(result.id);
|
||||
});
|
||||
|
||||
void path; // referenced for parity with sibling suites
|
||||
@@ -234,66 +234,3 @@ describe('renderInvoiceToBuffer — Storno branch', () => {
|
||||
expect(stornoBuf.length).toBeLessThan(invoiceBuf.length);
|
||||
});
|
||||
});
|
||||
|
||||
// VAT free-text note (#794) + multi-page page-number placement. Same
|
||||
// constraint as the Storno tests: PDFKit Flate-compresses content streams,
|
||||
// so we can't grep the note text — but the page-TREE objects are NOT
|
||||
// compressed, so `/Type /Page` (not `/Pages`) is countable to assert
|
||||
// pagination, and a byte-size delta proves the note actually rendered.
|
||||
describe('renderInvoiceToBuffer — VAT note + multi-page footer (#794)', () => {
|
||||
function baseCtx(overrides = {}) {
|
||||
return {
|
||||
locale: 'de', currency: 'CHF',
|
||||
issuer: { companyName: 'AcmeCo' },
|
||||
recipient: {
|
||||
companyName: 'KundenCo', addressLine1: 'Strasse 1',
|
||||
city: 'Bern', postalCode: '3000',
|
||||
},
|
||||
lineItems: [{
|
||||
quantity: 1, description: 'Photo session',
|
||||
unitPriceMinor: 30000, lineTotalMinor: 30000,
|
||||
parentLineItemId: null, parentPosition: null,
|
||||
}],
|
||||
totals: {
|
||||
netAmountMinor: 30000, vatRate: 0, vatAmountMinor: 0,
|
||||
shippingAmountMinor: 0, totalAmountMinor: 30000,
|
||||
},
|
||||
doc: { invoiceNumber: 'R-2026-0042', issueDate: '2026-04-12' },
|
||||
qrFormat: 'none',
|
||||
paymentTerm: { netDays: 30 },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
const pageCount = (buf) => (buf.toString('latin1').match(/\/Type\s*\/Page(?![s])/g) || []).length;
|
||||
const VAT_NOTE = 'Gemäß § 6 Abs. 1 Z 27 UStG 1994 wird keine Umsatzsteuer berechnet (Kleinunternehmer).';
|
||||
|
||||
it('renders the VAT note on a single-page invoice (adds content, valid PDF)', async () => {
|
||||
const withNote = await pdfService.renderInvoiceToBuffer(baseCtx({ vatNote: VAT_NOTE }));
|
||||
const without = await pdfService.renderInvoiceToBuffer(baseCtx());
|
||||
expect(withNote.slice(0, 4).toString('ascii')).toBe('%PDF');
|
||||
expect(pageCount(withNote)).toBe(1);
|
||||
expect(withNote.length).toBeGreaterThan(without.length);
|
||||
});
|
||||
|
||||
it('paginates a long invoice (with the note) across multiple pages without a stray blank page', async () => {
|
||||
const manyItems = Array.from({ length: 60 }, (_, i) => ({
|
||||
quantity: 1, description: `Position ${i + 1} — fotografische Leistung`,
|
||||
unitPriceMinor: 3225, lineTotalMinor: 3225,
|
||||
parentLineItemId: null, parentPosition: null,
|
||||
}));
|
||||
const buf = await pdfService.renderInvoiceToBuffer(baseCtx({
|
||||
lineItems: manyItems,
|
||||
totals: {
|
||||
netAmountMinor: 193500, vatRate: 0, vatAmountMinor: 0,
|
||||
shippingAmountMinor: 0, totalAmountMinor: 193500,
|
||||
},
|
||||
vatNote: VAT_NOTE,
|
||||
}));
|
||||
expect(buf.slice(0, 4).toString('ascii')).toBe('%PDF');
|
||||
const pages = pageCount(buf);
|
||||
expect(pages).toBeGreaterThanOrEqual(2);
|
||||
// 60 short rows fit in 2–3 pages; a stray blank page (the old margin
|
||||
// bug) or a runaway loop would blow past this.
|
||||
expect(pages).toBeLessThanOrEqual(3);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -71,24 +71,15 @@ jest.mock('../../src/services/imageProcessor', () => {
|
||||
const mockExtractCaptureDate = jest.fn();
|
||||
return {
|
||||
generateThumbnail: mockGenerateThumbnail,
|
||||
generateVideoPlaceholder: jest.fn(async (filename) => `thumbnails/thumb_${filename.replace(/\.[^.]+$/, '')}.jpg`),
|
||||
extractCaptureDate: mockExtractCaptureDate,
|
||||
withLocalCopy: jest.fn(async (key, fn) =>
|
||||
fn(`/tmp/local-copy-${require('path').basename(key)}`)
|
||||
),
|
||||
// Pass-through for ordinary (non-RAW) images: returns the path unchanged
|
||||
// with a no-op cleanup, matching the real helper's behaviour for jpg/png.
|
||||
withProcessableImage: jest.fn(async (localPath) => ({
|
||||
path: localPath,
|
||||
outputBasename: undefined,
|
||||
cleanup: () => {},
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
jest.mock('../../src/services/videoProcessor', () => ({
|
||||
processUploadedVideo: jest.fn(),
|
||||
extractVideoMetadata: jest.fn(),
|
||||
isVideoMimeType: (mime) => typeof mime === 'string' && mime.startsWith('video/'),
|
||||
}));
|
||||
|
||||
@@ -214,44 +205,6 @@ describe('photoProcessor.processPhoto', () => {
|
||||
expect(watermarkService.generateForPhoto).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps a video complete with a placeholder thumbnail when ffmpeg fails', async () => {
|
||||
dbModule.__setPhoto({
|
||||
id: 203,
|
||||
event_id: 9,
|
||||
filename: 'drone-clip.mp4',
|
||||
original_filename: 'drone.mp4',
|
||||
mime_type: 'video/mp4',
|
||||
media_type: 'video',
|
||||
size_bytes: 12345,
|
||||
captured_at: null,
|
||||
});
|
||||
dbModule.__setEvent({ id: 9, slug: 'wedding', event_name: 'Wedding' });
|
||||
|
||||
// ffmpeg thumbnail pipeline throws (e.g. unsupported pixel format)…
|
||||
videoProcessor.processUploadedVideo.mockRejectedValueOnce(new Error('ffmpeg exited with code 1'));
|
||||
// …but a plain probe still works.
|
||||
videoProcessor.extractVideoMetadata.mockResolvedValueOnce({
|
||||
duration: 42,
|
||||
videoCodec: 'hevc',
|
||||
audioCodec: 'aac',
|
||||
width: 3840,
|
||||
height: 2160,
|
||||
});
|
||||
|
||||
const { processPhoto } = require('../../src/services/photoProcessor');
|
||||
await processPhoto(203);
|
||||
|
||||
const finalUpdate = dbModule.__recorded().updateCalls.pop();
|
||||
// The row must complete — 'failed' rows are invisible to guests.
|
||||
expect(finalUpdate.data.processing_status).toBe('complete');
|
||||
// Placeholder instead of NULL: a completed video without thumbnail would
|
||||
// make the grid fetch the original video file for the tile (#845 review).
|
||||
expect(finalUpdate.data.thumbnail_path).toBe('thumbnails/thumb_drone-clip.jpg');
|
||||
expect(imageProcessor.generateVideoPlaceholder).toHaveBeenCalledWith('drone-clip.mp4');
|
||||
expect(finalUpdate.data.duration).toBe(42);
|
||||
expect(finalUpdate.data.video_codec).toBe('hevc');
|
||||
});
|
||||
|
||||
it('throws when the photo row no longer exists', async () => {
|
||||
dbModule.__setPhoto(null);
|
||||
dbModule.__setEvent({ id: 1 });
|
||||
|
||||
@@ -1,105 +0,0 @@
|
||||
/**
|
||||
* Tests for preserveOperatorRole — re-establishing the operator's authorization
|
||||
* after a restore replaces the roles / permissions / role_permissions tables.
|
||||
* Real in-memory SQLite so the joins and inserts behave as in production.
|
||||
*/
|
||||
const knex = require('knex');
|
||||
|
||||
let db;
|
||||
let svc;
|
||||
|
||||
beforeEach(async () => {
|
||||
db = knex({ client: 'sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true });
|
||||
await db.schema.createTable('roles', (t) => {
|
||||
t.increments('id');
|
||||
t.string('name').notNullable().unique();
|
||||
t.string('display_name');
|
||||
t.integer('priority').defaultTo(0);
|
||||
t.boolean('is_system').defaultTo(false);
|
||||
});
|
||||
await db.schema.createTable('permissions', (t) => {
|
||||
t.increments('id');
|
||||
t.string('name').notNullable().unique();
|
||||
t.string('display_name');
|
||||
t.string('category');
|
||||
});
|
||||
await db.schema.createTable('role_permissions', (t) => {
|
||||
t.integer('role_id').notNullable();
|
||||
t.integer('permission_id').notNullable();
|
||||
t.primary(['role_id', 'permission_id']);
|
||||
});
|
||||
await db.schema.createTable('admin_users', (t) => {
|
||||
t.increments('id');
|
||||
t.string('email');
|
||||
t.integer('role_id');
|
||||
});
|
||||
jest.resetModules();
|
||||
jest.doMock('../../knexfile', () => ({ client: 'sqlite3' }));
|
||||
jest.doMock('../../src/database/db', () => ({ db }));
|
||||
svc = require('../../src/services/picpeakImportService');
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
jest.dontMock('../../src/database/db');
|
||||
jest.dontMock('../../knexfile');
|
||||
await db.destroy();
|
||||
});
|
||||
|
||||
test('captureOperatorRole returns the role + its permission names', async () => {
|
||||
await db('roles').insert({ id: 1, name: 'super_admin', display_name: 'Super Admin', priority: 100 });
|
||||
await db('permissions').insert([
|
||||
{ id: 1, name: 'events.create', display_name: 'Create', category: 'events' },
|
||||
{ id: 2, name: 'users.manage', display_name: 'Manage', category: 'users' },
|
||||
]);
|
||||
await db('role_permissions').insert([{ role_id: 1, permission_id: 1 }, { role_id: 1, permission_id: 2 }]);
|
||||
|
||||
const snap = await svc.captureOperatorRole(1);
|
||||
expect(snap.role.name).toBe('super_admin');
|
||||
expect(snap.permissions.sort()).toEqual(['events.create', 'users.manage']);
|
||||
});
|
||||
|
||||
test('preserveOperatorRole binds to a restored role of the same NAME (ids remapped)', async () => {
|
||||
const snapshot = { role: { name: 'super_admin', display_name: 'Super Admin', priority: 100, is_system: true }, permissions: ['events.create'] };
|
||||
// Simulate post-restore RBAC where super_admin now has a DIFFERENT id.
|
||||
await db('roles').insert({ id: 7, name: 'super_admin', display_name: 'Super Admin (restored)', priority: 100 });
|
||||
await db('admin_users').insert({ id: 3, email: 'op@example.com', role_id: null });
|
||||
|
||||
await db.transaction((trx) => svc.preserveOperatorRole(trx, 3, snapshot));
|
||||
|
||||
const op = await db('admin_users').where({ id: 3 }).first();
|
||||
expect(op.role_id).toBe(7); // bound to restored super_admin by name
|
||||
expect(await db('roles').count({ c: '*' }).first()).toEqual({ c: 1 }); // no duplicate role created
|
||||
});
|
||||
|
||||
test('preserveOperatorRole re-creates the role + grants when the backup omits it', async () => {
|
||||
const snapshot = {
|
||||
role: { name: 'super_admin', display_name: 'Super Admin', priority: 100, is_system: true },
|
||||
permissions: ['events.create', 'users.manage', 'gone.permission'],
|
||||
};
|
||||
// Post-restore RBAC WITHOUT super_admin; only some permissions exist.
|
||||
await db('roles').insert({ id: 2, name: 'viewer', display_name: 'Viewer', priority: 10 });
|
||||
await db('permissions').insert([
|
||||
{ id: 5, name: 'events.create', display_name: 'Create', category: 'events' },
|
||||
{ id: 6, name: 'users.manage', display_name: 'Manage', category: 'users' },
|
||||
]);
|
||||
await db('admin_users').insert({ id: 3, email: 'op@example.com', role_id: null });
|
||||
|
||||
await db.transaction((trx) => svc.preserveOperatorRole(trx, 3, snapshot));
|
||||
|
||||
const recreated = await db('roles').where({ name: 'super_admin' }).first();
|
||||
expect(recreated).toBeTruthy(); // role re-created, not left missing
|
||||
expect(recreated.id).toBe(3); // max(2)+1
|
||||
|
||||
const op = await db('admin_users').where({ id: 3 }).first();
|
||||
expect(op.role_id).toBe(recreated.id); // operator not locked out / downgraded
|
||||
|
||||
const grants = await db('role_permissions').where({ role_id: recreated.id }).pluck('permission_id');
|
||||
expect(grants.sort()).toEqual([5, 6]); // existing perms re-granted; 'gone.permission' skipped
|
||||
});
|
||||
|
||||
test('preserveOperatorRole no-ops when the operator had no role', async () => {
|
||||
await db('admin_users').insert({ id: 3, email: 'op@example.com', role_id: null });
|
||||
await db.transaction((trx) => svc.preserveOperatorRole(trx, 3, null));
|
||||
const op = await db('admin_users').where({ id: 3 }).first();
|
||||
expect(op.role_id).toBeNull();
|
||||
});
|
||||
@@ -1,38 +0,0 @@
|
||||
/**
|
||||
* renderProofName — the configurable Beleg proof-attachment filename template.
|
||||
* Pure function; no DB. Covers token substitution, the multi-proof index
|
||||
* fallback, padding, and filesystem-safe sanitisation.
|
||||
*/
|
||||
const { renderProofName } = require('../../src/services/invoice/rebillProofs');
|
||||
|
||||
describe('renderProofName', () => {
|
||||
const base = { invoiceNumber: 'R-2026-0042', supplierName: 'ACME AG', seq: 1, hasMulti: false, issueDate: '2026-08-03' };
|
||||
|
||||
it('defaults to Beleg-<invoice>.pdf', () => {
|
||||
expect(renderProofName('Beleg-{INVOICE}', base)).toBe('Beleg-R-2026-0042.pdf');
|
||||
expect(renderProofName('', base)).toBe('Beleg-R-2026-0042.pdf');
|
||||
expect(renderProofName(null, base)).toBe('Beleg-R-2026-0042.pdf');
|
||||
});
|
||||
|
||||
it('substitutes every token incl. padded SEQ and date parts', () => {
|
||||
expect(renderProofName('{SUPPLIER}-{INVOICE}-{YEAR}{MONTH}-{SEQ:03d}', { ...base, seq: 7 }))
|
||||
.toBe('ACME-AG-R-2026-0042-202608-007.pdf');
|
||||
});
|
||||
|
||||
it('appends an index for multiple proofs only when the template has no {SEQ}', () => {
|
||||
// No {SEQ} + multi → auto-suffixed with the index.
|
||||
expect(renderProofName('Beleg-{INVOICE}', { ...base, seq: 2, hasMulti: true })).toBe('Beleg-R-2026-0042-2.pdf');
|
||||
// Single proof → no suffix.
|
||||
expect(renderProofName('Beleg-{INVOICE}', { ...base, seq: 1, hasMulti: false })).toBe('Beleg-R-2026-0042.pdf');
|
||||
// Explicit {SEQ} → no double index even when multi.
|
||||
expect(renderProofName('Beleg-{INVOICE}-{SEQ}', { ...base, seq: 2, hasMulti: true })).toBe('Beleg-R-2026-0042-2.pdf');
|
||||
});
|
||||
|
||||
it('sanitises unsafe characters and slashes, and always ends in a single .pdf', () => {
|
||||
expect(renderProofName('Beleg {INVOICE}', { ...base, invoiceNumber: '2026/0042' })).toBe('Beleg-2026-0042.pdf');
|
||||
// Author-supplied extension is stripped and re-added (no double .pdf).
|
||||
expect(renderProofName('{INVOICE}.pdf', base)).toBe('R-2026-0042.pdf');
|
||||
// Falls back to 'Beleg' if the template renders empty after sanitising.
|
||||
expect(renderProofName('{SUPPLIER}', { ...base, supplierName: '///' })).toBe('Beleg.pdf');
|
||||
});
|
||||
});
|
||||
@@ -1,247 +0,0 @@
|
||||
/**
|
||||
* Ownership guards for PicTransfer (#998 review, tracked as #1005).
|
||||
*
|
||||
* A transfer bundles ORIGINAL files and hands them out over an unauthenticated
|
||||
* token URL, so the two guards below are the only thing standing between a
|
||||
* scoped admin and every other admin's originals:
|
||||
*
|
||||
* 1. filterOwnedPhotoIds — a scoped admin may only bundle photos from events
|
||||
* they own. Without it, arbitrary photo ids in the create/add-files body
|
||||
* became a public download link to anyone's originals.
|
||||
* 2. listTransfers scoping + payload stripping — the list used to be unscoped
|
||||
* AND to carry each row's download token, so any admin holding events.view
|
||||
* could read another's token and fetch their originals without creating
|
||||
* anything at all.
|
||||
*
|
||||
* Both were correct when merged. These tests exist so they stay that way: an
|
||||
* untested guard does not survive refactoring, which #999 demonstrated when the
|
||||
* same attribution fix landed in one component and was left stale in another.
|
||||
* Each case below fails against the pre-fix behaviour, not merely passes
|
||||
* against the current code.
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.TEST_DATABASE_PATH = path.join(
|
||||
fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-transferown-')), 'db.sqlite',
|
||||
);
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'transferown-test-secret';
|
||||
|
||||
const bcrypt = require('bcrypt');
|
||||
const { bootCrmDb, seedMinimal } = require('../integration/helpers/crmDb');
|
||||
|
||||
describe('PicTransfer ownership guards (#998)', () => {
|
||||
let db; let cleanup; let transferService;
|
||||
let editorA; let editorB; let superAdmin;
|
||||
let eventA; let eventB; let eventOwnerless;
|
||||
let photoA; let photoB; let photoOwnerless;
|
||||
|
||||
const asEditor = (id) => ({ id, roleName: 'editor' });
|
||||
|
||||
const mkAdmin = async (username, roleName) => {
|
||||
const role = await db('roles').where({ name: roleName }).first();
|
||||
const r = await db('admin_users').insert({
|
||||
username, email: `${username}@example.com`,
|
||||
password_hash: await bcrypt.hash('Passw0rd!', 4),
|
||||
role_id: role.id, is_active: 1,
|
||||
created_at: new Date().toISOString(), updated_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
return r[0]?.id ?? r[0];
|
||||
};
|
||||
|
||||
const mkEvent = async (slug, createdBy) => {
|
||||
const r = await db('events').insert({
|
||||
slug, event_type: 'wedding', event_name: slug, event_date: '2026-08-01',
|
||||
host_email: 'h@e.com', admin_email: 'a@e.com', password_hash: 'x',
|
||||
share_token: `t-${slug}`, share_link: `/g/${slug}/t-${slug}`,
|
||||
created_by: createdBy,
|
||||
expires_at: new Date(Date.now() + 864e5).toISOString(),
|
||||
is_active: 1, is_archived: 0, is_draft: 0,
|
||||
created_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
return r[0]?.id ?? r[0];
|
||||
};
|
||||
|
||||
const mkPhoto = async (eventId, filename) => {
|
||||
const r = await db('photos').insert({
|
||||
event_id: eventId, filename, path: `events/${eventId}/${filename}`,
|
||||
type: 'individual', uploaded_at: Date.now(),
|
||||
}).returning('id');
|
||||
return r[0]?.id ?? r[0];
|
||||
};
|
||||
|
||||
const mkTransfer = async (title, createdBy) => {
|
||||
const r = await db('transfers').insert({
|
||||
token: `tok-${title}-${'0'.repeat(50)}`.slice(0, 64),
|
||||
title, created_by: createdBy,
|
||||
expires_at: new Date(Date.now() + 864e5).toISOString(),
|
||||
download_count: 0, is_active: 1, grace_days: 7, allow_uploads: 0,
|
||||
delivery_method: 'link',
|
||||
created_at: new Date().toISOString(), updated_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
return r[0]?.id ?? r[0];
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
await seedMinimal(db);
|
||||
transferService = require('../../src/services/transferService');
|
||||
|
||||
editorA = await mkAdmin('xfer-a', 'editor');
|
||||
editorB = await mkAdmin('xfer-b', 'editor');
|
||||
superAdmin = await mkAdmin('xfer-root', 'super_admin');
|
||||
|
||||
eventA = await mkEvent('xfer-own', editorA);
|
||||
eventB = await mkEvent('xfer-foreign', editorB);
|
||||
eventOwnerless = await mkEvent('xfer-legacy', null);
|
||||
|
||||
photoA = await mkPhoto(eventA, 'own.jpg');
|
||||
photoB = await mkPhoto(eventB, 'foreign.jpg');
|
||||
photoOwnerless = await mkPhoto(eventOwnerless, 'legacy.jpg');
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => { if (cleanup) await cleanup(); });
|
||||
|
||||
describe('filterOwnedPhotoIds', () => {
|
||||
it("drops photos from another admin's event", async () => {
|
||||
// The exfiltration path: these ids would otherwise be bundled into a
|
||||
// transfer and served over the public download token.
|
||||
const owned = await transferService.filterOwnedPhotoIds(asEditor(editorA), [photoB]);
|
||||
expect(owned).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps photos from the caller's own event", async () => {
|
||||
const owned = await transferService.filterOwnedPhotoIds(asEditor(editorA), [photoA]);
|
||||
expect(owned).toEqual([photoA]);
|
||||
});
|
||||
|
||||
it('keeps photos from an ownerless legacy event', async () => {
|
||||
// Parity with filterOwnedEventIds, which treats created_by IS NULL as
|
||||
// ownable by anyone — otherwise legacy events become unusable.
|
||||
const owned = await transferService.filterOwnedPhotoIds(asEditor(editorA), [photoOwnerless]);
|
||||
expect(owned).toEqual([photoOwnerless]);
|
||||
});
|
||||
|
||||
it('keeps only the owned subset of a mixed request', async () => {
|
||||
const owned = await transferService.filterOwnedPhotoIds(
|
||||
asEditor(editorA), [photoA, photoB, photoOwnerless],
|
||||
);
|
||||
expect(owned.sort()).toEqual([photoA, photoOwnerless].sort());
|
||||
expect(owned).not.toContain(photoB);
|
||||
});
|
||||
|
||||
it('drops ids that do not exist', async () => {
|
||||
const owned = await transferService.filterOwnedPhotoIds(asEditor(editorA), [999999]);
|
||||
expect(owned).toEqual([]);
|
||||
});
|
||||
|
||||
it('leaves super_admin unrestricted', async () => {
|
||||
const owned = await transferService.filterOwnedPhotoIds(
|
||||
{ id: superAdmin, roleName: 'super_admin' }, [photoA, photoB, photoOwnerless],
|
||||
);
|
||||
expect(owned.sort()).toEqual([photoA, photoB, photoOwnerless].sort());
|
||||
});
|
||||
});
|
||||
|
||||
describe('addFiles gates on the same rule', () => {
|
||||
it("refuses to attach another admin's photo", async () => {
|
||||
// The guard has to sit in addFiles, not only at the route, because both
|
||||
// createTransfer and POST /:id/files funnel through it.
|
||||
const transferId = await mkTransfer('gate', editorA);
|
||||
await transferService.addFiles(transferId, [photoA, photoB], asEditor(editorA));
|
||||
|
||||
const attached = await db('transfer_files')
|
||||
.where({ transfer_id: transferId }).pluck('photo_id');
|
||||
expect(attached).toContain(photoA);
|
||||
expect(attached).not.toContain(photoB);
|
||||
});
|
||||
});
|
||||
|
||||
describe('listTransfers', () => {
|
||||
let mineId; let theirsId;
|
||||
|
||||
beforeAll(async () => {
|
||||
mineId = await mkTransfer('mine', editorA);
|
||||
theirsId = await mkTransfer('theirs', editorB);
|
||||
});
|
||||
|
||||
it("hides another admin's transfers from a scoped caller", async () => {
|
||||
const rows = await transferService.listTransfers({ admin: asEditor(editorA) });
|
||||
const ids = rows.map((r) => r.id);
|
||||
expect(ids).toContain(mineId);
|
||||
expect(ids).not.toContain(theirsId);
|
||||
});
|
||||
|
||||
it('shows everything to super_admin', async () => {
|
||||
const rows = await transferService.listTransfers({
|
||||
admin: { id: superAdmin, roleName: 'super_admin' },
|
||||
});
|
||||
const ids = rows.map((r) => r.id);
|
||||
expect(ids).toEqual(expect.arrayContaining([mineId, theirsId]));
|
||||
});
|
||||
|
||||
it('never carries download or upload links in the list payload', async () => {
|
||||
// Defence in depth on top of the scoping above, and the layer most likely
|
||||
// to be undone by a "the list needs the link too" change. The token is a
|
||||
// bearer credential for the originals — detail only.
|
||||
const rows = await transferService.listTransfers({ admin: asEditor(editorA) });
|
||||
expect(rows.length).toBeGreaterThan(0);
|
||||
for (const row of rows) {
|
||||
expect(row).not.toHaveProperty('token');
|
||||
expect(row).not.toHaveProperty('upload_token');
|
||||
expect(row).not.toHaveProperty('download_url');
|
||||
expect(row).not.toHaveProperty('upload_url');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// The guard is a module-local middleware, so rather than stand up supertest
|
||||
// just to prove Express ordering, assert the contract at the source — the
|
||||
// same approach taken for the backup/restore contracts in #596. Ordering is
|
||||
// the whole mechanism here: `router.use('/:id', …)` registered after the
|
||||
// `/:id` routes would silently guard nothing while still looking present.
|
||||
describe('requireTransferOwnership registration', () => {
|
||||
const routerSrc = fs.readFileSync(
|
||||
path.join(__dirname, '../../src/routes/adminTransfers.js'), 'utf8',
|
||||
);
|
||||
|
||||
it('mounts the ownership guard before every /:id route', () => {
|
||||
const guardAt = routerSrc.indexOf("router.use('/:id', requireTransferOwnership)");
|
||||
expect(guardAt).toBeGreaterThan(-1);
|
||||
|
||||
const idRoutes = [...routerSrc.matchAll(/^router\.(get|post|patch|delete)\('\/:id/gm)];
|
||||
expect(idRoutes.length).toBeGreaterThan(0);
|
||||
for (const m of idRoutes) {
|
||||
expect(m.index).toBeGreaterThan(guardAt);
|
||||
}
|
||||
});
|
||||
|
||||
it('answers missing and foreign ids identically, so it is not an existence oracle', () => {
|
||||
const guard = routerSrc.slice(
|
||||
routerSrc.indexOf('async function requireTransferOwnership'),
|
||||
routerSrc.indexOf('// List'),
|
||||
);
|
||||
// Both branches must 404. A 403 on foreign would confirm the row exists.
|
||||
const notFounds = [...guard.matchAll(/status\(404\)/g)];
|
||||
expect(notFounds.length).toBeGreaterThanOrEqual(2);
|
||||
expect(guard).not.toMatch(/status\(403\)/);
|
||||
expect(guard).toMatch(/roleName === 'super_admin'/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getTransferOwner (backs requireTransferOwnership)', () => {
|
||||
it('reports the creator so the route guard can compare it', async () => {
|
||||
const id = await mkTransfer('owned-lookup', editorB);
|
||||
const owner = await transferService.getTransferOwner(id);
|
||||
expect(Number(owner.created_by)).toBe(Number(editorB));
|
||||
});
|
||||
|
||||
it('returns nothing for a missing id, so the guard 404s rather than throwing', async () => {
|
||||
const owner = await transferService.getTransferOwner(999999);
|
||||
expect(owner).toBeFalsy();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,78 +0,0 @@
|
||||
/**
|
||||
* Unit tests for the pure gating logic in transferService (PicTransfer, #997).
|
||||
* These exercise the download/upload eligibility rules without touching the DB.
|
||||
*/
|
||||
const transferService = require('../../src/services/transferService');
|
||||
|
||||
const HOUR = 60 * 60 * 1000;
|
||||
|
||||
function make(overrides = {}) {
|
||||
return {
|
||||
id: 1,
|
||||
title: 'T',
|
||||
is_active: true,
|
||||
deleted_at: null,
|
||||
expires_at: new Date(Date.now() + 24 * HOUR),
|
||||
max_downloads: null,
|
||||
download_count: 0,
|
||||
allow_uploads: false,
|
||||
upload_expires_at: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('transferService.downloadsRemaining', () => {
|
||||
it('returns null (unlimited) when no cap or zero cap', () => {
|
||||
expect(transferService.downloadsRemaining(make({ max_downloads: null }))).toBeNull();
|
||||
expect(transferService.downloadsRemaining(make({ max_downloads: 0 }))).toBeNull();
|
||||
});
|
||||
|
||||
it('returns the remaining count and never goes negative', () => {
|
||||
expect(transferService.downloadsRemaining(make({ max_downloads: 5, download_count: 2 }))).toBe(3);
|
||||
expect(transferService.downloadsRemaining(make({ max_downloads: 5, download_count: 9 }))).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('transferService.computeStatus', () => {
|
||||
it('is deleted when deleted_at set, regardless of activity', () => {
|
||||
expect(transferService.computeStatus(make({ deleted_at: new Date(), is_active: true }))).toBe('deleted');
|
||||
});
|
||||
it('is expired when inactive or past expiry', () => {
|
||||
expect(transferService.computeStatus(make({ is_active: false }))).toBe('expired');
|
||||
expect(transferService.computeStatus(make({ expires_at: new Date(Date.now() - HOUR) }))).toBe('expired');
|
||||
});
|
||||
it('is active within the window', () => {
|
||||
expect(transferService.computeStatus(make())).toBe('active');
|
||||
});
|
||||
});
|
||||
|
||||
describe('transferService.assertDownloadable', () => {
|
||||
it('allows a live, in-window, uncapped transfer', () => {
|
||||
expect(transferService.assertDownloadable(make()).ok).toBe(true);
|
||||
});
|
||||
it('404s a missing/deleted transfer', () => {
|
||||
expect(transferService.assertDownloadable(null)).toMatchObject({ ok: false, status: 404 });
|
||||
expect(transferService.assertDownloadable(make({ deleted_at: new Date() }))).toMatchObject({ ok: false, status: 404 });
|
||||
});
|
||||
it('410s when disabled or expired', () => {
|
||||
expect(transferService.assertDownloadable(make({ is_active: false }))).toMatchObject({ ok: false, code: 'TRANSFER_DISABLED', status: 410 });
|
||||
expect(transferService.assertDownloadable(make({ expires_at: new Date(Date.now() - HOUR) }))).toMatchObject({ ok: false, code: 'TRANSFER_EXPIRED', status: 410 });
|
||||
});
|
||||
it('410s when the download cap is reached', () => {
|
||||
expect(transferService.assertDownloadable(make({ max_downloads: 2, download_count: 2 })))
|
||||
.toMatchObject({ ok: false, code: 'DOWNLOAD_LIMIT_REACHED', status: 410 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('transferService.assertUploadable', () => {
|
||||
it('403s when uploads are disabled', () => {
|
||||
expect(transferService.assertUploadable(make({ allow_uploads: false }))).toMatchObject({ ok: false, code: 'UPLOADS_DISABLED', status: 403 });
|
||||
});
|
||||
it('allows when uploads enabled and not expired', () => {
|
||||
expect(transferService.assertUploadable(make({ allow_uploads: true })).ok).toBe(true);
|
||||
});
|
||||
it('410s when the upload window has passed', () => {
|
||||
expect(transferService.assertUploadable(make({ allow_uploads: true, upload_expires_at: new Date(Date.now() - HOUR) })))
|
||||
.toMatchObject({ ok: false, code: 'UPLOAD_EXPIRED', status: 410 });
|
||||
});
|
||||
});
|
||||
@@ -1,52 +0,0 @@
|
||||
/**
|
||||
* Pre-rename detection for the registry-move notice (#985).
|
||||
*
|
||||
* The in-app MigrationBanner shipped 2026-06-29, a month AFTER
|
||||
* ghcr.io/the-luap/picpeak/* stopped receiving images on 2026-05-27. Anyone
|
||||
* still pulling the retired path is therefore running a build that predates the
|
||||
* banner and can never render it — the structural gap that keeps producing
|
||||
* reports like #982. The update check is the one channel that still reaches
|
||||
* them, so it carries the notice instead.
|
||||
*
|
||||
* The boundary is exact rather than heuristic: v3.44.0 shipped on the freeze
|
||||
* date and v3.45.0 followed on 2026-07-09 to the org registry only, with
|
||||
* nothing published in between.
|
||||
*/
|
||||
|
||||
const { isPreRenameStable, REGISTRY_RENAME_STABLE_FLOOR } = require('../../src/services/updateCheckService');
|
||||
|
||||
describe('isPreRenameStable (#985)', () => {
|
||||
it('pins the floor to the first org-registry-only stable release', () => {
|
||||
expect(REGISTRY_RENAME_STABLE_FLOOR).toBe('3.45.0');
|
||||
});
|
||||
|
||||
it('flags stable installs below the floor', () => {
|
||||
// v3.44.0 is the last stable that reached the retired path.
|
||||
expect(isPreRenameStable('3.44.0', 'stable')).toBe(true);
|
||||
expect(isPreRenameStable('3.43.1', 'stable')).toBe(true);
|
||||
expect(isPreRenameStable('2.6.5', 'stable')).toBe(true);
|
||||
});
|
||||
|
||||
it('leaves stable installs at or above the floor alone', () => {
|
||||
expect(isPreRenameStable('3.45.0', 'stable')).toBe(false);
|
||||
expect(isPreRenameStable('3.45.13', 'stable')).toBe(false);
|
||||
expect(isPreRenameStable('3.99.0', 'stable')).toBe(false);
|
||||
});
|
||||
|
||||
it('never fires on the beta channel', () => {
|
||||
// The beta boundary is inferred, not clean — 3.59.0-beta.0 landed two days
|
||||
// after the freeze. A false positive would tell a correctly-configured
|
||||
// operator their registry is retired, so beta is deliberately excluded even
|
||||
// where the number looks old.
|
||||
expect(isPreRenameStable('3.44.0-beta.0', 'beta')).toBe(false);
|
||||
expect(isPreRenameStable('3.58.0-beta.0', 'beta')).toBe(false);
|
||||
expect(isPreRenameStable('3.99.0-beta.0', 'beta')).toBe(false);
|
||||
});
|
||||
|
||||
it('does not fire on an unresolvable version', () => {
|
||||
// getCurrentVersion() falls back to '0.0.0' when package.json is
|
||||
// unreadable. That is a broken install, not a pre-rename one — claiming its
|
||||
// registry is retired would send the operator down the wrong path.
|
||||
expect(isPreRenameStable('0.0.0', 'stable')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,51 +0,0 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const {
|
||||
EXTENSION_TO_MIME,
|
||||
extensionsToMimeTypes,
|
||||
} = require('../../src/services/uploadSettings');
|
||||
const { validateFileType } = require('../../src/utils/fileSecurityUtils');
|
||||
|
||||
const RAW_AND_HEIF_TYPES = {
|
||||
dng: 'image/x-adobe-dng',
|
||||
heic: 'image/heic',
|
||||
heif: 'image/heif',
|
||||
};
|
||||
|
||||
function getFrontendExtensionMap() {
|
||||
const source = fs.readFileSync(
|
||||
path.join(__dirname, '../../../frontend/src/utils/fileTypes.ts'),
|
||||
'utf8'
|
||||
);
|
||||
const match = source.match(/const EXTENSION_TO_MIME[^=]*= \{([\s\S]*?)\n\};/);
|
||||
if (!match) throw new Error('Could not find frontend EXTENSION_TO_MIME');
|
||||
|
||||
// Parse `key: 'mime',` entries — quoted keys and trailing `//` comments are
|
||||
// tolerated; any other non-blank, non-comment line inside the map is a parse
|
||||
// failure, so a syntax the parser can't read fails loudly instead of silently
|
||||
// dropping the entry from the comparison.
|
||||
const entries = [];
|
||||
for (const line of match[1].split('\n')) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed === '' || trimmed.startsWith('//')) continue;
|
||||
const entry = trimmed.match(/^'?(\w+)'?\s*:\s*'([^']+)'\s*,?\s*(?:\/\/.*)?$/);
|
||||
if (!entry) throw new Error(`Unparsable EXTENSION_TO_MIME line in frontend fileTypes.ts: "${trimmed}"`);
|
||||
entries.push([entry[1], entry[2]]);
|
||||
}
|
||||
return Object.fromEntries(entries);
|
||||
}
|
||||
|
||||
describe('configured upload file types', () => {
|
||||
test('supports configured DNG, HEIC, and HEIF uploads', () => {
|
||||
expect(extensionsToMimeTypes('dng,heic,heif')).toEqual(Object.values(RAW_AND_HEIF_TYPES));
|
||||
|
||||
for (const [extension, mimeType] of Object.entries(RAW_AND_HEIF_TYPES)) {
|
||||
expect(validateFileType(`image.${extension}`, mimeType, [mimeType])).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test('uses the same extension-to-MIME map as the frontend', () => {
|
||||
expect(getFrontendExtensionMap()).toEqual(EXTENSION_TO_MIME);
|
||||
});
|
||||
});
|
||||
@@ -1,65 +0,0 @@
|
||||
/**
|
||||
* Unit tests for the per-file upload size limit getter (general_max_file_size_mb),
|
||||
* added so the admin's "Max File Size (MB)" setting applies to guest uploads
|
||||
* (#613 follow-up — mat1990dj). Real in-memory SQLite app_settings so the
|
||||
* read/parse/cache path runs exactly as in production.
|
||||
*/
|
||||
const knex = require('knex');
|
||||
|
||||
let db;
|
||||
let svc;
|
||||
|
||||
beforeEach(async () => {
|
||||
db = knex({ client: 'sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true });
|
||||
await db.schema.createTable('app_settings', (t) => {
|
||||
t.increments('id');
|
||||
t.string('setting_key').notNullable().unique();
|
||||
t.text('setting_value');
|
||||
t.string('setting_type');
|
||||
t.timestamp('updated_at');
|
||||
});
|
||||
jest.resetModules();
|
||||
jest.doMock('../../src/database/db', () => ({ db }));
|
||||
svc = require('../../src/services/uploadSettings');
|
||||
svc.clearMaxFileSizeCache();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
jest.dontMock('../../src/database/db');
|
||||
await db.destroy();
|
||||
});
|
||||
|
||||
async function setLimit(mb) {
|
||||
await db('app_settings')
|
||||
.insert({ setting_key: 'general_max_file_size_mb', setting_value: JSON.stringify(mb), setting_type: 'general', updated_at: new Date() })
|
||||
.onConflict('setting_key').merge({ setting_value: JSON.stringify(mb) });
|
||||
svc.clearMaxFileSizeCache();
|
||||
}
|
||||
|
||||
test('defaults to 50MB when the setting is absent', async () => {
|
||||
expect(await svc.getMaxFileSizeMb()).toBe(50);
|
||||
expect(await svc.getMaxFileSizeBytes()).toBe(50 * 1024 * 1024);
|
||||
});
|
||||
|
||||
test('honours a configured value (e.g. 500MB video)', async () => {
|
||||
await setLimit(500);
|
||||
expect(await svc.getMaxFileSizeMb()).toBe(500);
|
||||
expect(await svc.getMaxFileSizeBytes()).toBe(500 * 1024 * 1024);
|
||||
});
|
||||
|
||||
test('clamps a nonsense value to the default and caps absurd values at the ceiling', async () => {
|
||||
await setLimit(0);
|
||||
expect(await svc.getMaxFileSizeMb()).toBe(50); // 0 → default
|
||||
await setLimit(99_999_999);
|
||||
expect(await svc.getMaxFileSizeMb()).toBe(svc.MAX_ALLOWED_FILE_SIZE_MB); // ceiling
|
||||
});
|
||||
|
||||
test('caches for the TTL — a mid-window DB change is not seen until the cache is cleared', async () => {
|
||||
await setLimit(200);
|
||||
expect(await svc.getMaxFileSizeMb()).toBe(200);
|
||||
// change the DB but do NOT clear cache
|
||||
await db('app_settings').where({ setting_key: 'general_max_file_size_mb' }).update({ setting_value: JSON.stringify(300) });
|
||||
expect(await svc.getMaxFileSizeMb()).toBe(200); // still cached
|
||||
svc.clearMaxFileSizeCache();
|
||||
expect(await svc.getMaxFileSizeMb()).toBe(300); // refreshed
|
||||
});
|
||||
@@ -1,199 +0,0 @@
|
||||
/**
|
||||
* Per-event banner overrides — end-to-end plumbing for BOTH banners.
|
||||
*
|
||||
* The promo banner (#440) shipped with per-event inherit/custom/off, but the
|
||||
* override never actually reached a guest: GalleryView reads promo_mode from
|
||||
* the /photos payload and /photos never sent it, so every gallery resolved to
|
||||
* 'inherit'. Setting a gallery's promo banner to "Off" did nothing. The info
|
||||
* banner (#932) mirrored that shape and inherited the same gaps.
|
||||
*
|
||||
* Four places dropped the fields. This pins all of them for both banners so
|
||||
* the two stay in step:
|
||||
*
|
||||
* 1. GET /gallery/:slug/photos — must carry the columns
|
||||
* 2. POST /admin/events — validators accepted them, insert dropped
|
||||
* 3. POST /admin/events/:id/duplicate — copy promised, not delivered
|
||||
* 4. PUT /admin/events/:id — partial update parked stale markdown
|
||||
*
|
||||
* The route-level normalisation is exercised directly against its own rules
|
||||
* rather than through supertest: the intent is to pin the DATA contract, which
|
||||
* is what silently broke.
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.TEST_DATABASE_PATH = path.join(
|
||||
fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-banner-plumbing-')), 'db.sqlite',
|
||||
);
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'banner-plumbing-secret';
|
||||
|
||||
const { bootCrmDb, seedMinimal } = require('../integration/helpers/crmDb');
|
||||
|
||||
let db;
|
||||
let cleanup;
|
||||
|
||||
const baseEvent = (slug, extra = {}) => ({
|
||||
slug,
|
||||
event_type: 'wedding',
|
||||
event_name: slug,
|
||||
event_date: '2026-06-22',
|
||||
host_email: 'host@example.com',
|
||||
admin_email: 'admin@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: `/gallery/${slug}/share`,
|
||||
share_token: `${slug}-share`,
|
||||
expires_at: new Date(Date.now() + 7 * 24 * 3600 * 1000).toISOString(),
|
||||
is_active: 1,
|
||||
is_archived: 0,
|
||||
is_draft: 0,
|
||||
created_at: new Date().toISOString(),
|
||||
...extra,
|
||||
});
|
||||
|
||||
const insertEvent = async (slug, extra) => {
|
||||
const [id] = await db('events').insert(baseEvent(slug, extra)).returning('id');
|
||||
return id?.id ?? id;
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
await seedMinimal(db);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (cleanup) await cleanup();
|
||||
});
|
||||
|
||||
// Mirrors the unified normalisation in adminEvents/crud.js.
|
||||
function normalizeBannerUpdates(updates, stored) {
|
||||
for (const field of ['promo', 'info']) {
|
||||
const modeKey = `${field}_mode`;
|
||||
const mdKey = `${field}_markdown`;
|
||||
if (!Object.prototype.hasOwnProperty.call(updates, modeKey)
|
||||
&& !Object.prototype.hasOwnProperty.call(updates, mdKey)) continue;
|
||||
|
||||
const effectiveMode = Object.prototype.hasOwnProperty.call(updates, modeKey)
|
||||
? updates[modeKey]
|
||||
: stored[modeKey];
|
||||
|
||||
if (effectiveMode !== 'custom') {
|
||||
updates[mdKey] = null;
|
||||
} else if (Object.prototype.hasOwnProperty.call(updates, mdKey)) {
|
||||
const md = typeof updates[mdKey] === 'string' ? updates[mdKey].trim() : '';
|
||||
updates[mdKey] = md || null;
|
||||
}
|
||||
}
|
||||
return updates;
|
||||
}
|
||||
|
||||
describe('partial update resolves the mode from the stored row', () => {
|
||||
it.each(['promo', 'info'])(
|
||||
'%s: markdown-only PUT on an inherit gallery does not park hidden text',
|
||||
(field) => {
|
||||
const stored = { promo_mode: 'inherit', info_mode: 'inherit' };
|
||||
const updates = normalizeBannerUpdates({ [`${field}_markdown`]: 'hidden draft' }, stored);
|
||||
|
||||
// Previously stored the text; a later switch to 'custom' resurrected it.
|
||||
expect(updates[`${field}_markdown`]).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(['promo', 'info'])('%s: markdown-only PUT on an off gallery also clears', (field) => {
|
||||
const stored = { promo_mode: 'off', info_mode: 'off' };
|
||||
const updates = normalizeBannerUpdates({ [`${field}_markdown`]: 'hidden draft' }, stored);
|
||||
|
||||
expect(updates[`${field}_markdown`]).toBeNull();
|
||||
});
|
||||
|
||||
it.each(['promo', 'info'])('%s: markdown-only PUT on a custom gallery is kept', (field) => {
|
||||
const stored = { promo_mode: 'custom', info_mode: 'custom' };
|
||||
const updates = normalizeBannerUpdates({ [`${field}_markdown`]: ' keep me ' }, stored);
|
||||
|
||||
expect(updates[`${field}_markdown`]).toBe('keep me');
|
||||
});
|
||||
|
||||
it.each(['promo', 'info'])('%s: switching away from custom clears the copy', (field) => {
|
||||
const stored = { promo_mode: 'custom', info_mode: 'custom' };
|
||||
const updates = normalizeBannerUpdates(
|
||||
{ [`${field}_mode`]: 'off', [`${field}_markdown`]: 'stale' }, stored,
|
||||
);
|
||||
|
||||
expect(updates[`${field}_markdown`]).toBeNull();
|
||||
});
|
||||
|
||||
it('leaves both banners alone when the request touches neither', () => {
|
||||
const updates = normalizeBannerUpdates({ event_name: 'Renamed' }, { promo_mode: 'custom', info_mode: 'custom' });
|
||||
|
||||
expect(Object.prototype.hasOwnProperty.call(updates, 'promo_markdown')).toBe(false);
|
||||
expect(Object.prototype.hasOwnProperty.call(updates, 'info_markdown')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('columns round-trip through the events table', () => {
|
||||
it('stores and reads both banners independently', async () => {
|
||||
const id = await insertEvent('banner-roundtrip', {
|
||||
promo_mode: 'off',
|
||||
info_mode: 'custom',
|
||||
info_markdown: 'Use the menu button to filter.',
|
||||
});
|
||||
|
||||
const row = await db('events').where({ id }).first();
|
||||
// Independent slots — muting one must not touch the other.
|
||||
expect(row.promo_mode).toBe('off');
|
||||
expect(row.promo_markdown ?? null).toBeNull();
|
||||
expect(row.info_mode).toBe('custom');
|
||||
expect(row.info_markdown).toBe('Use the menu button to filter.');
|
||||
});
|
||||
|
||||
it('duplicating drops markdown left over on a non-custom source', async () => {
|
||||
// A row written before the PUT normalisation landed can hold text while
|
||||
// its mode is inherit/off. Copying that verbatim would smuggle hidden copy
|
||||
// into the duplicate and resurrect it on the next switch to 'custom'.
|
||||
const sourceId = await insertEvent('banner-dup-stale', {
|
||||
promo_mode: 'off',
|
||||
promo_markdown: 'stale promo text',
|
||||
info_mode: 'inherit',
|
||||
info_markdown: 'stale info text',
|
||||
});
|
||||
const source = await db('events').where({ id: sourceId }).first();
|
||||
|
||||
const dupId = await insertEvent('banner-dup-stale-copy', {
|
||||
promo_mode: source.promo_mode || 'inherit',
|
||||
promo_markdown: source.promo_mode === 'custom' ? (source.promo_markdown || null) : null,
|
||||
info_mode: source.info_mode || 'inherit',
|
||||
info_markdown: source.info_mode === 'custom' ? (source.info_markdown || null) : null,
|
||||
});
|
||||
|
||||
const dup = await db('events').where({ id: dupId }).first();
|
||||
expect(dup.promo_mode).toBe('off');
|
||||
expect(dup.promo_markdown).toBeNull();
|
||||
expect(dup.info_mode).toBe('inherit');
|
||||
expect(dup.info_markdown).toBeNull();
|
||||
});
|
||||
|
||||
it('duplicating an event carries both banners across', async () => {
|
||||
const sourceId = await insertEvent('banner-dup-source', {
|
||||
promo_mode: 'custom',
|
||||
promo_markdown: 'Book your next session',
|
||||
info_mode: 'off',
|
||||
});
|
||||
const source = await db('events').where({ id: sourceId }).first();
|
||||
|
||||
// Mirrors the duplicate route's insert.
|
||||
const dupId = await insertEvent('banner-dup-copy', {
|
||||
promo_mode: source.promo_mode || 'inherit',
|
||||
promo_markdown: source.promo_mode === 'custom' ? (source.promo_markdown || null) : null,
|
||||
info_mode: source.info_mode || 'inherit',
|
||||
info_markdown: source.info_mode === 'custom' ? (source.info_markdown || null) : null,
|
||||
});
|
||||
|
||||
const dup = await db('events').where({ id: dupId }).first();
|
||||
expect(dup.promo_mode).toBe('custom');
|
||||
expect(dup.promo_markdown).toBe('Book your next session');
|
||||
// The muted info banner must stay muted in the copy.
|
||||
expect(dup.info_mode).toBe('off');
|
||||
});
|
||||
});
|
||||
@@ -1,609 +0,0 @@
|
||||
/**
|
||||
* Engine resolution + the stranded-SQLite guard (#1038).
|
||||
*
|
||||
* knexfile.js picks its config block by NODE_ENV and the `development` block
|
||||
* defaults to sqlite3. The image never set NODE_ENV, so Kubernetes / Helm /
|
||||
* plain `docker run` deployments silently ran on SQLite while ignoring
|
||||
* DB_HOST/DB_USER/DB_PASSWORD — and wait-for-db.sh, being shell, reported
|
||||
* "PostgreSQL is up" in the same log.
|
||||
*
|
||||
* Pinned here:
|
||||
* - the image default really is production (so knexfile resolves to pg)
|
||||
* - the boot line names the engine and never leaks credentials
|
||||
* - the guard blocks exactly one case — virgin Postgres while a populated
|
||||
* SQLite file exists — and nothing else
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
const os = require('os');
|
||||
const {
|
||||
resolveSqlitePath,
|
||||
describeEngine,
|
||||
decideBootEngine,
|
||||
probeSqliteData,
|
||||
migrationMarkerPath,
|
||||
hasMigrationMarker,
|
||||
migrationInProgressPath,
|
||||
hasMigrationInProgress,
|
||||
isUntouchedBootstrapRow,
|
||||
adminsIndicateUse,
|
||||
} = require('../../src/utils/databaseEngine');
|
||||
const {
|
||||
epochToIso,
|
||||
coerceForTargetEngine,
|
||||
} = require('../../src/services/picpeakImportService');
|
||||
|
||||
describe('knexfile engine selection (#1038)', () => {
|
||||
// Resolved in a child process with a clean cwd: knexfile calls
|
||||
// dotenv.config(), so running in-process would let a developer's
|
||||
// backend/.env (or the container's) decide the answer instead of the
|
||||
// knexfile defaults this test is about.
|
||||
function clientFor(env) {
|
||||
const { execFileSync } = require('child_process');
|
||||
const os = require('os');
|
||||
const knexfile = path.resolve(__dirname, '..', '..', 'knexfile.js');
|
||||
const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-knexenv-'));
|
||||
const childEnv = { PATH: process.env.PATH };
|
||||
if (env.NODE_ENV !== undefined) childEnv.NODE_ENV = env.NODE_ENV;
|
||||
const out = execFileSync(
|
||||
process.execPath,
|
||||
['-e', `process.stdout.write(String(require(${JSON.stringify(knexfile)}).client))`],
|
||||
{ cwd, env: childEnv, encoding: 'utf8' },
|
||||
);
|
||||
return out.trim();
|
||||
}
|
||||
|
||||
test('an unset NODE_ENV resolves to sqlite — the trap the image fell into', () => {
|
||||
expect(clientFor({})).toBe('sqlite3');
|
||||
});
|
||||
|
||||
test('NODE_ENV=production resolves to pg, so the Dockerfile default fixes it', () => {
|
||||
expect(clientFor({ NODE_ENV: 'production' })).toBe('pg');
|
||||
});
|
||||
|
||||
test('the Dockerfile pins NODE_ENV=production', () => {
|
||||
const dockerfile = fs.readFileSync(
|
||||
path.resolve(__dirname, '..', '..', 'Dockerfile'), 'utf8',
|
||||
);
|
||||
expect(dockerfile).toMatch(/^ENV NODE_ENV=production$/m);
|
||||
});
|
||||
});
|
||||
|
||||
describe('describeEngine', () => {
|
||||
// Built at runtime rather than written inline: a literal after `password:`
|
||||
// trips secret scanners, and this is a marker string, not a credential.
|
||||
const FAKE_CREDENTIAL = ['not', 'a', 'real', 'credential'].join('-');
|
||||
|
||||
test('names the postgres host/port/database', () => {
|
||||
const text = describeEngine({
|
||||
client: 'pg',
|
||||
connection: { host: 'db.internal', port: 5432, database: 'picpeak', password: FAKE_CREDENTIAL },
|
||||
});
|
||||
expect(text).toBe('postgres (db.internal:5432/picpeak)');
|
||||
});
|
||||
|
||||
test('never leaks the password', () => {
|
||||
const text = describeEngine({
|
||||
client: 'pg',
|
||||
connection: { host: 'h', port: 5432, database: 'd', password: FAKE_CREDENTIAL, user: 'picpeak' },
|
||||
});
|
||||
expect(text).not.toContain(FAKE_CREDENTIAL);
|
||||
});
|
||||
|
||||
test('names the sqlite file', () => {
|
||||
expect(describeEngine({ client: 'sqlite3', connection: { filename: '/app/data/x.db' } }))
|
||||
.toBe('sqlite (/app/data/x.db)');
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveSqlitePath', () => {
|
||||
const ORIGINAL = process.env.DATABASE_PATH;
|
||||
afterEach(() => {
|
||||
if (ORIGINAL === undefined) delete process.env.DATABASE_PATH;
|
||||
else process.env.DATABASE_PATH = ORIGINAL;
|
||||
});
|
||||
|
||||
test('defaults to backend/data/photo_sharing.db', () => {
|
||||
delete process.env.DATABASE_PATH;
|
||||
expect(resolveSqlitePath().endsWith(path.join('data', 'photo_sharing.db'))).toBe(true);
|
||||
expect(path.isAbsolute(resolveSqlitePath())).toBe(true);
|
||||
});
|
||||
|
||||
test('honours an absolute DATABASE_PATH', () => {
|
||||
process.env.DATABASE_PATH = '/var/lib/picpeak/db.sqlite';
|
||||
expect(resolveSqlitePath()).toBe('/var/lib/picpeak/db.sqlite');
|
||||
});
|
||||
});
|
||||
|
||||
describe('decideBootEngine — what an existing install gets after the fix', () => {
|
||||
test('STAYS on SQLite when Postgres is configured but holds no galleries', () => {
|
||||
// The install that has been unknowingly running on SQLite. Switching would
|
||||
// serve an empty database; blocking would take the galleries offline. It
|
||||
// keeps running exactly as before, loudly.
|
||||
const r = decideBootEngine({
|
||||
configuredClient: 'pg', explicitClient: null, pgHasData: false, sqliteHasData: true,
|
||||
});
|
||||
expect(r.client).toBe('sqlite3');
|
||||
expect(r.overridden).toBe(true);
|
||||
expect(r.reason).toBe('stranded-sqlite-data');
|
||||
});
|
||||
|
||||
test('switches to Postgres by itself once the data is there', () => {
|
||||
// i.e. straight after scripts/migrate-sqlite-to-postgres.js — no further
|
||||
// operator action needed on the next restart. The marker is what makes it
|
||||
// unambiguous; without one, data on both sides is a conflict (see below).
|
||||
const r = decideBootEngine({
|
||||
configuredClient: 'pg', explicitClient: null, pgHasData: true, sqliteHasData: true,
|
||||
migrationCompleted: true, pgConfigured: true,
|
||||
});
|
||||
expect(r.client).toBe('pg');
|
||||
expect(r.overridden).toBe(false);
|
||||
});
|
||||
|
||||
test('a fresh install with no SQLite file goes straight to Postgres', () => {
|
||||
expect(decideBootEngine({
|
||||
configuredClient: 'pg', explicitClient: null, pgHasData: false, sqliteHasData: false,
|
||||
}).client).toBe('pg');
|
||||
});
|
||||
|
||||
test('an explicit DATABASE_CLIENT is always honoured', () => {
|
||||
expect(decideBootEngine({
|
||||
configuredClient: 'pg', explicitClient: 'sqlite3', pgHasData: true, sqliteHasData: true,
|
||||
}).client).toBe('sqlite3');
|
||||
expect(decideBootEngine({
|
||||
configuredClient: 'sqlite3', explicitClient: 'pg', pgHasData: false, sqliteHasData: false,
|
||||
}).client).toBe('pg');
|
||||
});
|
||||
|
||||
test('forcing pg while SQLite still holds data is allowed, but flagged', () => {
|
||||
const r = decideBootEngine({
|
||||
configuredClient: 'pg', explicitClient: 'pg', pgHasData: false, sqliteHasData: true,
|
||||
});
|
||||
expect(r.client).toBe('pg');
|
||||
expect(r.reason).toBe('explicit-pg-leaves-sqlite-behind');
|
||||
});
|
||||
|
||||
test('keyed on DATA, not on tables: a migrated-but-empty Postgres still defers to SQLite', () => {
|
||||
// A stray `run-migrations` against the empty Postgres creates every table.
|
||||
// Keying the check on "has tables" would blind it and strand the operator
|
||||
// on an empty database; keying on rows survives that.
|
||||
expect(decideBootEngine({
|
||||
configuredClient: 'pg', explicitClient: null, pgHasData: false, sqliteHasData: true,
|
||||
}).client).toBe('sqlite3');
|
||||
});
|
||||
});
|
||||
|
||||
describe('cross-engine row coercion (#1038)', () => {
|
||||
test('epoch milliseconds become an ISO timestamp Postgres accepts', () => {
|
||||
// SQLite writes Date objects as epoch ms; pg rejects the bare number with
|
||||
// "date/time field value out of range".
|
||||
expect(epochToIso(1786548038763)).toBe('2026-08-12T15:20:38.763Z');
|
||||
});
|
||||
|
||||
test('epoch seconds are recognised too', () => {
|
||||
expect(epochToIso(1786548038)).toBe('2026-08-12T15:20:38.000Z');
|
||||
});
|
||||
|
||||
test('a non-numeric value is left alone', () => {
|
||||
expect(epochToIso('not-a-date')).toBe('not-a-date');
|
||||
});
|
||||
|
||||
test('timestamp and boolean columns are coerced, others untouched', () => {
|
||||
const rows = [{
|
||||
id: 1, created_at: 1786548038763, expires_at: '1786548038763',
|
||||
allow_downloads: 0, allow_user_uploads: 1, event_name: 'Wedding', hero_photo_id: null,
|
||||
}];
|
||||
const [out] = coerceForTargetEngine(rows, {
|
||||
timestamps: ['created_at', 'expires_at'],
|
||||
booleans: ['allow_downloads', 'allow_user_uploads'],
|
||||
});
|
||||
expect(out.created_at).toBe('2026-08-12T15:20:38.763Z');
|
||||
expect(out.expires_at).toBe('2026-08-12T15:20:38.763Z');
|
||||
expect(out.allow_downloads).toBe(false);
|
||||
expect(out.allow_user_uploads).toBe(true);
|
||||
expect(out.event_name).toBe('Wedding');
|
||||
expect(out.hero_photo_id).toBeNull();
|
||||
expect(out.id).toBe(1);
|
||||
});
|
||||
|
||||
test('nulls and empty strings survive untouched', () => {
|
||||
const [out] = coerceForTargetEngine(
|
||||
[{ created_at: null, expires_at: '', allow_downloads: null }],
|
||||
{ timestamps: ['created_at', 'expires_at'], booleans: ['allow_downloads'] },
|
||||
);
|
||||
expect(out.created_at).toBeNull();
|
||||
expect(out.expires_at).toBe('');
|
||||
expect(out.allow_downloads).toBeNull();
|
||||
});
|
||||
|
||||
test('an ISO string is not mangled into a number', () => {
|
||||
const [out] = coerceForTargetEngine(
|
||||
[{ created_at: '2026-08-12T15:20:38.763Z' }], { timestamps: ['created_at'], booleans: [] },
|
||||
);
|
||||
expect(out.created_at).toBe('2026-08-12T15:20:38.763Z');
|
||||
});
|
||||
});
|
||||
|
||||
describe('probeSqliteData fails closed (#1038 review)', () => {
|
||||
function tmpDb(contents) {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-probe-'));
|
||||
const file = path.join(dir, 'photo_sharing.db');
|
||||
fs.writeFileSync(file, contents);
|
||||
return file;
|
||||
}
|
||||
|
||||
test('a corrupt/unreadable file counts as "holds data", never as empty', async () => {
|
||||
// Reporting "no data" here would switch the install to an empty Postgres —
|
||||
// the exact failure this module exists to prevent.
|
||||
await expect(probeSqliteData(tmpDb('this is not a sqlite database'))).resolves.toBe(true);
|
||||
});
|
||||
|
||||
test('a missing file is genuinely no data', async () => {
|
||||
await expect(probeSqliteData('/nonexistent/photo_sharing.db')).resolves.toBe(false);
|
||||
});
|
||||
|
||||
test('the migration marker pins the install to Postgres', async () => {
|
||||
// Once migrated, a Postgres that merely LOOKS empty (every gallery deleted)
|
||||
// must not send the install back to the now-stale SQLite file.
|
||||
const file = tmpDb('this is not a sqlite database');
|
||||
expect(hasMigrationMarker(file)).toBe(false);
|
||||
expect(await probeSqliteData(file)).toBe(true);
|
||||
|
||||
fs.writeFileSync(migrationMarkerPath(file), '{}');
|
||||
expect(hasMigrationMarker(file)).toBe(true);
|
||||
expect(await probeSqliteData(file)).toBe(false);
|
||||
});
|
||||
|
||||
test('the marker sits next to the database file', () => {
|
||||
expect(migrationMarkerPath('/app/data/photo_sharing.db'))
|
||||
.toBe('/app/data/photo_sharing.db.migrated-to-postgres');
|
||||
});
|
||||
});
|
||||
|
||||
describe('an unfinished migration pins the boot to SQLite (#1038 review)', () => {
|
||||
// A migration that dies after touching Postgres leaves rows there — schema
|
||||
// creation alone seeds a bootstrap admin when ADMIN_PASSWORD is set. Those
|
||||
// rows read as "occupied", so without a pin the next restart would switch
|
||||
// engines and hide the SQLite data that is still authoritative.
|
||||
test('Postgres holding partial data does NOT win while the migration is unfinished', () => {
|
||||
const r = decideBootEngine({
|
||||
configuredClient: 'pg',
|
||||
explicitClient: null,
|
||||
pgHasData: true, // e.g. just the bootstrap admin, or a half-load
|
||||
sqliteHasData: true,
|
||||
migrationInProgress: true,
|
||||
});
|
||||
expect(r.client).toBe('sqlite3');
|
||||
expect(r.reason).toBe('migration-incomplete');
|
||||
});
|
||||
|
||||
test('once the migration completes, Postgres wins again', () => {
|
||||
// Completed means the marker exists — that is what distinguishes this from
|
||||
// two populated databases nobody has reconciled.
|
||||
expect(decideBootEngine({
|
||||
configuredClient: 'pg',
|
||||
explicitClient: null,
|
||||
pgHasData: true,
|
||||
sqliteHasData: true,
|
||||
migrationInProgress: false,
|
||||
migrationCompleted: true,
|
||||
pgConfigured: true,
|
||||
}).client).toBe('pg');
|
||||
});
|
||||
|
||||
test('the pin is irrelevant when there is no SQLite data to protect', () => {
|
||||
expect(decideBootEngine({
|
||||
configuredClient: 'pg',
|
||||
explicitClient: null,
|
||||
pgHasData: true,
|
||||
sqliteHasData: false,
|
||||
migrationInProgress: true,
|
||||
}).client).toBe('pg');
|
||||
});
|
||||
|
||||
test('the pin file sits next to the database', () => {
|
||||
expect(migrationInProgressPath('/app/data/photo_sharing.db'))
|
||||
.toBe('/app/data/photo_sharing.db.migration-in-progress');
|
||||
expect(hasMigrationInProgress('/nonexistent/photo_sharing.db')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the migration pin outranks an explicit client (#1038 review r6)', () => {
|
||||
// docker-compose sets DATABASE_CLIENT=pg, so without this an unfinished
|
||||
// migration would be ignored on exactly the deployments that pin it, and a
|
||||
// half-written Postgres would be served.
|
||||
test('explicit pg loses to an unfinished migration while SQLite holds data', () => {
|
||||
const r = decideBootEngine({
|
||||
configuredClient: 'pg', explicitClient: 'pg',
|
||||
pgHasData: true, sqliteHasData: true, migrationInProgress: true,
|
||||
});
|
||||
expect(r.client).toBe('sqlite3');
|
||||
expect(r.reason).toBe('migration-incomplete');
|
||||
});
|
||||
|
||||
test('explicit sqlite3 is left alone — it already points at the data', () => {
|
||||
expect(decideBootEngine({
|
||||
configuredClient: 'pg', explicitClient: 'sqlite3',
|
||||
pgHasData: true, sqliteHasData: true, migrationInProgress: true,
|
||||
}).client).toBe('sqlite3');
|
||||
});
|
||||
|
||||
test('once the migration finishes, explicit pg is honoured again', () => {
|
||||
expect(decideBootEngine({
|
||||
configuredClient: 'pg', explicitClient: 'pg',
|
||||
pgHasData: true, sqliteHasData: true, migrationInProgress: false,
|
||||
}).client).toBe('pg');
|
||||
});
|
||||
|
||||
test('a pin with no SQLite data left does not strand the install', () => {
|
||||
expect(decideBootEngine({
|
||||
configuredClient: 'pg', explicitClient: 'pg',
|
||||
pgHasData: true, sqliteHasData: false, migrationInProgress: true,
|
||||
}).client).toBe('pg');
|
||||
});
|
||||
});
|
||||
|
||||
describe('bootstrap admin vs real admin (#1038 review r7)', () => {
|
||||
// core/001_init.js seeds must_change_password=true when ADMIN_PASSWORD is set;
|
||||
// setupService writes false once a human finishes first-run setup. Judging by
|
||||
// the FLAG rather than the table keeps both mistakes away: counting the seed
|
||||
// as real data would abandon a populated SQLite file, and ignoring the whole
|
||||
// table would abandon a legitimately set-up Postgres.
|
||||
test('an untouched seeded row is recognised across both engines', () => {
|
||||
expect(isUntouchedBootstrapRow(true)).toBe(true);
|
||||
expect(isUntouchedBootstrapRow(1)).toBe(true);
|
||||
expect(isUntouchedBootstrapRow('1')).toBe(true);
|
||||
});
|
||||
|
||||
test('a completed setup is not a bootstrap row', () => {
|
||||
expect(isUntouchedBootstrapRow(false)).toBe(false);
|
||||
expect(isUntouchedBootstrapRow(0)).toBe(false);
|
||||
expect(isUntouchedBootstrapRow('0')).toBe(false);
|
||||
});
|
||||
|
||||
test('a legacy NULL counts as a real admin, not a seed', () => {
|
||||
expect(isUntouchedBootstrapRow(null)).toBe(false);
|
||||
expect(isUntouchedBootstrapRow(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('admin rows: bootstrap seed vs real use (#1038 review r7/r8)', () => {
|
||||
// must_change_password alone is mutable — resetAdminPassword() sets it on real
|
||||
// accounts — so it cannot be the only signal. Only the exact shape
|
||||
// core/001_init.js leaves behind reads as an untouched seed.
|
||||
test('one never-used seeded admin is NOT use', () => {
|
||||
expect(adminsIndicateUse([{ must_change_password: true, last_login: null }])).toBe(false);
|
||||
expect(adminsIndicateUse([{ must_change_password: 1, last_login: null }])).toBe(false);
|
||||
});
|
||||
|
||||
test('a completed first-run setup IS use', () => {
|
||||
expect(adminsIndicateUse([{ must_change_password: false, last_login: null }])).toBe(true);
|
||||
});
|
||||
|
||||
test('a real admin whose password was RESET is still use', () => {
|
||||
// resetAdminPassword() re-raises must_change_password on a live account.
|
||||
expect(adminsIndicateUse([
|
||||
{ must_change_password: true, last_login: '2026-08-01T10:00:00Z' },
|
||||
])).toBe(true);
|
||||
});
|
||||
|
||||
test('more than one admin is use regardless of flags', () => {
|
||||
expect(adminsIndicateUse([
|
||||
{ must_change_password: true, last_login: null },
|
||||
{ must_change_password: true, last_login: null },
|
||||
])).toBe(true);
|
||||
});
|
||||
|
||||
test('no admins at all is not use', () => {
|
||||
expect(adminsIndicateUse([])).toBe(false);
|
||||
});
|
||||
|
||||
test('installs predating the last_login column still work', () => {
|
||||
expect(adminsIndicateUse([{ must_change_password: true }])).toBe(false);
|
||||
expect(adminsIndicateUse([{ must_change_password: false }])).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('cross-engine JSON columns pass through untouched (#1038 review r8)', () => {
|
||||
// SQLite keeps json columns as TEXT holding valid JSON, and pg accepts JSON
|
||||
// text directly, so the coercion must not touch them at all: serialising
|
||||
// would store `{"a":1}` as a scalar string, and parse-then-serialise turned
|
||||
// the JSON literal `null` into SQL NULL, breaking NOT NULL json columns.
|
||||
test('timestamps and booleans are coerced; nothing else is', () => {
|
||||
const [out] = coerceForTargetEngine(
|
||||
[{ setting_value: '{"a":1}', nulled: 'null', created_at: 1786548038763, flag: 1 }],
|
||||
{ timestamps: ['created_at'], booleans: ['flag'] },
|
||||
);
|
||||
expect(out.setting_value).toBe('{"a":1}');
|
||||
expect(out.nulled).toBe('null');
|
||||
expect(out.created_at).toBe('2026-08-12T15:20:38.763Z');
|
||||
expect(out.flag).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Postgres probe: unreachable vs unusable (#1038 review r9)', () => {
|
||||
const { probePgData } = require('../../src/utils/databaseEngine');
|
||||
|
||||
test('an unreachable Postgres reports "occupied" so a healthy install is not diverted', async () => {
|
||||
// A transient network failure must not hand a live pg install over to a
|
||||
// stale SQLite file; startup should surface the real connection error.
|
||||
const warnings = [];
|
||||
const result = await probePgData(
|
||||
{ host: '127.0.0.1', port: 59999, user: 'nobody', password: 'x', database: 'nope' },
|
||||
(m) => warnings.push(m),
|
||||
);
|
||||
expect(result).toBe(true);
|
||||
expect(warnings.join(' ')).toMatch(/unreachable/i);
|
||||
}, 30000);
|
||||
});
|
||||
|
||||
describe('a completed migration overrides an implicit SQLite config (#1038 review r11)', () => {
|
||||
// The affected installs ARE the ones with NODE_ENV unset — that is why they
|
||||
// ended up on SQLite. An operator can easily migrate before fixing that, and
|
||||
// by then the source file has been renamed away, so honouring the implicit
|
||||
// sqlite3 would create a NEW empty database and serve it.
|
||||
test('marker + Postgres settings beat an implicitly-resolved sqlite3', () => {
|
||||
const r = decideBootEngine({
|
||||
configuredClient: 'sqlite3', explicitClient: null,
|
||||
pgHasData: true, sqliteHasData: false,
|
||||
migrationCompleted: true, pgConfigured: true,
|
||||
});
|
||||
expect(r.client).toBe('pg');
|
||||
expect(r.reason).toBe('migrated-to-postgres');
|
||||
});
|
||||
|
||||
test('an EXPLICIT sqlite3 still wins — that is a deliberate rollback', () => {
|
||||
expect(decideBootEngine({
|
||||
configuredClient: 'sqlite3', explicitClient: 'sqlite3',
|
||||
pgHasData: true, sqliteHasData: false,
|
||||
migrationCompleted: true, pgConfigured: true,
|
||||
}).client).toBe('sqlite3');
|
||||
});
|
||||
|
||||
test('without Postgres settings there is nowhere to send it', () => {
|
||||
expect(decideBootEngine({
|
||||
configuredClient: 'sqlite3', explicitClient: null,
|
||||
pgHasData: false, sqliteHasData: false,
|
||||
migrationCompleted: true, pgConfigured: false,
|
||||
}).client).toBe('sqlite3');
|
||||
});
|
||||
|
||||
test('no marker, no override — a plain SQLite install is left alone', () => {
|
||||
expect(decideBootEngine({
|
||||
configuredClient: 'sqlite3', explicitClient: null,
|
||||
pgHasData: false, sqliteHasData: true,
|
||||
migrationCompleted: false, pgConfigured: true,
|
||||
}).client).toBe('sqlite3');
|
||||
});
|
||||
});
|
||||
|
||||
describe('two populated databases is a conflict, not a guess (#1038 review r12)', () => {
|
||||
// An install that ran on Postgres, lost NODE_ENV, and kept working on SQLite
|
||||
// has real data on BOTH sides: the Postgres rows are old, the SQLite rows are
|
||||
// newer. Picking either hides galleries and splits future writes.
|
||||
test('no marker + data on both sides refuses to choose', () => {
|
||||
const r = decideBootEngine({
|
||||
configuredClient: 'pg', explicitClient: null,
|
||||
pgHasData: true, sqliteHasData: true, migrationCompleted: false,
|
||||
});
|
||||
expect(r.client).toBeNull();
|
||||
expect(r.reason).toBe('ambiguous-both-populated');
|
||||
});
|
||||
|
||||
test('a completed migration is not a conflict — the marker says which is current', () => {
|
||||
expect(decideBootEngine({
|
||||
configuredClient: 'pg', explicitClient: null,
|
||||
pgHasData: true, sqliteHasData: true, migrationCompleted: true, pgConfigured: true,
|
||||
}).client).toBe('pg');
|
||||
});
|
||||
|
||||
test('an explicit choice always resolves it', () => {
|
||||
expect(decideBootEngine({
|
||||
configuredClient: 'pg', explicitClient: 'sqlite3',
|
||||
pgHasData: true, sqliteHasData: true, migrationCompleted: false,
|
||||
}).client).toBe('sqlite3');
|
||||
expect(decideBootEngine({
|
||||
configuredClient: 'pg', explicitClient: 'pg',
|
||||
pgHasData: true, sqliteHasData: true, migrationCompleted: false,
|
||||
}).client).toBe('pg');
|
||||
});
|
||||
|
||||
test('only one side populated is not a conflict', () => {
|
||||
expect(decideBootEngine({
|
||||
configuredClient: 'pg', explicitClient: null,
|
||||
pgHasData: true, sqliteHasData: false, migrationCompleted: false,
|
||||
}).client).toBe('pg');
|
||||
expect(decideBootEngine({
|
||||
configuredClient: 'pg', explicitClient: null,
|
||||
pgHasData: false, sqliteHasData: true, migrationCompleted: false,
|
||||
}).client).toBe('sqlite3');
|
||||
});
|
||||
|
||||
test('the pg probe target comes from the environment, not a sqlite config', () => {
|
||||
const { pgConnectionFromEnv } = require('../../src/utils/databaseEngine');
|
||||
const prev = { ...process.env };
|
||||
process.env.DB_HOST = 'db.internal';
|
||||
process.env.DB_NAME = 'picpeak_prod';
|
||||
try {
|
||||
const c = pgConnectionFromEnv();
|
||||
expect(c.host).toBe('db.internal');
|
||||
expect(c.database).toBe('picpeak_prod');
|
||||
} finally {
|
||||
process.env.DB_HOST = prev.DB_HOST;
|
||||
process.env.DB_NAME = prev.DB_NAME;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('the target is resolved once, with production defaults (#1038 review r13)', () => {
|
||||
// knexfile's DEVELOPMENT block defaults pg to localhost/postgres/photo_sharing
|
||||
// while production uses db/picpeak/picpeak. The CLI runs in the NODE_ENV-unset
|
||||
// state by design, so without an explicit resolution the migration could land
|
||||
// in a database the running application never opens.
|
||||
const { pgConnectionFromEnv } = require('../../src/utils/databaseEngine');
|
||||
|
||||
test('falls back to what a running container actually uses', () => {
|
||||
// Host is `postgres`, matching wait-for-db.sh, which resolves and EXPORTS
|
||||
// that value — so it is the host a bare container really runs against.
|
||||
// knexfile's production block says `db`, but that default is only reached
|
||||
// when the entrypoint did not run; a `docker exec` CLI has to agree with
|
||||
// the runtime, not with the dormant default (#1038 review r14).
|
||||
const prev = { ...process.env };
|
||||
delete process.env.DB_HOST; delete process.env.DB_USER; delete process.env.DB_NAME;
|
||||
try {
|
||||
const c = pgConnectionFromEnv();
|
||||
expect(c.host).toBe('postgres');
|
||||
expect(c.user).toBe('picpeak');
|
||||
expect(c.database).toBe('picpeak');
|
||||
} finally {
|
||||
Object.assign(process.env, prev);
|
||||
}
|
||||
});
|
||||
|
||||
test('explicit settings always win', () => {
|
||||
const prev = { ...process.env };
|
||||
process.env.DB_HOST = 'pg.example'; process.env.DB_NAME = 'mypics';
|
||||
try {
|
||||
const c = pgConnectionFromEnv();
|
||||
expect(c.host).toBe('pg.example');
|
||||
expect(c.database).toBe('mypics');
|
||||
} finally {
|
||||
Object.assign(process.env, prev);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('the marker is bound to the target it describes (#1038 review r15)', () => {
|
||||
const { currentPgTargetId, readMigrationMarker } = require('../../src/utils/databaseEngine');
|
||||
|
||||
test('the target id has the shape the migration records', () => {
|
||||
const prev = { ...process.env };
|
||||
process.env.DB_HOST = 'pg.host'; process.env.DB_PORT = '6543'; process.env.DB_NAME = 'picpeak_prod';
|
||||
try {
|
||||
expect(currentPgTargetId()).toBe('pg.host:6543/picpeak_prod');
|
||||
} finally {
|
||||
Object.assign(process.env, prev);
|
||||
}
|
||||
});
|
||||
|
||||
test('an absent or unreadable marker reads as null, not a throw', () => {
|
||||
expect(readMigrationMarker('/nonexistent/photo_sharing.db')).toBeNull();
|
||||
});
|
||||
|
||||
test('inbound_documents is a real table; incoming_invoices never was', () => {
|
||||
// The occupancy lists silently skip tables that do not exist, so a wrong
|
||||
// name meant supplier documents never protected the install.
|
||||
const src = fs.readFileSync(
|
||||
path.resolve(__dirname, '..', '..', 'src', 'utils', 'databaseEngine.js'), 'utf8',
|
||||
);
|
||||
const cli = fs.readFileSync(
|
||||
path.resolve(__dirname, '..', '..', 'scripts', 'migrate-sqlite-to-postgres.js'), 'utf8',
|
||||
);
|
||||
for (const text of [src, cli]) {
|
||||
expect(text).toContain("'inbound_documents'");
|
||||
expect(text).not.toContain("'incoming_invoices'");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,177 +0,0 @@
|
||||
/**
|
||||
* Unit tests for rating removal (#884).
|
||||
*
|
||||
* Pins the contract of `feedbackService.submitFeedback` for
|
||||
* `feedback_type: 'rating'` with `rating: 0` ("clear my rating"):
|
||||
* - An existing rating row is DELETED (not updated to 0 — a stored 0
|
||||
* would drag the photo's average down and still count in totals).
|
||||
* - Photo stats (average_rating) are recalculated after the delete.
|
||||
* - Rating 0 with no existing rating is a no-op that never inserts a row.
|
||||
* - Removal is guest-scoped: clearing guest A's rating leaves guest B's
|
||||
* rating (and the resulting average) intact.
|
||||
* - Regular re-rating (3 → 5) still updates in place.
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.TEST_DATABASE_PATH = path.join(
|
||||
fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-rating-removal-')), 'db.sqlite',
|
||||
);
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'rating-removal-test-secret';
|
||||
|
||||
const { bootCrmDb, seedMinimal } = require('../integration/helpers/crmDb');
|
||||
|
||||
const feedbackService = require('../../src/services/feedbackService');
|
||||
|
||||
const EVENT_SLUG = 'rating-removal-event';
|
||||
const GUEST_A = 'guest-a-identifier';
|
||||
const GUEST_B = 'guest-b-identifier';
|
||||
|
||||
let db;
|
||||
let cleanup;
|
||||
let eventId;
|
||||
let photoId;
|
||||
|
||||
async function rate(rating, guestIdentifier = GUEST_A) {
|
||||
return feedbackService.submitFeedback(photoId, eventId, {
|
||||
feedback_type: 'rating',
|
||||
rating,
|
||||
ip_address: '127.0.0.1',
|
||||
user_agent: 'jest',
|
||||
}, guestIdentifier);
|
||||
}
|
||||
|
||||
async function ratingRows(guestIdentifier) {
|
||||
const q = db('photo_feedback').where({
|
||||
photo_id: photoId,
|
||||
feedback_type: 'rating',
|
||||
});
|
||||
if (guestIdentifier) q.where('guest_identifier', guestIdentifier);
|
||||
return q.select('*');
|
||||
}
|
||||
|
||||
async function photoAverage() {
|
||||
const photo = await db('photos').where('id', photoId).first();
|
||||
return Number(photo.average_rating);
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
await seedMinimal(db);
|
||||
const inserted = await db('events').insert({
|
||||
slug: EVENT_SLUG,
|
||||
event_type: 'wedding',
|
||||
event_name: 'Rating Removal Test',
|
||||
event_date: '2026-06-22',
|
||||
host_email: 'host@example.com',
|
||||
admin_email: 'admin@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: `/gallery/${EVENT_SLUG}/share`,
|
||||
share_token: 'rating-removal-share',
|
||||
expires_at: new Date(Date.now() + 7 * 24 * 3600 * 1000).toISOString(),
|
||||
is_active: 1,
|
||||
is_archived: 0,
|
||||
is_draft: 0,
|
||||
created_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
eventId = inserted[0]?.id ?? inserted[0];
|
||||
|
||||
const r = await db('photos').insert({
|
||||
event_id: eventId,
|
||||
filename: 'photo-1.jpg',
|
||||
path: 'events/rating-removal/1.jpg',
|
||||
type: 'individual',
|
||||
uploaded_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
photoId = r[0]?.id ?? r[0];
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => { if (cleanup) await cleanup(); });
|
||||
|
||||
beforeEach(async () => {
|
||||
await db('photo_feedback').where('event_id', eventId).del();
|
||||
await db('photos').where('id', photoId).update({ average_rating: 0, feedback_count: 0 });
|
||||
});
|
||||
|
||||
describe('rating removal (#884)', () => {
|
||||
test('rating 0 deletes the existing rating row and resets the average', async () => {
|
||||
const created = await rate(4);
|
||||
expect(created.created).toBe(true);
|
||||
expect(await photoAverage()).toBe(4);
|
||||
|
||||
const removed = await rate(0);
|
||||
expect(removed.removed).toBe(true);
|
||||
expect(await ratingRows(GUEST_A)).toHaveLength(0);
|
||||
expect(await photoAverage()).toBe(0);
|
||||
});
|
||||
|
||||
test('rating 0 without an existing rating is a no-op (no 0-row inserted)', async () => {
|
||||
const r = await rate(0);
|
||||
expect(r.removed).toBe(true);
|
||||
expect(await ratingRows()).toHaveLength(0);
|
||||
expect(await photoAverage()).toBe(0);
|
||||
});
|
||||
|
||||
test('removal is guest-scoped: guest B keeps their rating and the average', async () => {
|
||||
await rate(2, GUEST_A);
|
||||
await rate(4, GUEST_B);
|
||||
expect(await photoAverage()).toBe(3);
|
||||
|
||||
const removed = await rate(0, GUEST_A);
|
||||
expect(removed.removed).toBe(true);
|
||||
expect(await ratingRows(GUEST_A)).toHaveLength(0);
|
||||
expect(await ratingRows(GUEST_B)).toHaveLength(1);
|
||||
expect(await photoAverage()).toBe(4);
|
||||
});
|
||||
|
||||
test('numeric string "0" also clears (truthy-string bypass guard)', async () => {
|
||||
await rate(4);
|
||||
const removed = await rate('0');
|
||||
expect(removed.removed).toBe(true);
|
||||
expect(await ratingRows(GUEST_A)).toHaveLength(0);
|
||||
expect(await photoAverage()).toBe(0);
|
||||
});
|
||||
|
||||
test('malformed rating input never clears an existing rating', async () => {
|
||||
await rate(4);
|
||||
for (const bad of [undefined, null, 'bad', NaN]) {
|
||||
const r = await rate(bad);
|
||||
expect(r.removed).toBeFalsy();
|
||||
}
|
||||
expect(await ratingRows(GUEST_A)).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('clearing deletes racy duplicate rating rows, not just the first', async () => {
|
||||
// Simulate the check-then-insert race: two rating rows for one guest.
|
||||
const row = {
|
||||
photo_id: photoId,
|
||||
event_id: eventId,
|
||||
feedback_type: 'rating',
|
||||
guest_identifier: GUEST_A,
|
||||
is_approved: 1,
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
};
|
||||
await db('photo_feedback').insert({ ...row, rating: 3 });
|
||||
await db('photo_feedback').insert({ ...row, rating: 5 });
|
||||
expect(await ratingRows(GUEST_A)).toHaveLength(2);
|
||||
|
||||
const removed = await rate(0);
|
||||
expect(removed.removed).toBe(true);
|
||||
expect(await ratingRows(GUEST_A)).toHaveLength(0);
|
||||
expect(await photoAverage()).toBe(0);
|
||||
});
|
||||
|
||||
test('re-rating with a different value still updates in place', async () => {
|
||||
await rate(3);
|
||||
const updated = await rate(5);
|
||||
expect(updated.updated).toBe(true);
|
||||
const rows = await ratingRows(GUEST_A);
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0].rating).toBe(5);
|
||||
expect(await photoAverage()).toBe(5);
|
||||
});
|
||||
});
|
||||
@@ -1,202 +0,0 @@
|
||||
/**
|
||||
* Emoji reactions (#839) — pins the contract of the `reaction` feedback type:
|
||||
* - only emojis from the fixed curated set are accepted
|
||||
* - one reaction per guest per photo: same emoji again toggles OFF,
|
||||
* a different emoji SWITCHES the existing row (never a second row)
|
||||
* - per-guest scoping mirrors likes: guest_id when present, else the
|
||||
* device-hash guest_identifier — two token-guests on one device react
|
||||
* independently
|
||||
* - denormalized photos.reaction_count and the per-emoji tallies follow
|
||||
* visibility: hidden-by-moderator reactions disappear from both
|
||||
* - the long and pivoted exports carry the reaction
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.TEST_DATABASE_PATH = path.join(
|
||||
fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-feedback-reactions-')), 'db.sqlite',
|
||||
);
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'feedback-reactions-test-secret';
|
||||
|
||||
const { bootCrmDb, seedMinimal } = require('../integration/helpers/crmDb');
|
||||
|
||||
const feedbackService = require('../../src/services/feedbackService');
|
||||
const { REACTION_EMOJIS } = require('../../src/constants/reactions');
|
||||
|
||||
const EVENT_SLUG = 'reactions-test-event';
|
||||
const GUEST_A = 'guest-a-identifier';
|
||||
const GUEST_B = 'guest-b-identifier';
|
||||
|
||||
let db;
|
||||
let cleanup;
|
||||
let eventId;
|
||||
let photoIds;
|
||||
|
||||
async function react(photoId, emoji, { guestIdentifier = GUEST_A, guestId = null } = {}) {
|
||||
return feedbackService.submitFeedback(photoId, eventId, {
|
||||
feedback_type: 'reaction',
|
||||
reaction: emoji,
|
||||
guest_id: guestId,
|
||||
ip_address: '127.0.0.1',
|
||||
user_agent: 'jest',
|
||||
}, guestIdentifier);
|
||||
}
|
||||
|
||||
async function reactionCountOf(photoId) {
|
||||
const row = await db('photos').where('id', photoId).first();
|
||||
return Number(row.reaction_count) || 0;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
await seedMinimal(db);
|
||||
const inserted = await db('events').insert({
|
||||
slug: EVENT_SLUG,
|
||||
event_type: 'wedding',
|
||||
event_name: 'Reactions Test',
|
||||
event_date: '2026-07-20',
|
||||
host_email: 'host@example.com',
|
||||
admin_email: 'admin@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: `/gallery/${EVENT_SLUG}/share`,
|
||||
share_token: 'reactions-test-share',
|
||||
expires_at: new Date(Date.now() + 7 * 24 * 3600 * 1000).toISOString(),
|
||||
is_active: 1,
|
||||
is_archived: 0,
|
||||
is_draft: 0,
|
||||
created_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
eventId = inserted[0]?.id ?? inserted[0];
|
||||
|
||||
photoIds = [];
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const photo = await db('photos').insert({
|
||||
event_id: eventId,
|
||||
filename: `photo-${i}.jpg`,
|
||||
path: `events/reactions/${i}.jpg`,
|
||||
type: 'individual',
|
||||
uploaded_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
photoIds.push(photo[0]?.id ?? photo[0]);
|
||||
}
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => {
|
||||
if (cleanup) await cleanup();
|
||||
});
|
||||
|
||||
describe('reaction submission (#839)', () => {
|
||||
it('rejects emojis outside the curated set', async () => {
|
||||
await expect(react(photoIds[0], '🦄')).rejects.toThrow('Invalid reaction');
|
||||
await expect(react(photoIds[0], undefined)).rejects.toThrow('Invalid reaction');
|
||||
expect(await reactionCountOf(photoIds[0])).toBe(0);
|
||||
});
|
||||
|
||||
it('creates a reaction row and maintains the denormalized count', async () => {
|
||||
const result = await react(photoIds[0], '❤️');
|
||||
expect(result.created).toBe(true);
|
||||
|
||||
const row = await db('photo_feedback')
|
||||
.where({ photo_id: photoIds[0], feedback_type: 'reaction' })
|
||||
.first();
|
||||
expect(row.reaction).toBe('❤️');
|
||||
expect(await reactionCountOf(photoIds[0])).toBe(1);
|
||||
expect(await feedbackService.getPhotoReactionCounts(photoIds[0])).toEqual({ '❤️': 1 });
|
||||
});
|
||||
|
||||
it('switches to another emoji in place — never a second row per guest', async () => {
|
||||
const result = await react(photoIds[0], '🎉');
|
||||
expect(result.updated).toBe(true);
|
||||
|
||||
const rows = await db('photo_feedback')
|
||||
.where({ photo_id: photoIds[0], feedback_type: 'reaction' });
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0].reaction).toBe('🎉');
|
||||
expect(await feedbackService.getPhotoReactionCounts(photoIds[0])).toEqual({ '🎉': 1 });
|
||||
});
|
||||
|
||||
it('tallies different guests per emoji', async () => {
|
||||
await react(photoIds[0], '🎉', { guestIdentifier: GUEST_B });
|
||||
expect(await feedbackService.getPhotoReactionCounts(photoIds[0])).toEqual({ '🎉': 2 });
|
||||
expect(await reactionCountOf(photoIds[0])).toBe(2);
|
||||
});
|
||||
|
||||
it('toggles off with the same emoji', async () => {
|
||||
const result = await react(photoIds[0], '🎉');
|
||||
expect(result.removed).toBe(true);
|
||||
expect(await feedbackService.getPhotoReactionCounts(photoIds[0])).toEqual({ '🎉': 1 }); // GUEST_B remains
|
||||
expect(await reactionCountOf(photoIds[0])).toBe(1);
|
||||
});
|
||||
|
||||
it('scopes per guest_id when present — two token-guests on one device stay independent', async () => {
|
||||
const first = await react(photoIds[1], '😍', { guestIdentifier: GUEST_A, guestId: 101 });
|
||||
const second = await react(photoIds[1], '👏', { guestIdentifier: GUEST_A, guestId: 102 });
|
||||
expect(first.created).toBe(true);
|
||||
expect(second.created).toBe(true); // NOT treated as guest 101's switch
|
||||
expect(await feedbackService.getPhotoReactionCounts(photoIds[1])).toEqual({ '😍': 1, '👏': 1 });
|
||||
});
|
||||
|
||||
it('accepts every emoji of the curated set', async () => {
|
||||
for (const emoji of REACTION_EMOJIS) {
|
||||
const res = await react(photoIds[2], emoji, { guestIdentifier: `guest-${emoji}` });
|
||||
expect(res.created).toBe(true);
|
||||
}
|
||||
const counts = await feedbackService.getPhotoReactionCounts(photoIds[2]);
|
||||
expect(Object.keys(counts)).toHaveLength(REACTION_EMOJIS.length);
|
||||
});
|
||||
|
||||
it('hidden reactions leave both the per-emoji tallies and reaction_count', async () => {
|
||||
const row = await db('photo_feedback')
|
||||
.where({ photo_id: photoIds[0], feedback_type: 'reaction' })
|
||||
.first();
|
||||
await feedbackService.moderateFeedback(row.id, 'hide', 1);
|
||||
|
||||
expect(await feedbackService.getPhotoReactionCounts(photoIds[0])).toEqual({});
|
||||
expect(await reactionCountOf(photoIds[0])).toBe(0);
|
||||
|
||||
await feedbackService.moderateFeedback(row.id, 'approve', 1);
|
||||
expect(await reactionCountOf(photoIds[0])).toBe(1);
|
||||
});
|
||||
|
||||
it('toggle and switch collapse racy duplicate rows for the same guest', async () => {
|
||||
// Simulate the check-then-insert race: two rows for one guest+photo.
|
||||
const mk = (emoji) => ({
|
||||
photo_id: photoIds[1], event_id: eventId, feedback_type: 'reaction',
|
||||
reaction: emoji, guest_identifier: 'dup-guest', is_approved: true, is_hidden: false,
|
||||
created_at: new Date(), updated_at: new Date(),
|
||||
});
|
||||
await db('photo_feedback').insert([mk('❤️'), mk('❤️')]);
|
||||
|
||||
// Switching converges to exactly ONE row with the new emoji…
|
||||
const switched = await react(photoIds[1], '🎉', { guestIdentifier: 'dup-guest' });
|
||||
expect(switched.updated).toBe(true);
|
||||
let rows = await db('photo_feedback')
|
||||
.where({ photo_id: photoIds[1], feedback_type: 'reaction', guest_identifier: 'dup-guest' });
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0].reaction).toBe('🎉');
|
||||
|
||||
// …and toggle-off removes the full guest-scoped set.
|
||||
await db('photo_feedback').insert(mk('🎉'));
|
||||
const removed = await react(photoIds[1], '🎉', { guestIdentifier: 'dup-guest' });
|
||||
expect(removed.removed).toBe(true);
|
||||
rows = await db('photo_feedback')
|
||||
.where({ photo_id: photoIds[1], feedback_type: 'reaction', guest_identifier: 'dup-guest' });
|
||||
expect(rows).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('summary and exports carry reactions', async () => {
|
||||
const summary = await feedbackService.getEventFeedbackSummary(eventId);
|
||||
expect(Number(summary.stats.total_reactions)).toBeGreaterThan(0);
|
||||
|
||||
const longRows = await feedbackService.exportEventFeedback(eventId);
|
||||
const longReaction = longRows.find((r) => r.feedback_type === 'reaction');
|
||||
expect(longReaction.reaction).toBeTruthy();
|
||||
|
||||
const pivotRows = await feedbackService.exportEventFeedbackPivoted(eventId);
|
||||
const pivotWithReaction = pivotRows.find((r) => r.reaction);
|
||||
expect(REACTION_EMOJIS).toContain(pivotWithReaction.reaction);
|
||||
});
|
||||
});
|
||||
@@ -1,161 +0,0 @@
|
||||
/**
|
||||
* Regression tests for the feedback-settings write path (#1030).
|
||||
*
|
||||
* The admin event form posts its whole client-side feedback state back,
|
||||
* including three keys that were never columns on event_feedback_settings:
|
||||
* `enable_rate_limiting`, `rate_limit_window_minutes` and
|
||||
* `rate_limit_max_requests`. Spreading those into the knex UPDATE threw,
|
||||
* the route answered 500, and EventDetailsPage swallowed it — so the admin
|
||||
* saw "Event updated successfully" while "Enable feedback" never persisted
|
||||
* and guests could not leave any feedback.
|
||||
*
|
||||
* Pinned here:
|
||||
* - UI-only keys are dropped, not written, on BOTH the insert (no row yet)
|
||||
* and update (row exists) branches.
|
||||
* - Every real column still round-trips.
|
||||
* - Identity columns can't be mass-assigned through the settings body.
|
||||
* - gallery.js no longer declares a duplicate GET /:slug/feedback-settings.
|
||||
* server.js mounts galleryRoutes before galleryFeedback, so the duplicate
|
||||
* shadowed the real handler and dropped the #655 per-guest caps from the
|
||||
* guest payload.
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.TEST_DATABASE_PATH = path.join(
|
||||
fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-feedback-settings-')), 'db.sqlite',
|
||||
);
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'feedback-settings-test-secret';
|
||||
|
||||
const { bootCrmDb, seedMinimal } = require('../integration/helpers/crmDb');
|
||||
|
||||
const feedbackService = require('../../src/services/feedbackService');
|
||||
|
||||
// Exactly what EventDetailsPage holds in state before its settings GET
|
||||
// resolves — the three rate-limit keys are UI-only.
|
||||
const ADMIN_FORM_BODY = {
|
||||
feedback_enabled: true,
|
||||
allow_ratings: true,
|
||||
allow_likes: true,
|
||||
allow_comments: true,
|
||||
allow_favorites: true,
|
||||
allow_reactions: true,
|
||||
require_name_email: false,
|
||||
moderate_comments: true,
|
||||
show_feedback_to_guests: true,
|
||||
enable_rate_limiting: false,
|
||||
rate_limit_window_minutes: 15,
|
||||
rate_limit_max_requests: 10,
|
||||
};
|
||||
|
||||
let db;
|
||||
let cleanup;
|
||||
let eventId;
|
||||
|
||||
async function insertEvent(slug) {
|
||||
const inserted = await db('events').insert({
|
||||
slug,
|
||||
event_type: 'wedding',
|
||||
event_name: 'Feedback Settings Test',
|
||||
event_date: '2026-06-22',
|
||||
host_email: 'host@example.com',
|
||||
admin_email: 'admin@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: `/gallery/${slug}/share`,
|
||||
share_token: `${slug}-share`,
|
||||
expires_at: new Date(Date.now() + 7 * 24 * 3600 * 1000).toISOString(),
|
||||
is_active: 1,
|
||||
is_archived: 0,
|
||||
is_draft: 0,
|
||||
created_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
return inserted[0]?.id ?? inserted[0];
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
await seedMinimal(db);
|
||||
eventId = await insertEvent('feedback-settings-test');
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => { if (cleanup) await cleanup(); });
|
||||
|
||||
describe('updateEventFeedbackSettings ignores UI-only keys (#1030)', () => {
|
||||
test('insert branch: enabling feedback on an event with no settings row persists', async () => {
|
||||
const freshEventId = await insertEvent('feedback-settings-fresh');
|
||||
|
||||
const result = await feedbackService.updateEventFeedbackSettings(freshEventId, ADMIN_FORM_BODY);
|
||||
|
||||
expect(result.feedback_enabled).toBeTruthy();
|
||||
const row = await db('event_feedback_settings').where('event_id', freshEventId).first();
|
||||
expect(row).toBeTruthy();
|
||||
expect(row.feedback_enabled).toBeTruthy();
|
||||
expect(row).not.toHaveProperty('enable_rate_limiting');
|
||||
});
|
||||
|
||||
test('update branch: flipping the toggle on an existing row persists', async () => {
|
||||
await feedbackService.updateEventFeedbackSettings(eventId, { feedback_enabled: false });
|
||||
expect((await feedbackService.getEventFeedbackSettings(eventId)).feedback_enabled).toBeFalsy();
|
||||
|
||||
const result = await feedbackService.updateEventFeedbackSettings(eventId, ADMIN_FORM_BODY);
|
||||
|
||||
expect(result.feedback_enabled).toBeTruthy();
|
||||
const rows = await db('event_feedback_settings').where('event_id', eventId);
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0].feedback_enabled).toBeTruthy();
|
||||
});
|
||||
|
||||
test('every real column round-trips', async () => {
|
||||
const result = await feedbackService.updateEventFeedbackSettings(eventId, {
|
||||
...ADMIN_FORM_BODY,
|
||||
allow_comments: false,
|
||||
show_feedback_to_guests: false,
|
||||
identity_mode: 'guest',
|
||||
max_favorites_per_guest: 10,
|
||||
max_likes_per_guest: 5,
|
||||
});
|
||||
|
||||
expect(result.allow_comments).toBeFalsy();
|
||||
expect(result.show_feedback_to_guests).toBeFalsy();
|
||||
expect(result.identity_mode).toBe('guest');
|
||||
expect(result.max_favorites_per_guest).toBe(10);
|
||||
expect(result.max_likes_per_guest).toBe(5);
|
||||
});
|
||||
|
||||
test('identity columns cannot be mass-assigned through the settings body', async () => {
|
||||
const otherEventId = await insertEvent('feedback-settings-other');
|
||||
const before = await db('event_feedback_settings').where('event_id', eventId).first();
|
||||
|
||||
await feedbackService.updateEventFeedbackSettings(eventId, {
|
||||
feedback_enabled: true,
|
||||
id: 99999,
|
||||
event_id: otherEventId,
|
||||
});
|
||||
|
||||
const after = await db('event_feedback_settings').where('event_id', eventId).first();
|
||||
expect(after.id).toBe(before.id);
|
||||
expect(after.event_id).toBe(eventId);
|
||||
expect(await db('event_feedback_settings').where('event_id', otherEventId).first()).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('guest feedback-settings route is not shadowed (#1030)', () => {
|
||||
test('gallery.js does not declare GET /:slug/feedback-settings', () => {
|
||||
const source = fs.readFileSync(
|
||||
path.resolve(__dirname, '..', '..', 'src', 'routes', 'gallery.js'), 'utf8',
|
||||
);
|
||||
expect(source).not.toMatch(/router\.get\(\s*['"]\/:slug\/feedback-settings['"]/);
|
||||
});
|
||||
|
||||
test('galleryFeedback.js still serves it, including the #655 per-guest caps', () => {
|
||||
const source = fs.readFileSync(
|
||||
path.resolve(__dirname, '..', '..', 'src', 'routes', 'galleryFeedback.js'), 'utf8',
|
||||
);
|
||||
expect(source).toMatch(/router\.get\(\s*['"]\/:slug\/feedback-settings['"]/);
|
||||
expect(source).toMatch(/max_favorites_per_guest/);
|
||||
expect(source).toMatch(/max_likes_per_guest/);
|
||||
});
|
||||
});
|
||||
@@ -1,177 +0,0 @@
|
||||
/**
|
||||
* Gallery info banner (#932).
|
||||
*
|
||||
* A short note rendered ABOVE the photo grid — the reporter's case is an
|
||||
* onboarding hint ("use the menu button to filter"), which is useless in the
|
||||
* promo slot down by the footer because the guest has to scroll the whole
|
||||
* gallery to reach it.
|
||||
*
|
||||
* Covers what the migration actually produces on a real engine (the harness
|
||||
* runs SQLite) and the inherit/custom/off resolution the gallery render
|
||||
* depends on. The resolution is duplicated here rather than imported because
|
||||
* it lives in the React layer; the point is to pin the CONTRACT — which
|
||||
* source wins for each mode — so a change on either side has to update this
|
||||
* file deliberately.
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.TEST_DATABASE_PATH = path.join(
|
||||
fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-info-banner-')), 'db.sqlite',
|
||||
);
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'info-banner-test-secret';
|
||||
|
||||
const { bootCrmDb, seedMinimal } = require('../integration/helpers/crmDb');
|
||||
|
||||
let db;
|
||||
let cleanup;
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
await seedMinimal(db);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (cleanup) await cleanup();
|
||||
});
|
||||
|
||||
describe('migration 176 — schema', () => {
|
||||
it('adds events.info_mode defaulting to inherit', async () => {
|
||||
expect(await db.schema.hasColumn('events', 'info_mode')).toBe(true);
|
||||
|
||||
const [id] = await db('events').insert({
|
||||
slug: 'info-default-test',
|
||||
event_type: 'wedding',
|
||||
event_name: 'Info Default Test',
|
||||
event_date: '2026-06-22',
|
||||
host_email: 'host@example.com',
|
||||
admin_email: 'admin@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: '/gallery/info-default-test/share',
|
||||
share_token: 'info-default-test-share',
|
||||
expires_at: new Date(Date.now() + 7 * 24 * 3600 * 1000).toISOString(),
|
||||
is_active: 1,
|
||||
is_archived: 0,
|
||||
is_draft: 0,
|
||||
created_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
const eventId = id?.id ?? id;
|
||||
|
||||
const row = await db('events').where({ id: eventId }).first();
|
||||
// A gallery created before anyone configures the feature must inherit,
|
||||
// so switching the global default on lights up every existing gallery.
|
||||
expect(row.info_mode).toBe('inherit');
|
||||
expect(row.info_markdown ?? null).toBeNull();
|
||||
});
|
||||
|
||||
it('adds events.info_markdown as nullable text', async () => {
|
||||
expect(await db.schema.hasColumn('events', 'info_markdown')).toBe(true);
|
||||
});
|
||||
|
||||
it('seeds branding_info_markdown empty, so upgrading shows no banner', async () => {
|
||||
const row = await db('app_settings').where({ setting_key: 'branding_info_markdown' }).first();
|
||||
expect(row).toBeTruthy();
|
||||
expect(JSON.parse(row.setting_value)).toBe('');
|
||||
expect(row.setting_type).toBe('branding');
|
||||
});
|
||||
});
|
||||
|
||||
// Mirrors GalleryLayout's resolution.
|
||||
function resolveInfoBanner(event, brandingDefault) {
|
||||
const mode = event.info_mode || 'inherit';
|
||||
if (mode === 'off') return '';
|
||||
if (mode === 'custom') {
|
||||
const own = (event.info_markdown || '').trim();
|
||||
return (own || brandingDefault || '').trim();
|
||||
}
|
||||
return (brandingDefault || '').trim();
|
||||
}
|
||||
|
||||
describe('inherit / custom / off resolution', () => {
|
||||
const GLOBAL = 'Use the menu button to filter.';
|
||||
|
||||
it('inherit renders the global default', () => {
|
||||
expect(resolveInfoBanner({ info_mode: 'inherit' }, GLOBAL)).toBe(GLOBAL);
|
||||
});
|
||||
|
||||
it('a missing mode is treated as inherit (rows predating the migration)', () => {
|
||||
expect(resolveInfoBanner({}, GLOBAL)).toBe(GLOBAL);
|
||||
});
|
||||
|
||||
it('custom renders the event copy instead of the global', () => {
|
||||
const own = 'Proofs are watermarked until final delivery.';
|
||||
expect(resolveInfoBanner({ info_mode: 'custom', info_markdown: own }, GLOBAL)).toBe(own);
|
||||
});
|
||||
|
||||
it('custom with blank copy falls back to the global rather than showing nothing', () => {
|
||||
expect(resolveInfoBanner({ info_mode: 'custom', info_markdown: ' ' }, GLOBAL)).toBe(GLOBAL);
|
||||
});
|
||||
|
||||
it('off suppresses the banner even when a global default exists', () => {
|
||||
expect(resolveInfoBanner({ info_mode: 'off' }, GLOBAL)).toBe('');
|
||||
});
|
||||
|
||||
it('off wins over the event own copy too', () => {
|
||||
expect(resolveInfoBanner({ info_mode: 'off', info_markdown: 'ignored' }, GLOBAL)).toBe('');
|
||||
});
|
||||
|
||||
it('an empty global default means no banner anywhere — the upgrade state', () => {
|
||||
expect(resolveInfoBanner({ info_mode: 'inherit' }, '')).toBe('');
|
||||
expect(resolveInfoBanner({}, undefined)).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('per-event persistence', () => {
|
||||
let eventId;
|
||||
|
||||
beforeAll(async () => {
|
||||
const [id] = await db('events').insert({
|
||||
slug: 'info-persist-test',
|
||||
event_type: 'wedding',
|
||||
event_name: 'Info Persist Test',
|
||||
event_date: '2026-06-22',
|
||||
host_email: 'host@example.com',
|
||||
admin_email: 'admin@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: '/gallery/info-persist-test/share',
|
||||
share_token: 'info-persist-test-share',
|
||||
expires_at: new Date(Date.now() + 7 * 24 * 3600 * 1000).toISOString(),
|
||||
is_active: 1,
|
||||
is_archived: 0,
|
||||
is_draft: 0,
|
||||
created_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
eventId = id?.id ?? id;
|
||||
});
|
||||
|
||||
it('stores a custom override', async () => {
|
||||
await db('events').where({ id: eventId })
|
||||
.update({ info_mode: 'custom', info_markdown: '**Heads up** — proofs only.' });
|
||||
|
||||
const row = await db('events').where({ id: eventId }).first();
|
||||
expect(row.info_mode).toBe('custom');
|
||||
expect(row.info_markdown).toBe('**Heads up** — proofs only.');
|
||||
});
|
||||
|
||||
it('switching away from custom clears the stored copy', async () => {
|
||||
// Matches the route's normalisation: mode != custom nulls the text so a
|
||||
// later switch back to custom can't resurrect stale copy.
|
||||
await db('events').where({ id: eventId })
|
||||
.update({ info_mode: 'off', info_markdown: null });
|
||||
|
||||
const row = await db('events').where({ id: eventId }).first();
|
||||
expect(row.info_mode).toBe('off');
|
||||
expect(row.info_markdown).toBeNull();
|
||||
});
|
||||
|
||||
it('the promo banner is untouched by info-banner changes', async () => {
|
||||
const row = await db('events').where({ id: eventId }).first();
|
||||
// Independent slots: the whole point of #932 is that an info hint at the
|
||||
// top does not consume the marketing slot at the bottom.
|
||||
expect(row.promo_mode).toBe('inherit');
|
||||
expect(row.promo_markdown ?? null).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,143 +0,0 @@
|
||||
/**
|
||||
* Regression test for #1024: quote/invoice PDF endpoints 500'd (or silently
|
||||
* corrupted the filename) for customers whose name carries non-ASCII.
|
||||
*
|
||||
* The six PDF routes built the header by interpolating buildPdfFilename()'s
|
||||
* result straight into `inline; filename="${filename}"`. HTTP header values
|
||||
* are latin1, which splits the failure in two — and the split matters,
|
||||
* because the issue reported the umlaut case as the 500 and it isn't:
|
||||
*
|
||||
* U+0080-U+00FF (ä ö ü ß — every German umlaut)
|
||||
* No throw. The byte goes out raw and the client reads back a mangled
|
||||
* name. A silent corruption, not an error.
|
||||
*
|
||||
* above U+00FF (Polish ł, Czech ř, Turkish ş, €, Cyrillic, CJK, emoji)
|
||||
* Node's setHeader rejects it with ERR_INVALID_CHAR. Because the
|
||||
* throw lands after the PDF buffer is already rendered, the whole
|
||||
* request fails as an unhandled 500.
|
||||
*
|
||||
* buildContentDisposition() fixes both: an ASCII fallback for the legacy
|
||||
* `filename=` parameter plus the RFC 5987 `filename*=UTF-8''…` form that
|
||||
* carries the real name.
|
||||
*
|
||||
* These assertions run against the real Node header validator via a live
|
||||
* express server, so they'd fail against the old interpolation rather than
|
||||
* merely testing the helper in isolation.
|
||||
*/
|
||||
const express = require('express');
|
||||
const request = require('supertest');
|
||||
|
||||
const { buildPdfFilename, sanitiseSegment } = require('../../src/utils/pdfFilename');
|
||||
const { buildContentDisposition } = require('../../src/utils/filenameSanitizer');
|
||||
|
||||
// The RFC 5987 parameter prefix, i.e. filename*=UTF-8'' — the two trailing
|
||||
// quotes are the (empty) language tag the spec puts between the charset and
|
||||
// the percent-encoded value.
|
||||
const RFC5987_PREFIX = 'filename*=UTF-8\'\'';
|
||||
|
||||
// Mirrors what the six PDF routes now do.
|
||||
function buildApp(customer, docNumber = 'Q-2026-0042') {
|
||||
const app = express();
|
||||
app.get('/pdf', (req, res) => {
|
||||
const filename = buildPdfFilename({ docNumber, customer, fallback: 'quote-preview' });
|
||||
res.set('Content-Type', 'application/pdf');
|
||||
res.set('Content-Disposition', buildContentDisposition(filename, 'inline'));
|
||||
res.send(Buffer.from('%PDF-1.4 fake'));
|
||||
});
|
||||
// Mirrors the real error handler: an ERR_INVALID_CHAR throw inside the
|
||||
// handler surfaces as a 500, which is what #1024 reported.
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
app.use((err, req, res, next) => res.status(500).json({ error: err.code || err.message }));
|
||||
return app;
|
||||
}
|
||||
|
||||
describe('#1024 — PDF Content-Disposition with non-ASCII customer names', () => {
|
||||
it('serves a PDF for a German umlaut name and keeps the name intact', async () => {
|
||||
const res = await request(buildApp({ company_name: 'Müller Fotografie' })).get('/pdf');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const cd = res.headers['content-disposition'];
|
||||
// RFC 5987 form carries the real, unmangled name...
|
||||
expect(cd).toContain(RFC5987_PREFIX);
|
||||
expect(cd).toContain(encodeURIComponent('Müller-Fotografie.pdf'));
|
||||
// ...and the ASCII fallback is legal latin1 with no raw umlaut byte.
|
||||
const fallback = /filename="([^"]+)"/.exec(cd)[1];
|
||||
expect(fallback).toMatch(/^[\x20-\x7e]+$/);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['Polish', 'Michał Kowalski'],
|
||||
['Czech', 'Dvořák Studio'],
|
||||
['Turkish', 'Şahin Fotoğraf'],
|
||||
['Cyrillic', 'Иванов Фото'],
|
||||
['CJK', '山田写真'],
|
||||
['emoji', 'Studio 🎉 Berlin'],
|
||||
])('does not 500 for a %s customer name (was ERR_INVALID_CHAR)', async (_label, company) => {
|
||||
const res = await request(buildApp({ company_name: company })).get('/pdf');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const cd = res.headers['content-disposition'];
|
||||
expect(cd).toContain(RFC5987_PREFIX);
|
||||
// The legacy filename= token drops non-ASCII, so a name written entirely
|
||||
// in another script degrades to just the document number
|
||||
// (`Q-2026-0042_.pdf`). That's the intended trade — filename* carries the
|
||||
// real name — but the fallback must still be a legal, non-empty,
|
||||
// ASCII-only token, since that is what a client without RFC 5987 support
|
||||
// ends up saving.
|
||||
const fallback = /filename="([^"]*)"/.exec(cd)[1];
|
||||
expect(fallback.length).toBeGreaterThan(0);
|
||||
expect(fallback).toMatch(/^[\x20-\x7e]+$/);
|
||||
expect(fallback).toContain('Q-2026-0042');
|
||||
});
|
||||
|
||||
it('leaves a plain ASCII name on the familiar filename= form', async () => {
|
||||
const res = await request(buildApp({ company_name: 'Bright Studio' })).get('/pdf');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers['content-disposition'])
|
||||
.toContain('filename="Q-2026-0042_Bright-Studio.pdf"');
|
||||
});
|
||||
|
||||
it('still works when the customer row is missing entirely (preview path)', async () => {
|
||||
const res = await request(buildApp(null, null)).get('/pdf');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers['content-disposition']).toContain('quote-preview_customer.pdf');
|
||||
});
|
||||
|
||||
// sanitiseSegment caps each segment at 80 UTF-16 code units. A cap landing
|
||||
// inside an astral character used to leave a dangling high surrogate, which
|
||||
// makes encodeURIComponent throw URIError inside buildContentDisposition —
|
||||
// a 500 on the very endpoint this PR fixes, reached a different way.
|
||||
it.each([
|
||||
['emoji on the 80-char boundary', `${'a'.repeat(79)}🎉`],
|
||||
['astral CJK on the boundary', `${'a'.repeat(79)}𠜎`],
|
||||
['a label that is entirely astral', '🎉'.repeat(60)],
|
||||
])('does not 500 when truncation splits a surrogate pair — %s', async (_label, company) => {
|
||||
const res = await request(buildApp({ company_name: company })).get('/pdf');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers['content-disposition']).toContain(RFC5987_PREFIX);
|
||||
});
|
||||
|
||||
it('drops the orphaned surrogate rather than widening the length cap', () => {
|
||||
const seg = sanitiseSegment(`${'a'.repeat(79)}🎉`);
|
||||
|
||||
// 79 'a's + a half-emoji would be 80; the orphan is dropped, not kept.
|
||||
expect(seg).toHaveLength(79);
|
||||
expect(seg).toBe('a'.repeat(79));
|
||||
// Nothing in the result may be an unpaired surrogate.
|
||||
expect(seg).toBe(seg.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/g, ''));
|
||||
});
|
||||
|
||||
it('the raw interpolation these routes used to do really does throw', () => {
|
||||
// Pins the root cause itself, so nobody "simplifies" the helper away.
|
||||
const filename = buildPdfFilename({
|
||||
docNumber: 'Q-2026-0042',
|
||||
customer: { company_name: 'Michał Kowalski' },
|
||||
});
|
||||
const res = new (require('http').ServerResponse)({});
|
||||
expect(() => res.setHeader('Content-Disposition', `inline; filename="${filename}"`))
|
||||
.toThrow(/ERR_INVALID_CHAR|Invalid character/);
|
||||
});
|
||||
});
|
||||
@@ -1,56 +0,0 @@
|
||||
/**
|
||||
* Unit tests for the global session cutoff (utils/sessionCutoff.js). Uses a
|
||||
* real in-memory SQLite `app_settings` table so the read/write/parse path is
|
||||
* exercised exactly as in production.
|
||||
*/
|
||||
const knex = require('knex');
|
||||
|
||||
let db;
|
||||
let cutoff;
|
||||
|
||||
beforeEach(async () => {
|
||||
db = knex({ client: 'sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true });
|
||||
await db.schema.createTable('app_settings', (t) => {
|
||||
t.increments('id');
|
||||
t.string('setting_key').notNullable().unique();
|
||||
t.text('setting_value');
|
||||
t.string('setting_type');
|
||||
t.timestamp('updated_at');
|
||||
});
|
||||
jest.resetModules();
|
||||
jest.doMock('../../src/database/db', () => ({ db }));
|
||||
cutoff = require('../../src/utils/sessionCutoff');
|
||||
cutoff._resetCache();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
jest.dontMock('../../src/database/db');
|
||||
await db.destroy();
|
||||
});
|
||||
|
||||
test('no cutoff set → nothing is invalidated', async () => {
|
||||
expect(await cutoff.getSessionsValidAfter()).toBe(0);
|
||||
expect(await cutoff.isTokenBeforeCutoff({ iat: 1000 })).toBe(false);
|
||||
});
|
||||
|
||||
test('token issued before the cutoff is rejected, at/after is accepted', async () => {
|
||||
await cutoff.setSessionsValidAfter(2000);
|
||||
expect(await cutoff.isTokenBeforeCutoff({ iat: 1999 })).toBe(true); // pre-restore session
|
||||
expect(await cutoff.isTokenBeforeCutoff({ iat: 2000 })).toBe(false); // same second → kept
|
||||
expect(await cutoff.isTokenBeforeCutoff({ iat: 2001 })).toBe(false); // post-restore login
|
||||
});
|
||||
|
||||
test('setSessionsValidAfter upserts a single row and refreshes the cache', async () => {
|
||||
await cutoff.setSessionsValidAfter(1000);
|
||||
await cutoff.setSessionsValidAfter(3000);
|
||||
const rows = await db('app_settings').where('setting_key', 'security_sessions_valid_after');
|
||||
expect(rows).toHaveLength(1);
|
||||
cutoff._resetCache();
|
||||
expect(await cutoff.getSessionsValidAfter()).toBe(3000);
|
||||
});
|
||||
|
||||
test('a token without iat is never treated as before the cutoff', async () => {
|
||||
await cutoff.setSessionsValidAfter(2000);
|
||||
expect(await cutoff.isTokenBeforeCutoff({})).toBe(false);
|
||||
expect(await cutoff.isTokenBeforeCutoff(null)).toBe(false);
|
||||
});
|
||||
@@ -1,106 +0,0 @@
|
||||
/**
|
||||
* Regression test for clearing an event's expiration on SQLite (#1029).
|
||||
*
|
||||
* Migration 061 dropped the NOT NULL on events.event_date / events.expires_at
|
||||
* for Postgres only — it skipped SQLite on the (wrong) premise that SQLite
|
||||
* doesn't enforce NOT NULL. It does, so every SQLite install answered
|
||||
*
|
||||
* SQLITE_CONSTRAINT: NOT NULL constraint failed: events.expires_at
|
||||
*
|
||||
* when an admin cleared the expiration, surfacing as "Failed to update event".
|
||||
* Migration 174 finishes the job. The harness runs on SQLite, so this asserts
|
||||
* the real engine behaviour rather than a mock.
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.TEST_DATABASE_PATH = path.join(
|
||||
fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-nullable-dates-')), 'db.sqlite',
|
||||
);
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'nullable-dates-test-secret';
|
||||
|
||||
const { bootCrmDb, seedMinimal } = require('../integration/helpers/crmDb');
|
||||
|
||||
let db;
|
||||
let cleanup;
|
||||
let eventId;
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
await seedMinimal(db);
|
||||
const inserted = await db('events').insert({
|
||||
slug: 'nullable-dates-test',
|
||||
event_type: 'wedding',
|
||||
event_name: 'Nullable Dates Test',
|
||||
event_date: '2026-06-22',
|
||||
host_email: 'host@example.com',
|
||||
admin_email: 'admin@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: '/gallery/nullable-dates-test/share',
|
||||
share_token: 'nullable-dates-share',
|
||||
expires_at: new Date(Date.now() + 7 * 24 * 3600 * 1000).toISOString(),
|
||||
is_active: 1,
|
||||
is_archived: 0,
|
||||
is_draft: 0,
|
||||
created_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
eventId = inserted[0]?.id ?? inserted[0];
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => { if (cleanup) await cleanup(); });
|
||||
|
||||
describe('events date columns are nullable on SQLite (#1029)', () => {
|
||||
test('the engine under test really is SQLite', () => {
|
||||
expect(['sqlite3', 'better-sqlite3']).toContain(db.client.config.client);
|
||||
});
|
||||
|
||||
test('clearing expires_at succeeds — this threw SQLITE_CONSTRAINT before migration 174', async () => {
|
||||
await db('events').where('id', eventId).update({ expires_at: null });
|
||||
const row = await db('events').where('id', eventId).first('expires_at');
|
||||
expect(row.expires_at).toBeNull();
|
||||
});
|
||||
|
||||
test('clearing event_date succeeds too (061 covered both columns on PG)', async () => {
|
||||
await db('events').where('id', eventId).update({ event_date: null });
|
||||
const row = await db('events').where('id', eventId).first('event_date');
|
||||
expect(row.event_date).toBeNull();
|
||||
});
|
||||
|
||||
test('a gallery can be created with no expiration at all', async () => {
|
||||
const inserted = await db('events').insert({
|
||||
slug: 'never-expires-test',
|
||||
event_type: 'other',
|
||||
event_name: 'Never Expires',
|
||||
event_date: null,
|
||||
host_email: 'host@example.com',
|
||||
admin_email: 'admin@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: '/gallery/never-expires-test/share',
|
||||
share_token: 'never-expires-share',
|
||||
expires_at: null,
|
||||
is_active: 1,
|
||||
is_archived: 0,
|
||||
is_draft: 0,
|
||||
created_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
const id = inserted[0]?.id ?? inserted[0];
|
||||
const row = await db('events').where('id', id).first('expires_at', 'event_date');
|
||||
expect(row.expires_at).toBeNull();
|
||||
expect(row.event_date).toBeNull();
|
||||
});
|
||||
|
||||
test('columns the events table depends on survived the table rebuild', async () => {
|
||||
// Knex implements .alter() on SQLite by recreating the table; make sure the
|
||||
// rebuild kept the row and the wider schema intact.
|
||||
const row = await db('events').where('id', eventId).first();
|
||||
expect(row.slug).toBe('nullable-dates-test');
|
||||
expect(row.share_token).toBe('nullable-dates-share');
|
||||
expect(await db.schema.hasColumn('events', 'allow_downloads')).toBe(true);
|
||||
expect(await db.schema.hasColumn('events', 'hero_photo_id')).toBe(true);
|
||||
const photos = await db('photos').where('event_id', eventId);
|
||||
expect(Array.isArray(photos)).toBe(true);
|
||||
});
|
||||
});
|
||||
Binary file not shown.
Binary file not shown.
@@ -1,93 +0,0 @@
|
||||
Copyright © 2017 IBM Corp. with Reserved Font Name "Plex"
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
|
||||
This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -1,9 +1,8 @@
|
||||
module.exports = {
|
||||
testEnvironment: 'node',
|
||||
// bootCrmDb() runs EVERY core migration in beforeAll; the chain keeps
|
||||
// growing (163-165 pushed several suites past jest's default on CI
|
||||
// runners — the 3.94 release PR failed on exactly this). 120s matches
|
||||
// the convention the newer suites already pin explicitly.
|
||||
// bootCrmDb() runs EVERY core migration in beforeAll and the chain keeps
|
||||
// growing (134 migrations and counting via backports). 120s matches the
|
||||
// beta-branch convention from #860.
|
||||
testTimeout: 120000,
|
||||
coverageDirectory: 'coverage',
|
||||
collectCoverageFrom: [
|
||||
|
||||
+46
-9
@@ -1,13 +1,39 @@
|
||||
require('dotenv').config();
|
||||
|
||||
const path = require('path');
|
||||
|
||||
// Database configuration for different environments
|
||||
// Shared with the engine guard (#1038) so both resolve the identical path.
|
||||
const { resolveSqliteFilename } = require('./src/utils/sqlitePath');
|
||||
// One resolution of the PostgreSQL target for the whole application (#1038).
|
||||
// The development and production blocks used to carry different host/user/
|
||||
// database defaults, so a process that probed or migrated against one could
|
||||
// hand over to a process that opened another.
|
||||
const { pgConnectionFromEnv } = require('./src/utils/pgConnection');
|
||||
const resolveSqliteFilename = (filenameEnv) => {
|
||||
const fallback = path.join(__dirname, './data/photo_sharing.db');
|
||||
|
||||
if (!filenameEnv) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const trimmed = String(filenameEnv).trim();
|
||||
if (!trimmed) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
let resolved;
|
||||
if (path.isAbsolute(trimmed)) {
|
||||
resolved = trimmed;
|
||||
} else if (trimmed.startsWith('./') || trimmed.startsWith('../')) {
|
||||
resolved = path.resolve(__dirname, trimmed);
|
||||
} else {
|
||||
resolved = path.join(__dirname, trimmed);
|
||||
}
|
||||
|
||||
const normalized = path.normalize(resolved);
|
||||
const baseSuffix = path.relative(path.parse(__dirname).root, path.normalize(__dirname));
|
||||
const duplicatePattern = `${path.sep}${baseSuffix}${path.sep}${baseSuffix}`;
|
||||
|
||||
if (normalized.includes(duplicatePattern)) {
|
||||
return normalized.replace(duplicatePattern, `${path.sep}${baseSuffix}`);
|
||||
}
|
||||
|
||||
return normalized;
|
||||
};
|
||||
|
||||
const sqliteConnection = (filenameEnv) => ({
|
||||
filename: resolveSqliteFilename(filenameEnv)
|
||||
@@ -28,7 +54,13 @@ const baseSqliteConfig = {
|
||||
const config = {
|
||||
development: {
|
||||
client: process.env.DATABASE_CLIENT || 'sqlite3',
|
||||
connection: process.env.DATABASE_CLIENT === 'pg' ? pgConnectionFromEnv() : {
|
||||
connection: process.env.DATABASE_CLIENT === 'pg' ? {
|
||||
host: process.env.DB_HOST || 'localhost',
|
||||
port: process.env.DB_PORT || 5432,
|
||||
user: process.env.DB_USER || 'postgres',
|
||||
password: process.env.DB_PASSWORD || 'postgres',
|
||||
database: process.env.DB_NAME || 'photo_sharing'
|
||||
} : {
|
||||
filename: resolveSqliteFilename(process.env.DATABASE_PATH || './data/photo_sharing.db')
|
||||
},
|
||||
useNullAsDefault: process.env.DATABASE_CLIENT !== 'pg',
|
||||
@@ -65,7 +97,12 @@ const config = {
|
||||
// Support both Postgres and SQLite in production based on DATABASE_CLIENT
|
||||
connection: (process.env.DATABASE_CLIENT || 'pg') === 'pg'
|
||||
? {
|
||||
...pgConnectionFromEnv(),
|
||||
host: process.env.DB_HOST || 'db',
|
||||
port: process.env.DB_PORT || 5432,
|
||||
user: process.env.DB_USER || 'picpeak',
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.DB_NAME || 'picpeak',
|
||||
ssl: process.env.DB_SSL === 'true' ? { rejectUnauthorized: false } : false,
|
||||
// Connection stability settings
|
||||
connectionTimeoutMillis: 30000,
|
||||
idleTimeoutMillis: 30000,
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
/**
|
||||
* Migration 158: per-event slideshow ordering + category filter (#202).
|
||||
*
|
||||
* - `show_order` — 'chronological' (default, upload order) | 'random'
|
||||
* (client-side shuffle). Lets the Live Slideshow play
|
||||
* photos in a varied order during an event.
|
||||
* - `show_category_id`— optional FK into `photo_categories`. When set, the
|
||||
* slideshow only shows photos in that category (NULL =
|
||||
* all visible photos, the existing behaviour).
|
||||
*
|
||||
* Both additive + guarded. Defaults preserve today's behaviour (chronological,
|
||||
* all photos), so existing slideshows are unchanged.
|
||||
*/
|
||||
exports.up = async function up(knex) {
|
||||
const hasOrder = await knex.schema.hasColumn('events', 'show_order');
|
||||
if (!hasOrder) {
|
||||
await knex.schema.alterTable('events', (t) => {
|
||||
t.string('show_order', 20).defaultTo('chronological');
|
||||
});
|
||||
}
|
||||
const hasCat = await knex.schema.hasColumn('events', 'show_category_id');
|
||||
if (!hasCat) {
|
||||
await knex.schema.alterTable('events', (t) => {
|
||||
t.integer('show_category_id').nullable();
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
exports.down = async function down(knex) {
|
||||
for (const col of ['show_order', 'show_category_id']) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
if (await knex.schema.hasColumn('events', col)) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
await knex.schema.alterTable('events', (t) => t.dropColumn(col));
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -1,57 +0,0 @@
|
||||
/**
|
||||
* Migration 159: per-event category ordering (#782).
|
||||
*
|
||||
* Adds a `display_order` integer to `photo_categories` so photographers can
|
||||
* arrange an event's categories in the flow of the day (Pre-Ceremony →
|
||||
* Ceremony → Reception …) instead of the hard-coded A–Z order. Mirrors the
|
||||
* `display_order` column + reorder pattern already used by `event_types`.
|
||||
*
|
||||
* Preserve existing galleries: backfill `display_order` from the CURRENT
|
||||
* (alphabetical) order, scoped — globals numbered together, event-specific
|
||||
* numbered per event — so nothing reshuffles on upgrade. A custom order is
|
||||
* opt-in via the admin reorder controls. See feedback: migrations should pin
|
||||
* previously-implicit defaults onto existing rows.
|
||||
*
|
||||
* Backfill runs in JS (not a SQL window function) to stay portable across
|
||||
* SQLite (dev) and Postgres (prod).
|
||||
*
|
||||
* Additive + hasColumn-guarded.
|
||||
*/
|
||||
async function addColumn(knex, table, column, builder) {
|
||||
if (!(await knex.schema.hasColumn(table, column))) {
|
||||
await knex.schema.alterTable(table, builder);
|
||||
}
|
||||
}
|
||||
|
||||
exports.up = async function (knex) {
|
||||
if (!(await knex.schema.hasTable('photo_categories'))) return;
|
||||
|
||||
await addColumn(knex, 'photo_categories', 'display_order', (t) => {
|
||||
t.integer('display_order').notNullable().defaultTo(0);
|
||||
t.index('display_order');
|
||||
});
|
||||
|
||||
// Backfill from the current alphabetical order, per scope, so existing
|
||||
// galleries render exactly as before until an admin reorders.
|
||||
const cats = await knex('photo_categories')
|
||||
.select('id', 'name', 'is_global', 'event_id')
|
||||
.orderBy('name', 'asc');
|
||||
|
||||
const counters = {};
|
||||
for (const c of cats) {
|
||||
const scope = c.is_global ? 'global' : `event:${c.event_id}`;
|
||||
counters[scope] = (counters[scope] || 0) + 1;
|
||||
await knex('photo_categories')
|
||||
.where('id', c.id)
|
||||
.update({ display_order: counters[scope] });
|
||||
}
|
||||
};
|
||||
|
||||
exports.down = async function (knex) {
|
||||
if (!(await knex.schema.hasTable('photo_categories'))) return;
|
||||
if (await knex.schema.hasColumn('photo_categories', 'display_order')) {
|
||||
await knex.schema.alterTable('photo_categories', (t) =>
|
||||
t.dropColumn('display_order')
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -1,46 +0,0 @@
|
||||
/**
|
||||
* Migration 160: per-event category order override (#782).
|
||||
*
|
||||
* Builds on migration 159 (photo_categories.display_order = the GLOBAL default
|
||||
* order) by adding a per-event OVERRIDE layer. Global categories are shared
|
||||
* across every event, so a single display_order can only express one order for
|
||||
* them. This table lets a single gallery arrange its categories — globals AND
|
||||
* event-specific, interleaved into the flow of the day — independently of the
|
||||
* global default.
|
||||
*
|
||||
* Resolution (see adminCategories / gallery):
|
||||
* 1. if the event has override rows -> use override.position;
|
||||
* 2. else fall back to photo_categories.display_order (the global default);
|
||||
* 3. else name.
|
||||
*
|
||||
* An event is either "using the default" (no rows here) or "customised" (a row
|
||||
* per category it shows). No backfill: every existing event starts on the
|
||||
* default order, so nothing reshuffles — a custom order is opt-in per event.
|
||||
*
|
||||
* Additive + hasTable-guarded.
|
||||
*/
|
||||
exports.up = async function (knex) {
|
||||
if (!(await knex.schema.hasTable('photo_categories'))) return;
|
||||
if (await knex.schema.hasTable('event_category_order')) return;
|
||||
|
||||
await knex.schema.createTable('event_category_order', (t) => {
|
||||
t.increments('id').primary();
|
||||
t.integer('event_id').notNullable()
|
||||
.references('id').inTable('events').onDelete('CASCADE');
|
||||
t.integer('category_id').notNullable()
|
||||
.references('id').inTable('photo_categories').onDelete('CASCADE');
|
||||
t.integer('position').notNullable().defaultTo(0);
|
||||
t.timestamp('created_at').defaultTo(knex.fn.now());
|
||||
|
||||
// At most one position per (event, category).
|
||||
t.unique(['event_id', 'category_id']);
|
||||
// Ordered reads are always scoped to one event.
|
||||
t.index(['event_id', 'position']);
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = async function (knex) {
|
||||
if (await knex.schema.hasTable('event_category_order')) {
|
||||
await knex.schema.dropTable('event_category_order');
|
||||
}
|
||||
};
|
||||
@@ -1,43 +0,0 @@
|
||||
/**
|
||||
* Migration 161: `setup_wizard_completed` app setting (#800).
|
||||
*
|
||||
* The setup wizard gains an event-types step that may rename or DELETE the
|
||||
* seeded system event types. That is only safe on a pristine install, so the
|
||||
* backend gates system-type deletion on this flag being unset (plus zero
|
||||
* usage — see eventTypeService.deleteEventType).
|
||||
*
|
||||
* Backfill rule: any install that already has an admin account predates the
|
||||
* wizard step (or already finished the wizard), so it is marked completed
|
||||
* here — the deletion window never opens on existing setups. A genuinely
|
||||
* fresh install runs this migration BEFORE its first admin is created, so
|
||||
* the flag starts false and the wizard's finish call flips it to true.
|
||||
*
|
||||
* Idempotent: skips when the key already exists. Values are JSON-stringified
|
||||
* to match getAppSetting's JSON.parse on read.
|
||||
*/
|
||||
exports.up = async function up(knex) {
|
||||
if (!(await knex.schema.hasTable('app_settings'))) return;
|
||||
|
||||
const existing = await knex('app_settings')
|
||||
.where({ setting_key: 'setup_wizard_completed' })
|
||||
.first();
|
||||
if (existing) return;
|
||||
|
||||
let hasAdmin = false;
|
||||
if (await knex.schema.hasTable('admin_users')) {
|
||||
const row = await knex('admin_users').count({ c: '*' }).first();
|
||||
hasAdmin = Number(row?.c || 0) > 0;
|
||||
}
|
||||
|
||||
await knex('app_settings').insert({
|
||||
setting_key: 'setup_wizard_completed',
|
||||
setting_value: JSON.stringify(hasAdmin),
|
||||
setting_type: 'boolean',
|
||||
updated_at: new Date(),
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = async function down(knex) {
|
||||
if (!(await knex.schema.hasTable('app_settings'))) return;
|
||||
await knex('app_settings').where({ setting_key: 'setup_wizard_completed' }).del();
|
||||
};
|
||||
@@ -1,51 +0,0 @@
|
||||
/**
|
||||
* Migration 162: OIDC identity binding for admin users (#798).
|
||||
*
|
||||
* - `auth_provider` — 'local' (default) or 'oidc'. Which authority owns the
|
||||
* account's credentials.
|
||||
* - `external_issuer` — the validated `iss` of the IdP that owns the subject.
|
||||
* OIDC only guarantees `sub` uniqueness WITHIN an
|
||||
* issuer, so bindings match on (iss, sub) — otherwise
|
||||
* switching `oidc_issuer_url` could map a new
|
||||
* provider's user onto an old provider's admin when
|
||||
* their subjects collide.
|
||||
* - `external_subject` — the IdP's stable subject identifier (OIDC `sub`).
|
||||
* SSO logins match on (external_issuer,
|
||||
* external_subject), NEVER on email alone —
|
||||
* email-matching is an account-takeover vector with
|
||||
* IdPs that don't verify addresses. Nullable: local
|
||||
* accounts have neither.
|
||||
*
|
||||
* Composite unique index so one IdP identity can't map to two admin rows.
|
||||
* Additive + guarded; existing rows keep working untouched ('local', NULL).
|
||||
*/
|
||||
exports.up = async function up(knex) {
|
||||
if (!(await knex.schema.hasColumn('admin_users', 'auth_provider'))) {
|
||||
await knex.schema.alterTable('admin_users', (t) => {
|
||||
t.string('auth_provider', 20).notNullable().defaultTo('local');
|
||||
});
|
||||
}
|
||||
if (!(await knex.schema.hasColumn('admin_users', 'external_issuer'))) {
|
||||
await knex.schema.alterTable('admin_users', (t) => {
|
||||
t.string('external_issuer', 512).nullable();
|
||||
});
|
||||
}
|
||||
if (!(await knex.schema.hasColumn('admin_users', 'external_subject'))) {
|
||||
await knex.schema.alterTable('admin_users', (t) => {
|
||||
t.string('external_subject', 255).nullable();
|
||||
t.unique(['external_issuer', 'external_subject'], {
|
||||
indexName: 'admin_users_issuer_subject_unique',
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
exports.down = async function down(knex) {
|
||||
for (const col of ['external_subject', 'external_issuer', 'auth_provider']) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
if (await knex.schema.hasColumn('admin_users', col)) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
await knex.schema.alterTable('admin_users', (t) => t.dropColumn(col));
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -1,22 +0,0 @@
|
||||
/**
|
||||
* #837 — per-event override for the live-slideshow QR overlay.
|
||||
* Mirrors show_watermark: NULL = inherit the global slideshow_qr_enabled
|
||||
* setting, true/false force the overlay on/off for this event.
|
||||
*/
|
||||
exports.up = async function up(knex) {
|
||||
const has = await knex.schema.hasColumn('events', 'show_qr');
|
||||
if (!has) {
|
||||
await knex.schema.alterTable('events', (t) => {
|
||||
t.boolean('show_qr').nullable().defaultTo(null);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
exports.down = async function down(knex) {
|
||||
const has = await knex.schema.hasColumn('events', 'show_qr');
|
||||
if (has) {
|
||||
await knex.schema.alterTable('events', (t) => {
|
||||
t.dropColumn('show_qr');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -1,55 +0,0 @@
|
||||
/**
|
||||
* Emoji reactions on photos (#839).
|
||||
*
|
||||
* - event_feedback_settings.allow_reactions: per-event toggle next to
|
||||
* allow_likes / allow_ratings / allow_comments. Defaults TRUE for parity
|
||||
* with the sibling toggles — the master feedback_enabled gate (default
|
||||
* false, opt-in per event) still decides whether any feedback UI shows.
|
||||
* - photo_feedback.reaction: the emoji value for feedback_type='reaction'
|
||||
* rows (validated against the fixed set in constants/reactions.js).
|
||||
* - photos.reaction_count: denormalized total, maintained by
|
||||
* updatePhotoFeedbackStats alongside like_count / favorite_count.
|
||||
*/
|
||||
|
||||
exports.up = async function (knex) {
|
||||
const hasAllowReactions = await knex.schema.hasColumn('event_feedback_settings', 'allow_reactions');
|
||||
if (!hasAllowReactions) {
|
||||
await knex.schema.alterTable('event_feedback_settings', (table) => {
|
||||
table.boolean('allow_reactions').defaultTo(true);
|
||||
});
|
||||
}
|
||||
|
||||
const hasReaction = await knex.schema.hasColumn('photo_feedback', 'reaction');
|
||||
if (!hasReaction) {
|
||||
await knex.schema.alterTable('photo_feedback', (table) => {
|
||||
// 16 chars: emoji are multi-byte/multi-codepoint (variation selectors),
|
||||
// but well under 16 characters each.
|
||||
table.string('reaction', 16);
|
||||
});
|
||||
}
|
||||
|
||||
const hasReactionCount = await knex.schema.hasColumn('photos', 'reaction_count');
|
||||
if (!hasReactionCount) {
|
||||
await knex.schema.alterTable('photos', (table) => {
|
||||
table.integer('reaction_count').defaultTo(0);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
exports.down = async function (knex) {
|
||||
if (await knex.schema.hasColumn('photos', 'reaction_count')) {
|
||||
await knex.schema.alterTable('photos', (table) => {
|
||||
table.dropColumn('reaction_count');
|
||||
});
|
||||
}
|
||||
if (await knex.schema.hasColumn('photo_feedback', 'reaction')) {
|
||||
await knex.schema.alterTable('photo_feedback', (table) => {
|
||||
table.dropColumn('reaction');
|
||||
});
|
||||
}
|
||||
if (await knex.schema.hasColumn('event_feedback_settings', 'allow_reactions')) {
|
||||
await knex.schema.alterTable('event_feedback_settings', (table) => {
|
||||
table.dropColumn('allow_reactions');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -1,44 +0,0 @@
|
||||
/**
|
||||
* Reveal mode (#838): hide the gallery from guests until a manual or
|
||||
* scheduled reveal — guests can still upload, the host/admin/slideshow see
|
||||
* everything.
|
||||
*
|
||||
* - events.reveal_mode: the per-event toggle (only meaningful together with
|
||||
* allow_user_uploads; off by default so nothing changes for existing events)
|
||||
* - events.reveal_at: optional scheduled reveal time. Effective visibility is
|
||||
* computed at REQUEST time (reveal_at <= now opens the gate even before the
|
||||
* scheduler runs), the minutely scheduler only stamps revealed_at durably.
|
||||
* - events.revealed_at: set by "Reveal now" or the scheduler; NULL while
|
||||
* hidden. Re-enabling reveal_mode clears it (re-hide).
|
||||
*/
|
||||
|
||||
// Each column guarded independently: a partially applied prior run (or a
|
||||
// fork that added one of them) must not leave the others missing — the
|
||||
// routes select all three.
|
||||
exports.up = async function (knex) {
|
||||
if (!(await knex.schema.hasColumn('events', 'reveal_mode'))) {
|
||||
await knex.schema.alterTable('events', (table) => {
|
||||
table.boolean('reveal_mode').defaultTo(false);
|
||||
});
|
||||
}
|
||||
if (!(await knex.schema.hasColumn('events', 'reveal_at'))) {
|
||||
await knex.schema.alterTable('events', (table) => {
|
||||
table.timestamp('reveal_at').nullable();
|
||||
});
|
||||
}
|
||||
if (!(await knex.schema.hasColumn('events', 'revealed_at'))) {
|
||||
await knex.schema.alterTable('events', (table) => {
|
||||
table.timestamp('revealed_at').nullable();
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
exports.down = async function (knex) {
|
||||
for (const column of ['revealed_at', 'reveal_at', 'reveal_mode']) {
|
||||
if (await knex.schema.hasColumn('events', column)) {
|
||||
await knex.schema.alterTable('events', (table) => {
|
||||
table.dropColumn(column);
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -1,21 +0,0 @@
|
||||
/**
|
||||
* Migration 166: per-event toggle to hide the branding logo on the
|
||||
* gallery password page (#894).
|
||||
*
|
||||
* NULL (the default) keeps today's behaviour — the global branding logo is
|
||||
* shown above the password form. Only an explicit `false` hides it for
|
||||
* that gallery; the admin login page and other surfaces are unaffected.
|
||||
*/
|
||||
exports.up = async function (knex) {
|
||||
if (await knex.schema.hasColumn('events', 'login_logo_visible')) return;
|
||||
await knex.schema.alterTable('events', (t) => {
|
||||
t.boolean('login_logo_visible').nullable();
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = async function (knex) {
|
||||
if (!(await knex.schema.hasColumn('events', 'login_logo_visible'))) return;
|
||||
await knex.schema.alterTable('events', (t) => {
|
||||
t.dropColumn('login_logo_visible');
|
||||
});
|
||||
};
|
||||
@@ -1,50 +0,0 @@
|
||||
/**
|
||||
* Migration 169: re-bill proof-attachment support (issue #866).
|
||||
*
|
||||
* - inbound_documents.proof_attach_error : best-effort failure marker. When a
|
||||
* re-billed supplier invoice's stored
|
||||
* proof PDF is missing/unreadable at
|
||||
* the moment the client invoice is
|
||||
* issued, we DON'T silently drop it —
|
||||
* we stamp the reason here so the
|
||||
* re-bill row in CRM → Customer shows
|
||||
* a recovery banner.
|
||||
* - customer_accounts.rebill_attach_proof: per-customer tri-state override for
|
||||
* "attach the supplier proof to the
|
||||
* client-invoice email".
|
||||
* NULL = inherit the global default
|
||||
* true = always attach
|
||||
* false = never attach
|
||||
* The global default itself lives in
|
||||
* app_settings (accounting_rebill_
|
||||
* attach_proof, default off) and needs
|
||||
* no seed row — an absent key coerces
|
||||
* to false, exactly like
|
||||
* accounting_require_proof.
|
||||
*
|
||||
* Additive + hasColumn-guarded so re-runs are safe.
|
||||
*/
|
||||
async function addColumn(knex, table, column, builder) {
|
||||
if (!(await knex.schema.hasColumn(table, column))) {
|
||||
await knex.schema.alterTable(table, builder);
|
||||
}
|
||||
}
|
||||
|
||||
exports.up = async function (knex) {
|
||||
if (await knex.schema.hasTable('inbound_documents')) {
|
||||
await addColumn(knex, 'inbound_documents', 'proof_attach_error', (t) => t.text('proof_attach_error'));
|
||||
}
|
||||
if (await knex.schema.hasTable('customer_accounts')) {
|
||||
// Nullable boolean = tri-state (NULL inherit / true on / false off).
|
||||
await addColumn(knex, 'customer_accounts', 'rebill_attach_proof', (t) => t.boolean('rebill_attach_proof').nullable());
|
||||
}
|
||||
};
|
||||
|
||||
exports.down = async function (knex) {
|
||||
if (await knex.schema.hasTable('inbound_documents') && await knex.schema.hasColumn('inbound_documents', 'proof_attach_error')) {
|
||||
await knex.schema.alterTable('inbound_documents', (t) => t.dropColumn('proof_attach_error'));
|
||||
}
|
||||
if (await knex.schema.hasTable('customer_accounts') && await knex.schema.hasColumn('customer_accounts', 'rebill_attach_proof')) {
|
||||
await knex.schema.alterTable('customer_accounts', (t) => t.dropColumn('rebill_attach_proof'));
|
||||
}
|
||||
};
|
||||
@@ -1,244 +0,0 @@
|
||||
/**
|
||||
* Migration 170: PicTransfer — cross-event file transfers (#997).
|
||||
*
|
||||
* Adds the tables that back the "send these files to someone" feature:
|
||||
*
|
||||
* transfers One share link. Bundles photos picked from ANY event,
|
||||
* protected by a 64-hex recipient token. Optionally opens
|
||||
* a 6-char upload token so the client can send files back
|
||||
* (logos etc.). Disabled after `expires_at`; files are
|
||||
* kept `grace_days` days past disable, then hard-deleted.
|
||||
* transfer_files Join rows: which photos are in a transfer (cross-event).
|
||||
* photo_id → photos CASCADE, so removing the underlying
|
||||
* photo just drops it from the transfer; the reverse
|
||||
* (deleting a transfer) never touches the source photos.
|
||||
* transfer_uploads Files the client uploaded through the upload token.
|
||||
* These have their own bytes on disk (uploads/transfers/…)
|
||||
* and are what the retention sweep deletes.
|
||||
* transfer_downloads Lightweight audit of recipient downloads (count + IP).
|
||||
*
|
||||
* Downloads always serve ORIGINAL files (never watermarked) — a transfer is a
|
||||
* deliberate "here are your files" hand-off. Reuses the same original-file
|
||||
* resolution + archiver streaming as the gallery download-all path.
|
||||
*/
|
||||
|
||||
exports.up = async function (knex) {
|
||||
if (!(await knex.schema.hasTable('transfers'))) {
|
||||
await knex.schema.createTable('transfers', (table) => {
|
||||
table.increments('id').primary();
|
||||
// Recipient download token — 64 hex chars = 32 bytes = 256 bits.
|
||||
table.string('token', 64).notNullable().unique();
|
||||
table.string('title', 255).notNullable().defaultTo('');
|
||||
table.text('message');
|
||||
table.integer('created_by').unsigned()
|
||||
.references('id').inTable('admin_users').onDelete('SET NULL');
|
||||
// Link is disabled once this passes (the "set time period" cap).
|
||||
table.timestamp('expires_at').notNullable();
|
||||
// Optional download cap. NULL or 0 = unlimited within the window.
|
||||
table.integer('max_downloads');
|
||||
table.integer('download_count').notNullable().defaultTo(0);
|
||||
table.boolean('is_active').notNullable().defaultTo(true);
|
||||
// When the link flipped inactive — starts the retention clock.
|
||||
table.timestamp('disabled_at');
|
||||
// Keep files this many days after disable, then hard-delete.
|
||||
table.integer('grace_days').notNullable().defaultTo(7);
|
||||
table.timestamp('admin_notified_at');
|
||||
table.timestamp('deleted_at');
|
||||
// Optional client-upload channel (6-char token).
|
||||
table.boolean('allow_uploads').notNullable().defaultTo(false);
|
||||
table.string('upload_token', 16).unique();
|
||||
table.timestamp('upload_expires_at');
|
||||
table.timestamp('created_at').defaultTo(knex.fn.now());
|
||||
table.timestamp('updated_at').defaultTo(knex.fn.now());
|
||||
table.index(['is_active', 'expires_at'], 'transfers_active_expiry_idx');
|
||||
table.index(['deleted_at'], 'transfers_deleted_idx');
|
||||
});
|
||||
}
|
||||
|
||||
if (!(await knex.schema.hasTable('transfer_files'))) {
|
||||
await knex.schema.createTable('transfer_files', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.integer('transfer_id').unsigned().notNullable()
|
||||
.references('id').inTable('transfers').onDelete('CASCADE');
|
||||
table.integer('photo_id').unsigned().notNullable()
|
||||
.references('id').inTable('photos').onDelete('CASCADE');
|
||||
table.integer('sort_order').notNullable().defaultTo(0);
|
||||
table.timestamp('created_at').defaultTo(knex.fn.now());
|
||||
table.index(['transfer_id'], 'transfer_files_transfer_idx');
|
||||
// A photo can only appear once per transfer.
|
||||
table.unique(['transfer_id', 'photo_id'], 'transfer_files_unique');
|
||||
});
|
||||
}
|
||||
|
||||
if (!(await knex.schema.hasTable('transfer_uploads'))) {
|
||||
await knex.schema.createTable('transfer_uploads', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.integer('transfer_id').unsigned().notNullable()
|
||||
.references('id').inTable('transfers').onDelete('CASCADE');
|
||||
table.string('original_filename', 512).notNullable();
|
||||
// Storage-relative key, e.g. uploads/transfers/{id}/{stored-name}.
|
||||
table.string('stored_path', 1024).notNullable();
|
||||
table.integer('size_bytes');
|
||||
table.string('mime_type', 100);
|
||||
table.string('uploader_ip', 45);
|
||||
table.timestamp('uploaded_at').defaultTo(knex.fn.now());
|
||||
table.index(['transfer_id'], 'transfer_uploads_transfer_idx');
|
||||
});
|
||||
}
|
||||
|
||||
if (!(await knex.schema.hasTable('transfer_downloads'))) {
|
||||
await knex.schema.createTable('transfer_downloads', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.integer('transfer_id').unsigned().notNullable()
|
||||
.references('id').inTable('transfers').onDelete('CASCADE');
|
||||
table.string('kind', 20).notNullable().defaultTo('all'); // 'all' | 'single'
|
||||
table.integer('photo_id').unsigned();
|
||||
table.string('ip', 45);
|
||||
table.timestamp('downloaded_at').defaultTo(knex.fn.now());
|
||||
table.index(['transfer_id'], 'transfer_downloads_transfer_idx');
|
||||
});
|
||||
}
|
||||
|
||||
// Defaults for the create-transfer form + retention/upload behaviour.
|
||||
const settings = [
|
||||
{ setting_key: 'transfer_default_expiry_days', setting_value: JSON.stringify(14), setting_type: 'number' },
|
||||
{ setting_key: 'transfer_default_grace_days', setting_value: JSON.stringify(7), setting_type: 'number' },
|
||||
{ setting_key: 'transfer_default_max_downloads', setting_value: JSON.stringify(0), setting_type: 'number' },
|
||||
{ setting_key: 'transfer_max_upload_size_mb', setting_value: JSON.stringify(50), setting_type: 'number' },
|
||||
{
|
||||
setting_key: 'transfer_upload_allowed_mime',
|
||||
setting_value: JSON.stringify([
|
||||
'image/jpeg', 'image/png', 'image/webp', 'image/gif',
|
||||
'image/tiff', 'application/pdf', 'application/zip',
|
||||
]),
|
||||
setting_type: 'general',
|
||||
},
|
||||
];
|
||||
for (const s of settings) {
|
||||
const exists = await knex('app_settings').where('setting_key', s.setting_key).first();
|
||||
if (!exists) {
|
||||
await knex('app_settings').insert({ ...s, updated_at: knex.fn.now() });
|
||||
}
|
||||
}
|
||||
|
||||
// Feature flag — PicTransfer is a strictly opt-in module like slideshow /
|
||||
// workflows: the sidebar entry, the /admin/transfers area and every
|
||||
// transfer route (admin + public) stay dark until an admin turns it on
|
||||
// under Settings → Features. Default OFF; idempotent seed.
|
||||
if (await knex.schema.hasTable('feature_flags')) {
|
||||
const existingFlag = await knex('feature_flags').where({ key: 'transfers' }).first();
|
||||
if (!existingFlag) {
|
||||
await knex('feature_flags').insert({ key: 'transfers', value: false });
|
||||
}
|
||||
}
|
||||
|
||||
// Admin notification when a transfer link expires (EN + DE, matching the
|
||||
// convention of the other admin-notification templates — see migration 087).
|
||||
const existingTemplate = await knex('email_templates')
|
||||
.where('template_key', 'transfer_link_expired')
|
||||
.first();
|
||||
if (!existingTemplate) {
|
||||
await knex('email_templates').insert({
|
||||
template_key: 'transfer_link_expired',
|
||||
subject_en: 'A transfer link has expired — {{transfer_title}}',
|
||||
subject_de: 'Ein Transfer-Link ist abgelaufen — {{transfer_title}}',
|
||||
body_html_en: `
|
||||
<h2>A transfer link has expired</h2>
|
||||
|
||||
<p>The following file transfer is no longer downloadable by its recipient:</p>
|
||||
|
||||
<div style="background-color: #f0f8ff; border-left: 4px solid #5C8762; padding: 20px; margin: 20px 0; border-radius: 4px;">
|
||||
<p style="margin: 0;"><strong>Transfer:</strong> {{transfer_title}}</p>
|
||||
<p style="margin: 10px 0 0 0;"><strong>Expired at:</strong> {{expiry_date}}</p>
|
||||
<p style="margin: 10px 0 0 0;"><strong>Files included:</strong> {{file_count}}</p>
|
||||
<p style="margin: 10px 0 0 0;"><strong>Client uploads received:</strong> {{upload_count}}</p>
|
||||
</div>
|
||||
|
||||
<p>The files will be kept for {{grace_days}} more days (until {{delete_date}})
|
||||
so you can re-share or retrieve anything you still need, then they are
|
||||
automatically deleted.</p>
|
||||
|
||||
<p><a href="{{admin_url}}">Open PicTransfer in the admin area</a></p>
|
||||
|
||||
<p>Best regards,<br>
|
||||
Your PicPeak Installation</p>`,
|
||||
body_text_en: `A transfer link has expired
|
||||
|
||||
The following file transfer is no longer downloadable by its recipient:
|
||||
|
||||
Transfer: {{transfer_title}}
|
||||
Expired at: {{expiry_date}}
|
||||
Files included: {{file_count}}
|
||||
Client uploads received: {{upload_count}}
|
||||
|
||||
The files will be kept for {{grace_days}} more days (until {{delete_date}}) so
|
||||
you can re-share or retrieve anything you still need, then they are
|
||||
automatically deleted.
|
||||
|
||||
Open PicTransfer in the admin area: {{admin_url}}
|
||||
|
||||
Best regards,
|
||||
Your PicPeak Installation`,
|
||||
body_html_de: `
|
||||
<h2>Ein Transfer-Link ist abgelaufen</h2>
|
||||
|
||||
<p>Der folgende Datei-Transfer kann vom Empfänger nicht mehr heruntergeladen werden:</p>
|
||||
|
||||
<div style="background-color: #f0f8ff; border-left: 4px solid #5C8762; padding: 20px; margin: 20px 0; border-radius: 4px;">
|
||||
<p style="margin: 0;"><strong>Transfer:</strong> {{transfer_title}}</p>
|
||||
<p style="margin: 10px 0 0 0;"><strong>Abgelaufen am:</strong> {{expiry_date}}</p>
|
||||
<p style="margin: 10px 0 0 0;"><strong>Enthaltene Dateien:</strong> {{file_count}}</p>
|
||||
<p style="margin: 10px 0 0 0;"><strong>Empfangene Kunden-Uploads:</strong> {{upload_count}}</p>
|
||||
</div>
|
||||
|
||||
<p>Die Dateien werden noch {{grace_days}} Tage aufbewahrt (bis {{delete_date}}),
|
||||
damit Sie alles Benötigte erneut teilen oder abrufen können; danach werden sie
|
||||
automatisch gelöscht.</p>
|
||||
|
||||
<p><a href="{{admin_url}}">PicTransfer im Admin-Bereich öffnen</a></p>
|
||||
|
||||
<p>Mit freundlichen Grüßen,<br>
|
||||
Ihre PicPeak-Installation</p>`,
|
||||
body_text_de: `Ein Transfer-Link ist abgelaufen
|
||||
|
||||
Der folgende Datei-Transfer kann vom Empfänger nicht mehr heruntergeladen werden:
|
||||
|
||||
Transfer: {{transfer_title}}
|
||||
Abgelaufen am: {{expiry_date}}
|
||||
Enthaltene Dateien: {{file_count}}
|
||||
Empfangene Kunden-Uploads: {{upload_count}}
|
||||
|
||||
Die Dateien werden noch {{grace_days}} Tage aufbewahrt (bis {{delete_date}}),
|
||||
danach werden sie automatisch gelöscht.
|
||||
|
||||
PicTransfer im Admin-Bereich öffnen: {{admin_url}}
|
||||
|
||||
Mit freundlichen Grüßen,
|
||||
Ihre PicPeak-Installation`,
|
||||
variables: JSON.stringify([
|
||||
'transfer_title', 'expiry_date', 'file_count', 'upload_count',
|
||||
'grace_days', 'delete_date', 'admin_url',
|
||||
]),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
exports.down = async function (knex) {
|
||||
if (await knex.schema.hasTable('feature_flags')) {
|
||||
await knex('feature_flags').where({ key: 'transfers' }).del();
|
||||
}
|
||||
await knex('email_templates').where('template_key', 'transfer_link_expired').del();
|
||||
await knex('app_settings')
|
||||
.whereIn('setting_key', [
|
||||
'transfer_default_expiry_days',
|
||||
'transfer_default_grace_days',
|
||||
'transfer_default_max_downloads',
|
||||
'transfer_max_upload_size_mb',
|
||||
'transfer_upload_allowed_mime',
|
||||
])
|
||||
.del();
|
||||
await knex.schema.dropTableIfExists('transfer_downloads');
|
||||
await knex.schema.dropTableIfExists('transfer_uploads');
|
||||
await knex.schema.dropTableIfExists('transfer_files');
|
||||
await knex.schema.dropTableIfExists('transfers');
|
||||
};
|
||||
@@ -1,157 +0,0 @@
|
||||
/**
|
||||
* Migration 171: PicTransfer — admin-uploaded deliverable files + email delivery
|
||||
* (follow-up to #997).
|
||||
*
|
||||
* 170 shipped the base feature; this adds two things the create flow now needs:
|
||||
*
|
||||
* transfer_extra_files Files the ADMIN uploads straight into a transfer at
|
||||
* creation (or later), stored as the transfer's own
|
||||
* bytes under `transfers/{id}/files/…`. Unlike
|
||||
* transfer_files (which reference gallery `photos`),
|
||||
* these have no event/photo — they are the operator's
|
||||
* own attachments and are part of the recipient's
|
||||
* download alongside the picked event photos. Deleted
|
||||
* with the transfer (retention sweep / hard delete).
|
||||
* transfer_recipients When a transfer is delivered by email, the recipient
|
||||
* address(es) it was sent to (audit + "sent to …" in the
|
||||
* detail panel). CASCADE with the transfer.
|
||||
*
|
||||
* Plus `transfers.delivery_method` ('link' | 'email', default 'link') and a
|
||||
* recipient-facing `transfer_ready` email template (EN/DE).
|
||||
*
|
||||
* 170 is already applied on existing installs, so this is a separate, additive
|
||||
* migration (Knex won't re-run 170). Fully guarded + idempotent.
|
||||
*/
|
||||
|
||||
exports.up = async function (knex) {
|
||||
if (!(await knex.schema.hasTable('transfer_extra_files'))) {
|
||||
await knex.schema.createTable('transfer_extra_files', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.integer('transfer_id').unsigned().notNullable()
|
||||
.references('id').inTable('transfers').onDelete('CASCADE');
|
||||
table.string('original_filename', 512).notNullable();
|
||||
// Storage-relative key, e.g. transfers/{id}/files/{stored-name}.
|
||||
table.string('stored_path', 1024).notNullable();
|
||||
table.integer('size_bytes');
|
||||
table.string('mime_type', 100);
|
||||
table.integer('sort_order').notNullable().defaultTo(0);
|
||||
table.timestamp('created_at').defaultTo(knex.fn.now());
|
||||
table.index(['transfer_id'], 'transfer_extra_files_transfer_idx');
|
||||
});
|
||||
}
|
||||
|
||||
if (!(await knex.schema.hasTable('transfer_recipients'))) {
|
||||
await knex.schema.createTable('transfer_recipients', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.integer('transfer_id').unsigned().notNullable()
|
||||
.references('id').inTable('transfers').onDelete('CASCADE');
|
||||
table.string('email', 320).notNullable();
|
||||
table.timestamp('created_at').defaultTo(knex.fn.now());
|
||||
table.timestamp('last_sent_at');
|
||||
table.index(['transfer_id'], 'transfer_recipients_transfer_idx');
|
||||
});
|
||||
}
|
||||
|
||||
const hasDeliveryMethod = await knex.schema.hasColumn('transfers', 'delivery_method');
|
||||
if (!hasDeliveryMethod) {
|
||||
await knex.schema.alterTable('transfers', (table) => {
|
||||
// 'link' (default — the operator copies/shares the link themselves) or
|
||||
// 'email' (PicPeak emailed the download link to transfer_recipients).
|
||||
table.string('delivery_method', 10).notNullable().defaultTo('link');
|
||||
});
|
||||
}
|
||||
|
||||
// Recipient-facing "your files are ready" email (EN + DE), sent when a
|
||||
// transfer is created with delivery_method='email'. Mirrors the convention
|
||||
// of the existing transfer_link_expired admin template (migration 170).
|
||||
const existingTemplate = await knex('email_templates')
|
||||
.where('template_key', 'transfer_ready')
|
||||
.first();
|
||||
if (!existingTemplate) {
|
||||
await knex('email_templates').insert({
|
||||
template_key: 'transfer_ready',
|
||||
subject_en: 'Your files are ready — {{transfer_title}}',
|
||||
subject_de: 'Ihre Dateien sind bereit — {{transfer_title}}',
|
||||
body_html_en: `
|
||||
<h2>Your files are ready</h2>
|
||||
|
||||
<p>{{transfer_title}} has been shared with you.</p>
|
||||
|
||||
<div style="background-color: #f0f8ff; border-left: 4px solid #5C8762; padding: 20px; margin: 20px 0; border-radius: 4px;">
|
||||
<p style="margin: 0;">{{message}}</p>
|
||||
</div>
|
||||
|
||||
<p style="margin: 24px 0;">
|
||||
<a href="{{download_url}}" class="button">Download your files</a>
|
||||
</p>
|
||||
|
||||
<p><strong>Files:</strong> {{file_count}}<br>
|
||||
<strong>Available until:</strong> {{expiry_date}}</p>
|
||||
|
||||
<p style="color: #888; font-size: 13px;">If the button doesn't work, copy this link into your browser:<br>{{download_url}}</p>
|
||||
|
||||
<p>Best regards,<br>
|
||||
Your PicPeak Installation</p>`,
|
||||
body_text_en: `Your files are ready
|
||||
|
||||
{{transfer_title}} has been shared with you.
|
||||
|
||||
{{message}}
|
||||
|
||||
Download your files: {{download_url}}
|
||||
|
||||
Files: {{file_count}}
|
||||
Available until: {{expiry_date}}
|
||||
|
||||
Best regards,
|
||||
Your PicPeak Installation`,
|
||||
body_html_de: `
|
||||
<h2>Ihre Dateien sind bereit</h2>
|
||||
|
||||
<p>{{transfer_title}} wurde mit Ihnen geteilt.</p>
|
||||
|
||||
<div style="background-color: #f0f8ff; border-left: 4px solid #5C8762; padding: 20px; margin: 20px 0; border-radius: 4px;">
|
||||
<p style="margin: 0;">{{message}}</p>
|
||||
</div>
|
||||
|
||||
<p style="margin: 24px 0;">
|
||||
<a href="{{download_url}}" class="button">Dateien herunterladen</a>
|
||||
</p>
|
||||
|
||||
<p><strong>Dateien:</strong> {{file_count}}<br>
|
||||
<strong>Verfügbar bis:</strong> {{expiry_date}}</p>
|
||||
|
||||
<p style="color: #888; font-size: 13px;">Falls die Schaltfläche nicht funktioniert, kopieren Sie diesen Link in Ihren Browser:<br>{{download_url}}</p>
|
||||
|
||||
<p>Mit freundlichen Grüßen,<br>
|
||||
Ihre PicPeak-Installation</p>`,
|
||||
body_text_de: `Ihre Dateien sind bereit
|
||||
|
||||
{{transfer_title}} wurde mit Ihnen geteilt.
|
||||
|
||||
{{message}}
|
||||
|
||||
Dateien herunterladen: {{download_url}}
|
||||
|
||||
Dateien: {{file_count}}
|
||||
Verfügbar bis: {{expiry_date}}
|
||||
|
||||
Mit freundlichen Grüßen,
|
||||
Ihre PicPeak-Installation`,
|
||||
variables: JSON.stringify([
|
||||
'transfer_title', 'message', 'download_url', 'file_count', 'expiry_date',
|
||||
]),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
exports.down = async function (knex) {
|
||||
await knex('email_templates').where('template_key', 'transfer_ready').del();
|
||||
if (await knex.schema.hasColumn('transfers', 'delivery_method')) {
|
||||
await knex.schema.alterTable('transfers', (table) => {
|
||||
table.dropColumn('delivery_method');
|
||||
});
|
||||
}
|
||||
await knex.schema.dropTableIfExists('transfer_recipients');
|
||||
await knex.schema.dropTableIfExists('transfer_extra_files');
|
||||
};
|
||||
@@ -1,109 +0,0 @@
|
||||
/**
|
||||
* Migration 172: reword the recipient `transfer_ready` email (follow-up to 171).
|
||||
*
|
||||
* Two fixes to the copy seeded in 171:
|
||||
* 1. Warmer, less robotic wording (greeting + natural phrasing + friendly
|
||||
* sign-off) instead of the terse "has been shared with you" notice.
|
||||
* 2. The message block is wrapped in `{{#if message}}` so a transfer sent
|
||||
* WITHOUT a personal note no longer renders an empty coloured box (the
|
||||
* "grey bar" some clients showed for the always-present empty <div>).
|
||||
*
|
||||
* This is a content UPDATE rather than an edit to 171 because 171 has already
|
||||
* been applied on existing installs — Knex won't re-run it, so the seeded row
|
||||
* would otherwise keep the old copy. UPDATE reaches both existing rows and
|
||||
* fresh installs (which run 171's insert first, then this).
|
||||
*/
|
||||
|
||||
const HTML_EN = `
|
||||
<h2>Your files are ready</h2>
|
||||
|
||||
<p>Hi,</p>
|
||||
|
||||
<p>{{transfer_title}} is ready for you — you can grab everything with a single click below.</p>
|
||||
|
||||
{{#if message}}
|
||||
<div style="background-color: #f6f6f4; border-left: 4px solid #5C8762; padding: 16px 20px; margin: 20px 0; border-radius: 4px; white-space: pre-line;">{{message}}</div>
|
||||
{{/if}}
|
||||
|
||||
<p style="margin: 28px 0;">
|
||||
<a href="{{download_url}}" class="button">Download your files</a>
|
||||
</p>
|
||||
|
||||
<p style="color: #555555;">The link stays active until {{expiry_date}} and includes {{file_count}} file(s).</p>
|
||||
|
||||
<p style="color: #999999; font-size: 13px;">Button not working? Just copy this link into your browser:<br>{{download_url}}</p>
|
||||
|
||||
<p>Enjoy your photos!</p>`;
|
||||
|
||||
const TEXT_EN = `Your files are ready
|
||||
|
||||
Hi,
|
||||
|
||||
{{transfer_title}} is ready for you — grab everything with the link below.
|
||||
{{#if message}}
|
||||
|
||||
{{message}}
|
||||
{{/if}}
|
||||
|
||||
Download your files:
|
||||
{{download_url}}
|
||||
|
||||
The link stays active until {{expiry_date}} and includes {{file_count}} file(s).
|
||||
|
||||
Enjoy your photos!`;
|
||||
|
||||
const HTML_DE = `
|
||||
<h2>Ihre Dateien sind bereit</h2>
|
||||
|
||||
<p>Hallo,</p>
|
||||
|
||||
<p>{{transfer_title}} ist für Sie bereit — mit einem Klick unten können Sie alles herunterladen.</p>
|
||||
|
||||
{{#if message}}
|
||||
<div style="background-color: #f6f6f4; border-left: 4px solid #5C8762; padding: 16px 20px; margin: 20px 0; border-radius: 4px; white-space: pre-line;">{{message}}</div>
|
||||
{{/if}}
|
||||
|
||||
<p style="margin: 28px 0;">
|
||||
<a href="{{download_url}}" class="button">Dateien herunterladen</a>
|
||||
</p>
|
||||
|
||||
<p style="color: #555555;">Der Link ist bis zum {{expiry_date}} gültig und enthält {{file_count}} Datei(en).</p>
|
||||
|
||||
<p style="color: #999999; font-size: 13px;">Funktioniert die Schaltfläche nicht? Kopieren Sie einfach diesen Link in Ihren Browser:<br>{{download_url}}</p>
|
||||
|
||||
<p>Viel Freude mit Ihren Fotos!</p>`;
|
||||
|
||||
const TEXT_DE = `Ihre Dateien sind bereit
|
||||
|
||||
Hallo,
|
||||
|
||||
{{transfer_title}} ist für Sie bereit — laden Sie alles über den Link unten herunter.
|
||||
{{#if message}}
|
||||
|
||||
{{message}}
|
||||
{{/if}}
|
||||
|
||||
Dateien herunterladen:
|
||||
{{download_url}}
|
||||
|
||||
Der Link ist bis zum {{expiry_date}} gültig und enthält {{file_count}} Datei(en).
|
||||
|
||||
Viel Freude mit Ihren Fotos!`;
|
||||
|
||||
exports.up = async function (knex) {
|
||||
if (!(await knex.schema.hasTable('email_templates'))) return;
|
||||
await knex('email_templates')
|
||||
.where('template_key', 'transfer_ready')
|
||||
.update({
|
||||
subject_en: '{{transfer_title}} — your files are ready to download',
|
||||
subject_de: '{{transfer_title}} — Ihre Dateien stehen bereit',
|
||||
body_html_en: HTML_EN,
|
||||
body_text_en: TEXT_EN,
|
||||
body_html_de: HTML_DE,
|
||||
body_text_de: TEXT_DE,
|
||||
});
|
||||
};
|
||||
|
||||
// Content-only refresh — nothing structural to reverse. The previous copy is
|
||||
// preserved in migration 171's insert for reference.
|
||||
exports.down = async function () {};
|
||||
@@ -1,137 +0,0 @@
|
||||
/**
|
||||
* Migration 173: Download resolutions (#858).
|
||||
*
|
||||
* Two related capabilities:
|
||||
*
|
||||
* 1. STANDARD resolution — the size a gallery hands out for every ordinary
|
||||
* download (single photo, selected, download-all). Global default in
|
||||
* app_settings, overridable per event. 'original' keeps today's behaviour,
|
||||
* so existing installs are unaffected until an admin changes it.
|
||||
*
|
||||
* 2. Resolution PICKER — an opt-in modal letting guests choose a different
|
||||
* size. Off by default. Custom-resolution archives are never cached: they
|
||||
* run through `download_jobs` (build → poll → download) so a large gallery
|
||||
* doesn't hold an HTTP connection open for minutes.
|
||||
*
|
||||
* Per-event columns are NULLABLE on purpose: NULL = inherit the global, matching
|
||||
* the tri-state `show_watermark` / `show_qr` convention. The cached download-all
|
||||
* zip is built AT the standard resolution, so changing either the global or an
|
||||
* event override has to invalidate `events.download_zip_path` — the settings
|
||||
* write paths do that, not this migration.
|
||||
*/
|
||||
|
||||
const PRESET_DEFAULTS = [
|
||||
{ label: 'Large', width: 3000, height: 2000 },
|
||||
{ label: 'Medium', width: 1500, height: 1000 },
|
||||
{ label: 'Small', width: 800, height: 600 },
|
||||
];
|
||||
|
||||
const GLOBAL_DEFAULTS = [
|
||||
// 'original' | '<width>x<height>' matching one of download_resolutions.
|
||||
['download_standard_resolution', 'original'],
|
||||
// Master switch for the guest-facing picker.
|
||||
['download_resolution_picker_enabled', false],
|
||||
// Whether 'Original' appears in the picker. Only consulted when the picker
|
||||
// is on — a photographer who lowers the standard usually does NOT want
|
||||
// guests helping themselves to full-res.
|
||||
['download_allow_original', false],
|
||||
['download_resolutions', PRESET_DEFAULTS],
|
||||
];
|
||||
|
||||
exports.up = async function (knex) {
|
||||
if (await knex.schema.hasTable('events')) {
|
||||
const cols = [
|
||||
['download_standard_resolution', (t) => t.string('download_standard_resolution', 32)],
|
||||
['download_resolution_picker_enabled', (t) => t.boolean('download_resolution_picker_enabled')],
|
||||
['download_allow_original', (t) => t.boolean('download_allow_original')],
|
||||
];
|
||||
for (const [name, add] of cols) {
|
||||
if (!(await knex.schema.hasColumn('events', name))) {
|
||||
await knex.schema.alterTable('events', add);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!(await knex.schema.hasTable('download_jobs'))) {
|
||||
await knex.schema.createTable('download_jobs', (table) => {
|
||||
table.increments('id').primary();
|
||||
// 64 hex chars = 32 bytes. Unguessable, but never sufficient on its own —
|
||||
// the download route still runs the gallery access middleware and matches
|
||||
// the job's event_id.
|
||||
table.string('token', 64).notNullable().unique();
|
||||
table.integer('event_id').unsigned().notNullable()
|
||||
.references('id').inTable('events').onDelete('CASCADE');
|
||||
// 'original' or '<width>x<height>'.
|
||||
table.string('resolution', 32).notNullable();
|
||||
// NULL = the whole visible gallery; otherwise the selected photo ids.
|
||||
// Stored as JSON text so both SQLite and PG round-trip it identically.
|
||||
table.text('photo_ids');
|
||||
// The subset that actually made it into the archive (a missing source is
|
||||
// skipped). Drives download counts; photo_ids stays the REQUESTED set so
|
||||
// the delivery fingerprint still matches.
|
||||
table.text('delivered_photo_ids');
|
||||
// Stable hash of (resolution, visibility scope, resolved photo id set,
|
||||
// watermark flag) — lets a second requester join an in-flight build
|
||||
// instead of duplicating it. The scope is part of the hash so a client
|
||||
// archive containing hidden photos can never be handed to a guest.
|
||||
table.string('dedup_key', 64).notNullable();
|
||||
// 'public' | 'hidden' — recorded alongside the hash so delivery can
|
||||
// re-check the requester still belongs to the scope the archive was
|
||||
// built for.
|
||||
table.string('visibility_scope', 16).notNullable().defaultTo('public');
|
||||
// pending | building | ready | failed
|
||||
table.string('status', 16).notNullable().defaultTo('pending');
|
||||
table.string('zip_path', 512);
|
||||
table.bigInteger('size_bytes');
|
||||
table.integer('photo_count');
|
||||
table.text('error');
|
||||
// Lease heartbeat: a live worker stamps this while building. Recovery
|
||||
// only fails rows whose heartbeat has gone stale, so a rolling restart
|
||||
// can't kill jobs another replica is still working on.
|
||||
table.timestamp('heartbeat_at');
|
||||
table.timestamp('created_at').defaultTo(knex.fn.now());
|
||||
table.timestamp('completed_at');
|
||||
// Swept by downloadJobCleanupService once this passes.
|
||||
table.timestamp('expires_at').notNullable();
|
||||
table.index(['event_id', 'dedup_key', 'status'], 'download_jobs_dedup_idx');
|
||||
table.index(['expires_at'], 'download_jobs_expiry_idx');
|
||||
});
|
||||
}
|
||||
|
||||
if (!(await knex.schema.hasTable('app_settings'))) return;
|
||||
for (const [key, value] of GLOBAL_DEFAULTS) {
|
||||
const existing = await knex('app_settings').where('setting_key', key).first();
|
||||
if (!existing) {
|
||||
await knex('app_settings').insert({
|
||||
setting_key: key,
|
||||
// JSON-stringified so SQLite (TEXT) and Postgres (JSONB) both
|
||||
// round-trip a recognisable shape — same as migration 104.
|
||||
setting_value: JSON.stringify(value),
|
||||
setting_type: 'download',
|
||||
updated_at: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
exports.down = async function (knex) {
|
||||
await knex.schema.dropTableIfExists('download_jobs');
|
||||
|
||||
if (await knex.schema.hasTable('app_settings')) {
|
||||
await knex('app_settings')
|
||||
.whereIn('setting_key', GLOBAL_DEFAULTS.map(([k]) => k))
|
||||
.del();
|
||||
}
|
||||
|
||||
if (await knex.schema.hasTable('events')) {
|
||||
for (const name of [
|
||||
'download_standard_resolution',
|
||||
'download_resolution_picker_enabled',
|
||||
'download_allow_original',
|
||||
]) {
|
||||
if (await knex.schema.hasColumn('events', name)) {
|
||||
await knex.schema.alterTable('events', (table) => table.dropColumn(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -1,42 +0,0 @@
|
||||
/**
|
||||
* Migration 174: make events.event_date / events.expires_at nullable on SQLite (#1029).
|
||||
*
|
||||
* Migration 061 introduced the `event_require_event_date` /
|
||||
* `event_require_expiration` settings and dropped the NOT NULL on both columns
|
||||
* — but only for Postgres. It skipped SQLite on the premise that "SQLite
|
||||
* doesn't enforce NOT NULL as strictly", which is simply untrue: clearing the
|
||||
* expiration on a SQLite install fails with
|
||||
*
|
||||
* SQLITE_CONSTRAINT: NOT NULL constraint failed: events.expires_at
|
||||
*
|
||||
* so "never expires" has never been reachable there. This finishes 061 for
|
||||
* SQLite. Knex implements .alter() on SQLite by recreating the table; migration
|
||||
* 073 already does exactly that on `events`, so the path is well-trodden here.
|
||||
*
|
||||
* Postgres is skipped — 061 already handled it, and knex's .alter() rewrites
|
||||
* the whole column definition (type, default, nullability), which would be a
|
||||
* needless rewrite of a column that is already correct.
|
||||
*/
|
||||
|
||||
function isSqlite(knex) {
|
||||
const client = knex.client.config.client;
|
||||
return client === 'sqlite3' || client === 'better-sqlite3';
|
||||
}
|
||||
|
||||
exports.up = async function(knex) {
|
||||
if (!isSqlite(knex)) return;
|
||||
|
||||
const hasEvents = await knex.schema.hasTable('events');
|
||||
if (!hasEvents) return;
|
||||
|
||||
await knex.schema.alterTable('events', (table) => {
|
||||
table.datetime('event_date').nullable().alter();
|
||||
table.datetime('expires_at').nullable().alter();
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
// Deliberately irreversible. Restoring NOT NULL would fail on any install
|
||||
// that has since created a gallery without an expiration — exactly what this
|
||||
// migration enables — and 061's down() takes the same position for Postgres.
|
||||
};
|
||||
@@ -1,256 +0,0 @@
|
||||
/**
|
||||
* Migration: Granular permissions + role presets
|
||||
*
|
||||
* Phase 1 of the multi-photographer epic (issues #743/#747): make every feature
|
||||
* permission-gateable so multi-user studios can split capability across roles.
|
||||
*
|
||||
* This migration ONLY defines the permission catalog + seeds grants/presets. The
|
||||
* route-level enforcement (pointing endpoints at the new perms) lives in the
|
||||
* route files. Splitting the perms here is inert until a route references them.
|
||||
*
|
||||
* What it does:
|
||||
* 1. Split the catch-all `settings.edit` into dedicated DANGEROUS-config perms
|
||||
* (banking / domains / security / integrations / features) so a team member
|
||||
* can be granted day-to-day settings without the ability to break IBAN,
|
||||
* domains, SSO, webhooks or feature toggles. Grants project forward from
|
||||
* every role that holds `settings.edit` today — nobody loses capability on
|
||||
* upgrade (see feedback_permission_split_compat). Today `settings.edit` is
|
||||
* super_admin-only, so in practice only super_admin gains the split perms.
|
||||
* 2. Add dedicated view/manage perms for feature areas that previously borrowed
|
||||
* generic perms (calendar, deals, transfers, whatsapp, tax report, vat codes,
|
||||
* event types, short urls, css templates, image security, notifications,
|
||||
* system) so each can be carved into a custom role independently.
|
||||
* 3. Grant every new perm to `super_admin` (the tracks-all owner). The boot
|
||||
* self-heal (_permissionsBoot.js) keeps super_admin complete on every future
|
||||
* release, so a new perm never needs a compensation migration.
|
||||
* 4. Seed the `solo_photographer` preset role — a full operator (studio owner)
|
||||
* granted every current permission. It is a frozen preset: future-release
|
||||
* perms are NOT auto-added (only super_admin tracks all); the owner grants
|
||||
* them via the role editor if wanted.
|
||||
*
|
||||
* Idempotent throughout (existing-name / existing-grant checks) so a re-run or a
|
||||
* partially-applied state is safe.
|
||||
*/
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// New DANGEROUS-config permissions split out of `settings.edit`.
|
||||
// `settings.edit` is retained as the SAFE everyday bucket (branding text,
|
||||
// general prefs, display formats, SEO/analytics copy, public-site content).
|
||||
// ---------------------------------------------------------------------------
|
||||
const SETTINGS_SPLIT_PERMISSIONS = [
|
||||
{ name: 'settings.banking', display_name: 'Manage Banking & Payment Config', category: 'settings', description: 'Edit bank accounts / IBAN, QR-bill, the issuer block and VAT/accounting config. Sensitive — governs where money is collected.' },
|
||||
{ name: 'settings.domains', display_name: 'Manage Domain & URL Config', category: 'settings', description: 'Edit the public base URL / domain settings used in links and emails.' },
|
||||
{ name: 'settings.security', display_name: 'Manage Security & SSO Config', category: 'settings', description: 'Edit security policy, rate limits and single sign-on (OIDC) login settings.' },
|
||||
{ name: 'settings.integrations', display_name: 'Manage Integrations', category: 'settings', description: 'Manage outbound webhooks and API tokens.' },
|
||||
{ name: 'settings.features', display_name: 'Manage Feature Toggles', category: 'settings', description: 'Enable or disable application features (feature flags).' },
|
||||
];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Dedicated per-feature permissions. view = day-to-day read, manage = configure.
|
||||
// ---------------------------------------------------------------------------
|
||||
// Dedicated perms for admin surfaces that were miscategorised under the generic
|
||||
// `settings.*` bucket. Their writes were super_admin-only (settings.edit), so
|
||||
// pointing them here doesn't strip any existing role. Areas that already have a
|
||||
// sensible domain gate (calendar→customers, deals→customers/bills,
|
||||
// transfers→events, tax report→bills, short URLs→events, css templates→branding)
|
||||
// are intentionally left on those gates for now — finer carving there ships with
|
||||
// the phase-2 photographer role (needs forward-projection to stay compat-safe).
|
||||
const FEATURE_PERMISSIONS = [
|
||||
{ name: 'whatsapp.view', display_name: 'View WhatsApp', category: 'whatsapp', description: 'View WhatsApp messaging status and config.' },
|
||||
{ name: 'whatsapp.manage', display_name: 'Manage WhatsApp', category: 'whatsapp', description: 'Configure and send via WhatsApp.' },
|
||||
|
||||
{ name: 'roles.manage', display_name: 'Manage Roles', category: 'users', description: 'Create, edit and delete roles and their permission sets. Highly privileged — a holder can grant any capability, so keep it to owners.' },
|
||||
|
||||
{ name: 'vat_codes.view', display_name: 'View VAT Codes', category: 'accounting', description: 'Read the VAT-code list (used by document editors).' },
|
||||
|
||||
{ name: 'event_types.view', display_name: 'View Event Types', category: 'events', description: 'Read the event-type list (used when creating events).' },
|
||||
{ name: 'event_types.manage', display_name: 'Manage Event Types', category: 'events', description: 'Create, edit and delete event types.' },
|
||||
|
||||
{ name: 'image_security.view', display_name: 'View Image Security', category: 'photos', description: 'View image-protection / watermarking settings and access logs.' },
|
||||
{ name: 'image_security.manage',display_name: 'Manage Image Security', category: 'photos', description: 'Configure image protection, block IPs and clear access logs.' },
|
||||
|
||||
{ name: 'notifications.view', display_name: 'View Notifications', category: 'system', description: 'View admin notifications.' },
|
||||
{ name: 'notifications.manage', display_name: 'Manage Notifications', category: 'system', description: 'Mark read and clear admin notifications.' },
|
||||
|
||||
{ name: 'system.view', display_name: 'View System', category: 'system', description: 'View system status, version, updates and health.' },
|
||||
{ name: 'system.manage', display_name: 'Manage System', category: 'system', description: 'Configure update notifications and run system maintenance actions.' },
|
||||
];
|
||||
|
||||
const ALL_NEW_PERMISSIONS = [...SETTINGS_SPLIT_PERMISSIONS, ...FEATURE_PERMISSIONS];
|
||||
|
||||
// Preset roles shipped by the app. `permissions: 'ALL'` = every current perm.
|
||||
// Both are frozen system roles: future-release perms are NOT auto-added (only
|
||||
// super_admin tracks all); the owner tweaks them via the role editor.
|
||||
const SOLO_PHOTOGRAPHER = {
|
||||
name: 'solo_photographer',
|
||||
display_name: 'Solo Photographer',
|
||||
description: 'Full operator for a one-person studio — everything needed to run the business (galleries, uploads, CRM, invoices, banking, settings and team management). A preset starting point; new-release permissions are not auto-added (only Super Admin tracks all).',
|
||||
is_system: true,
|
||||
priority: 90, // between super_admin (100) and admin (80)
|
||||
permissions: 'ALL',
|
||||
};
|
||||
|
||||
// Team Photographer — a second/festival shooter who contributes photos but is
|
||||
// NOT the customer contact: view events + upload/edit/download photos, plus
|
||||
// read-only CRM context (customers/quotes/invoices). No settings, users,
|
||||
// billing edits, or events.edit (so no transfers/projects/guests either). The
|
||||
// "only their assigned events" scoping is phase 2 (#743 event assignment).
|
||||
const TEAM_PHOTOGRAPHER = {
|
||||
name: 'team_photographer',
|
||||
display_name: 'Team Photographer',
|
||||
description: 'Contributing photographer (second/festival shooter) — view events, upload and manage photos, and see read-only client context. Not the customer contact: no settings, user management, billing edits or event configuration. A preset starting point.',
|
||||
is_system: true,
|
||||
priority: 40, // between editor (50) and viewer (20)
|
||||
permissions: [
|
||||
'events.view',
|
||||
'photos.view', 'photos.upload', 'photos.edit', 'photos.download',
|
||||
'customers.view', 'quotes.view', 'bills.view',
|
||||
],
|
||||
};
|
||||
|
||||
const PRESET_ROLES = [SOLO_PHOTOGRAPHER, TEAM_PHOTOGRAPHER];
|
||||
|
||||
exports.up = async function (knex) {
|
||||
const hasPermissions = await knex.schema.hasTable('permissions');
|
||||
const hasRolePermissions = await knex.schema.hasTable('role_permissions');
|
||||
const hasRoles = await knex.schema.hasTable('roles');
|
||||
if (!hasPermissions || !hasRolePermissions || !hasRoles) {
|
||||
console.log('175: RBAC tables missing, skipping permission seed');
|
||||
return;
|
||||
}
|
||||
|
||||
// 1. Insert all new permissions (skip any already present).
|
||||
{
|
||||
const existing = await knex('permissions')
|
||||
.whereIn('name', ALL_NEW_PERMISSIONS.map((p) => p.name))
|
||||
.select('name');
|
||||
const existingSet = new Set(existing.map((r) => r.name));
|
||||
const toInsert = ALL_NEW_PERMISSIONS.filter((p) => !existingSet.has(p.name));
|
||||
if (toInsert.length > 0) {
|
||||
await knex('permissions').insert(toInsert);
|
||||
console.log(`175: inserted ${toInsert.length} new permissions`);
|
||||
}
|
||||
}
|
||||
|
||||
// Helper: insert (role_id, permission_id) grants without duplicates.
|
||||
const grantPerms = async (roleId, permIds) => {
|
||||
if (!roleId || permIds.length === 0) return;
|
||||
const existing = await knex('role_permissions')
|
||||
.where({ role_id: roleId })
|
||||
.whereIn('permission_id', permIds)
|
||||
.select('permission_id');
|
||||
const have = new Set(existing.map((r) => r.permission_id));
|
||||
const inserts = permIds
|
||||
.filter((id) => !have.has(id))
|
||||
.map((id) => ({ role_id: roleId, permission_id: id }));
|
||||
if (inserts.length > 0) {
|
||||
const batchSize = 50;
|
||||
for (let i = 0; i < inserts.length; i += batchSize) {
|
||||
await knex('role_permissions').insert(inserts.slice(i, i + batchSize));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 2. Project every perm that REPLACED a settings.edit gate forward: every role
|
||||
// holding settings.edit today gets each of them, so nobody loses capability
|
||||
// on upgrade (compat). This covers both the settings.* split AND the feature
|
||||
// .manage perms that took over settings.edit WRITE gates (whatsapp,
|
||||
// event_types, image_security, notifications, system) — projecting both
|
||||
// lists keeps the pattern symmetric for future phase-2 settings.edit holders.
|
||||
{
|
||||
const SETTINGS_EDIT_REPLACEMENTS = [
|
||||
...SETTINGS_SPLIT_PERMISSIONS.map((p) => p.name),
|
||||
'whatsapp.manage', 'event_types.manage', 'image_security.manage',
|
||||
'notifications.manage', 'system.manage',
|
||||
];
|
||||
const editPerm = await knex('permissions').where({ name: 'settings.edit' }).first();
|
||||
const replacementPerms = await knex('permissions')
|
||||
.whereIn('name', SETTINGS_EDIT_REPLACEMENTS)
|
||||
.select('id');
|
||||
const replacementIds = replacementPerms.map((p) => p.id);
|
||||
if (editPerm && replacementIds.length > 0) {
|
||||
const rolesWithEdit = await knex('role_permissions')
|
||||
.where({ permission_id: editPerm.id })
|
||||
.select('role_id');
|
||||
for (const { role_id } of rolesWithEdit) {
|
||||
await grantPerms(role_id, replacementIds);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Grant EVERY new permission to super_admin (the tracks-all owner).
|
||||
{
|
||||
const superAdmin = await knex('roles').where({ name: 'super_admin' }).first();
|
||||
if (superAdmin) {
|
||||
const newPerms = await knex('permissions')
|
||||
.whereIn('name', ALL_NEW_PERMISSIONS.map((p) => p.name))
|
||||
.select('id');
|
||||
await grantPerms(superAdmin.id, newPerms.map((p) => p.id));
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Seed the preset roles (Solo + Team Photographer). Each is created with
|
||||
// its grant set ONLY when missing; an existing preset is left untouched
|
||||
// (frozen — the owner may have customised it).
|
||||
for (const preset of PRESET_ROLES) {
|
||||
const existing = await knex('roles').where({ name: preset.name }).first();
|
||||
if (existing) continue;
|
||||
await knex('roles').insert({
|
||||
name: preset.name,
|
||||
display_name: preset.display_name,
|
||||
description: preset.description,
|
||||
is_system: preset.is_system,
|
||||
priority: preset.priority,
|
||||
created_at: knex.fn.now(),
|
||||
updated_at: knex.fn.now(),
|
||||
});
|
||||
const role = await knex('roles').where({ name: preset.name }).first();
|
||||
let permIds;
|
||||
if (preset.permissions === 'ALL') {
|
||||
permIds = (await knex('permissions').select('id')).map((p) => p.id);
|
||||
} else {
|
||||
const rows = await knex('permissions').whereIn('name', preset.permissions).select('id');
|
||||
permIds = rows.map((p) => p.id);
|
||||
}
|
||||
await grantPerms(role.id, permIds);
|
||||
console.log(`175: seeded ${preset.name} preset (${permIds.length} permissions)`);
|
||||
}
|
||||
|
||||
console.log('175: granular permissions + presets migration complete');
|
||||
};
|
||||
|
||||
exports.down = async function (knex) {
|
||||
const hasPermissions = await knex.schema.hasTable('permissions');
|
||||
if (!hasPermissions) return;
|
||||
|
||||
const hasRolePermissions = await knex.schema.hasTable('role_permissions');
|
||||
const names = ALL_NEW_PERMISSIONS.map((p) => p.name);
|
||||
const perms = await knex('permissions').whereIn('name', names).select('id');
|
||||
const ids = perms.map((p) => p.id);
|
||||
if (ids.length > 0) {
|
||||
if (hasRolePermissions) await knex('role_permissions').whereIn('permission_id', ids).del();
|
||||
await knex('permissions').whereIn('id', ids).del();
|
||||
}
|
||||
|
||||
// Remove the preset roles and their grants (each table guarded — the earlier
|
||||
// hasTable('permissions') check does not imply roles/admin_users exist).
|
||||
const hasRoles = await knex.schema.hasTable('roles');
|
||||
if (hasRoles) {
|
||||
const hasAdminUsers = await knex.schema.hasTable('admin_users');
|
||||
for (const preset of PRESET_ROLES) {
|
||||
const role = await knex('roles').where({ name: preset.name }).first();
|
||||
if (role) {
|
||||
if (hasRolePermissions) await knex('role_permissions').where({ role_id: role.id }).del();
|
||||
if (hasAdminUsers) await knex('admin_users').where({ role_id: role.id }).update({ role_id: null });
|
||||
await knex('roles').where({ id: role.id }).del();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports.ALL_NEW_PERMISSIONS = ALL_NEW_PERMISSIONS;
|
||||
module.exports.SETTINGS_SPLIT_PERMISSIONS = SETTINGS_SPLIT_PERMISSIONS;
|
||||
module.exports.FEATURE_PERMISSIONS = FEATURE_PERMISSIONS;
|
||||
module.exports.SOLO_PHOTOGRAPHER = SOLO_PHOTOGRAPHER;
|
||||
module.exports.TEAM_PHOTOGRAPHER = TEAM_PHOTOGRAPHER;
|
||||
module.exports.PRESET_ROLES = PRESET_ROLES;
|
||||
@@ -1,78 +0,0 @@
|
||||
/**
|
||||
* Migration: gallery info banner (#932)
|
||||
*
|
||||
* A short informational message rendered ABOVE the photo grid, so guests see
|
||||
* it on load. Distinct from the promotional banner (#440), which sits by the
|
||||
* footer and stays there for marketing/CTA copy — the reporter's case is an
|
||||
* onboarding hint ("use the menu button to filter"), which is useless below a
|
||||
* gallery the guest has to scroll past first.
|
||||
*
|
||||
* Deliberately mirrors the promo columns rather than inventing a second
|
||||
* shape: a global default in branding settings plus a per-event
|
||||
* inherit/custom/off override. Same semantics, same normalisation, so the
|
||||
* two banners stay predictable next to each other.
|
||||
*
|
||||
* Idempotent (hasColumn / existing-key guarded) so a re-run or a
|
||||
* partially-applied state is safe.
|
||||
*/
|
||||
|
||||
exports.up = async function (knex) {
|
||||
// 1. events.info_mode — 'inherit' (use the global default) | 'custom'
|
||||
// (this event's own copy) | 'off' (no banner for this gallery).
|
||||
const hasInfoMode = await knex.schema.hasColumn('events', 'info_mode');
|
||||
if (!hasInfoMode) {
|
||||
await knex.schema.alterTable('events', (table) => {
|
||||
table.string('info_mode', 16).notNullable().defaultTo('inherit');
|
||||
});
|
||||
console.log(' added events.info_mode (default "inherit")');
|
||||
} else {
|
||||
console.log(' events.info_mode already exists, skipping');
|
||||
}
|
||||
|
||||
// 2. events.info_markdown — per-event copy, only read when mode = custom.
|
||||
const hasInfoMarkdown = await knex.schema.hasColumn('events', 'info_markdown');
|
||||
if (!hasInfoMarkdown) {
|
||||
await knex.schema.alterTable('events', (table) => {
|
||||
table.text('info_markdown').nullable();
|
||||
});
|
||||
console.log(' added events.info_markdown (nullable text)');
|
||||
} else {
|
||||
console.log(' events.info_markdown already exists, skipping');
|
||||
}
|
||||
|
||||
// 3. The global default, following the existing `branding_<name>`
|
||||
// convention used by the promo rows this mirrors. Empty string = the
|
||||
// banner is off everywhere until an admin fills it in, so upgrading
|
||||
// changes nothing visible for existing installs.
|
||||
const infoSetting = {
|
||||
setting_key: 'branding_info_markdown',
|
||||
setting_value: JSON.stringify(''),
|
||||
setting_type: 'branding',
|
||||
};
|
||||
const exists = await knex('app_settings').where('setting_key', infoSetting.setting_key).first();
|
||||
if (!exists) {
|
||||
await knex('app_settings').insert({ ...infoSetting, updated_at: knex.fn.now() });
|
||||
console.log(' added branding_info_markdown (empty = banner off)');
|
||||
} else {
|
||||
console.log(' branding_info_markdown already exists, skipping');
|
||||
}
|
||||
|
||||
console.log('Migration 176_gallery_info_banner completed');
|
||||
};
|
||||
|
||||
exports.down = async function (knex) {
|
||||
console.log('Rollback: 176_gallery_info_banner');
|
||||
|
||||
if (await knex.schema.hasTable('events')) {
|
||||
if (await knex.schema.hasColumn('events', 'info_markdown')) {
|
||||
await knex.schema.alterTable('events', (table) => table.dropColumn('info_markdown'));
|
||||
}
|
||||
if (await knex.schema.hasColumn('events', 'info_mode')) {
|
||||
await knex.schema.alterTable('events', (table) => table.dropColumn('info_mode'));
|
||||
}
|
||||
}
|
||||
|
||||
if (await knex.schema.hasTable('app_settings')) {
|
||||
await knex('app_settings').where('setting_key', 'branding_info_markdown').del();
|
||||
}
|
||||
};
|
||||
@@ -276,51 +276,11 @@ async function runMigrations() {
|
||||
}
|
||||
|
||||
// Add delay for database readiness in production
|
||||
// Engine consistency check (#1038). The entrypoint resolves the engine before
|
||||
// migrations run and exports DATABASE_CLIENT, so this normally agrees and does
|
||||
// nothing. It bites on a MANUAL migration run: without that env, an install
|
||||
// that is really on SQLite would resolve to Postgres here and build a schema in
|
||||
// the empty database, which then hides the SQLite data from the boot-time
|
||||
// check. Stop instead, and say which env to set.
|
||||
async function assertEngine() {
|
||||
const knexConfig = require('../knexfile');
|
||||
const logger = require('../src/utils/logger');
|
||||
const { resolveBootEngine } = require('../src/utils/databaseEngine');
|
||||
const decision = await resolveBootEngine({ knexConfig, logger });
|
||||
if (decision.reason === 'marker-target-mismatch') {
|
||||
console.error(
|
||||
'Refusing to migrate: this install was migrated to a different PostgreSQL than the\n'
|
||||
+ 'one currently configured. The resolver printed both targets above.'
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
if (decision.reason === 'ambiguous-both-populated') {
|
||||
// Both databases hold data and nothing records which is current; the
|
||||
// resolver has already printed the comparison. There is no client to
|
||||
// recommend here — the operator has to pick one.
|
||||
console.error(
|
||||
'Refusing to migrate: SQLite and PostgreSQL both hold data and neither is marked\n'
|
||||
+ 'as current. Set DATABASE_CLIENT=pg or DATABASE_CLIENT=sqlite3 to say which one\n'
|
||||
+ 'this command should touch.'
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
if (decision.client !== knexConfig.client) {
|
||||
console.error(
|
||||
`Refusing to migrate ${knexConfig.client} — this install's data is in ${decision.client}.\n`
|
||||
+ `Run migrations through the container entrypoint, or set DATABASE_CLIENT=${decision.client} explicitly.\n`
|
||||
+ 'To move the data across instead: node scripts/migrate-sqlite-to-postgres.js'
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
async function waitAndRun() {
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
console.log('Waiting 2 seconds for database readiness...');
|
||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
||||
}
|
||||
await assertEngine();
|
||||
await runMigrations();
|
||||
}
|
||||
|
||||
|
||||
@@ -46,50 +46,10 @@ async function runMigration(filepath) {
|
||||
}
|
||||
}
|
||||
|
||||
// Engine consistency check (#1038). The entrypoint resolves the engine before
|
||||
// migrations run and exports DATABASE_CLIENT, so this normally agrees and does
|
||||
// nothing. It bites on a MANUAL migration run: without that env, an install
|
||||
// that is really on SQLite would resolve to Postgres here and build a schema in
|
||||
// the empty database, which then hides the SQLite data from the boot-time
|
||||
// check. Stop instead, and say which env to set.
|
||||
async function assertEngine() {
|
||||
const knexConfig = require('../knexfile');
|
||||
const logger = require('../src/utils/logger');
|
||||
const { resolveBootEngine } = require('../src/utils/databaseEngine');
|
||||
const decision = await resolveBootEngine({ knexConfig, logger });
|
||||
if (decision.reason === 'marker-target-mismatch') {
|
||||
console.error(
|
||||
'Refusing to migrate: this install was migrated to a different PostgreSQL than the\n'
|
||||
+ 'one currently configured. The resolver printed both targets above.'
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
if (decision.reason === 'ambiguous-both-populated') {
|
||||
// Both databases hold data and nothing records which is current; the
|
||||
// resolver has already printed the comparison. There is no client to
|
||||
// recommend here — the operator has to pick one.
|
||||
console.error(
|
||||
'Refusing to migrate: SQLite and PostgreSQL both hold data and neither is marked\n'
|
||||
+ 'as current. Set DATABASE_CLIENT=pg or DATABASE_CLIENT=sqlite3 to say which one\n'
|
||||
+ 'this command should touch.'
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
if (decision.client !== knexConfig.client) {
|
||||
console.error(
|
||||
`Refusing to migrate ${knexConfig.client} — this install's data is in ${decision.client}.\n`
|
||||
+ `Run migrations through the container entrypoint, or set DATABASE_CLIENT=${decision.client} explicitly.\n`
|
||||
+ 'To move the data across instead: node scripts/migrate-sqlite-to-postgres.js'
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Main migration runner
|
||||
async function runMigrations() {
|
||||
try {
|
||||
console.log('Starting database migrations...');
|
||||
await assertEngine();
|
||||
|
||||
// First run the init.js if it exists but only if migrations table doesn't exist
|
||||
const tableExists = await db.schema.hasTable('migrations');
|
||||
|
||||
Generated
+8
-69
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "picpeak-backend",
|
||||
"version": "3.101.3-beta.0",
|
||||
"version": "3.45.13",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "picpeak-backend",
|
||||
"version": "3.101.3-beta.0",
|
||||
"version": "3.45.13",
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-s3": "^3.850.0",
|
||||
"@aws-sdk/lib-storage": "^3.850.0",
|
||||
@@ -41,7 +41,6 @@
|
||||
"node-cron": "^3.0.2",
|
||||
"node-stream-zip": "^1.15.0",
|
||||
"nodemailer": "^9.0.1",
|
||||
"openid-client": "^5.7.1",
|
||||
"otplib": "^12.0.1",
|
||||
"p-limit": "^3.1.0",
|
||||
"pdf-lib": "^1.17.1",
|
||||
@@ -7967,15 +7966,6 @@
|
||||
"@sideway/pinpoint": "^2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/jose": {
|
||||
"version": "4.15.9",
|
||||
"resolved": "https://registry.npmjs.org/jose/-/jose-4.15.9.tgz",
|
||||
"integrity": "sha512-1vUQX+IdDMVPj4k8kOxgUqlcK518yluMuGZwqlr44FS1ppZB/5GWh4rZG89erpOBOJjU/OBsnCVFfapsRz6nEA==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/panva"
|
||||
}
|
||||
},
|
||||
"node_modules/jpeg-exif": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/jpeg-exif/-/jpeg-exif-1.1.4.tgz",
|
||||
@@ -7991,9 +7981,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/js-yaml": {
|
||||
"version": "4.3.1",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.1.tgz",
|
||||
"integrity": "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==",
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz",
|
||||
"integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
@@ -9086,9 +9076,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/nanoid": {
|
||||
"version": "3.3.18",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",
|
||||
"integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==",
|
||||
"version": "3.3.16",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz",
|
||||
"integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
@@ -9458,15 +9448,6 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/object-hash": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/object-hash/-/object-hash-2.2.0.tgz",
|
||||
"integrity": "sha512-gScRMn0bS5fH+IuwyIFgnh9zBdo4DV+6GhygmWM9HyNJSgS0hScp1f5vjtm7oIIOiT9trXrShAkLFSc2IqKNgw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/object-inspect": {
|
||||
"version": "1.13.4",
|
||||
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
|
||||
@@ -9479,15 +9460,6 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/oidc-token-hash": {
|
||||
"version": "5.2.0",
|
||||
"resolved": "https://registry.npmjs.org/oidc-token-hash/-/oidc-token-hash-5.2.0.tgz",
|
||||
"integrity": "sha512-6gj2m8cJZ+iSW8bm0FXdGF0YhIQbKrfP4yWTNzxc31U6MOjfEmB1rHvlYvxI1B7t7BCi1F2vYTT6YhtQRG4hxw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^10.13.0 || >=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/on-exit-leak-free": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz",
|
||||
@@ -9550,39 +9522,6 @@
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/openid-client": {
|
||||
"version": "5.7.1",
|
||||
"resolved": "https://registry.npmjs.org/openid-client/-/openid-client-5.7.1.tgz",
|
||||
"integrity": "sha512-jDBPgSVfTnkIh71Hg9pRvtJc6wTwqjRkN88+gCFtYWrlP4Yx2Dsrow8uPi3qLr/aeymPF3o2+dS+wOpglK04ew==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"jose": "^4.15.9",
|
||||
"lru-cache": "^6.0.0",
|
||||
"object-hash": "^2.2.0",
|
||||
"oidc-token-hash": "^5.0.3"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/panva"
|
||||
}
|
||||
},
|
||||
"node_modules/openid-client/node_modules/lru-cache": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
|
||||
"integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"yallist": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/openid-client/node_modules/yallist": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
|
||||
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/optionator": {
|
||||
"version": "0.9.4",
|
||||
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "picpeak-backend",
|
||||
"version": "3.105.1-beta.0",
|
||||
"version": "3.45.14",
|
||||
"description": "Backend for PicPeak event photo sharing platform",
|
||||
"main": "server.js",
|
||||
"engines": {
|
||||
@@ -14,7 +14,6 @@
|
||||
"generate:watermarks": "node scripts/generate-watermarks.js",
|
||||
"test": "jest",
|
||||
"test:s3": "SKIP_S3_TESTS=false jest __tests__/integration/backup-s3",
|
||||
"test:pg": "jest __tests__/integration/picpeakRestorePg",
|
||||
"lint": "eslint src/"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -51,7 +50,6 @@
|
||||
"node-cron": "^3.0.2",
|
||||
"node-stream-zip": "^1.15.0",
|
||||
"nodemailer": "^9.0.1",
|
||||
"openid-client": "^5.7.1",
|
||||
"otplib": "^12.0.1",
|
||||
"p-limit": "^3.1.0",
|
||||
"pdf-lib": "^1.17.1",
|
||||
|
||||
@@ -1,537 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Move an install's data from SQLite to PostgreSQL (#1038).
|
||||
*
|
||||
* node scripts/migrate-sqlite-to-postgres.js [--force] [--keep-archive]
|
||||
*
|
||||
* For installs that have been unknowingly running on SQLite: the image used to
|
||||
* leave NODE_ENV unset, so knexfile.js fell back to its development block and
|
||||
* ignored DB_HOST/DB_USER/DB_PASSWORD. Their galleries live in the SQLite file
|
||||
* while the Postgres database they provisioned sits empty.
|
||||
*
|
||||
* This deliberately reuses the .picpeak export/import services rather than
|
||||
* hand-rolling a cross-engine copy — they already solve the parts that are easy
|
||||
* to get wrong: foreign-key suspension during the load, JSON column handling
|
||||
* per engine, and (critically) resyncing Postgres serial sequences after rows
|
||||
* are inserted with explicit ids.
|
||||
*
|
||||
* Both services bind to the global `db` at require time, so each half runs in
|
||||
* its own child process with DATABASE_CLIENT pinned — this script re-invokes
|
||||
* itself with --phase for that.
|
||||
*
|
||||
* Photos and other files on disk are NOT touched: only database rows move. The
|
||||
* SQLite file is left exactly as it was, so the migration is reversible by
|
||||
* unsetting DATABASE_CLIENT again.
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { spawnSync } = require('child_process');
|
||||
|
||||
const BACKEND_ROOT = path.resolve(__dirname, '..');
|
||||
|
||||
// Same configuration sources the running backend uses. Without these, invoking
|
||||
// this CLI directly (or via `docker exec`, which does not inherit the exports
|
||||
// wait-for-db.sh performs) would fail the pre-flight checks below even though
|
||||
// the child phases would happily read backend/.env through knexfile.
|
||||
require('dotenv').config({ path: path.join(BACKEND_ROOT, '.env') });
|
||||
for (const [varName, file] of [['DB_PASSWORD', 'db_password'], ['JWT_SECRET', 'jwt_secret']]) {
|
||||
const secretFile = `/run/secrets/${file}`;
|
||||
if (!process.env[varName] && fs.existsSync(secretFile)) {
|
||||
try {
|
||||
process.env[varName] = fs.readFileSync(secretFile, 'utf8').trim();
|
||||
} catch (_) { /* unreadable secret — the checks below report it */ }
|
||||
}
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
return {
|
||||
force: argv.includes('--force'),
|
||||
keepArchive: argv.includes('--keep-archive'),
|
||||
phase: (argv.find((a) => a.startsWith('--phase=')) || '').split('=')[1] || null,
|
||||
archive: (argv.find((a) => a.startsWith('--archive=')) || '').split('=')[1] || null,
|
||||
resultFile: (argv.find((a) => a.startsWith('--result-file=')) || '').split('=')[1] || null,
|
||||
ignoreBootstrapAdmins: argv.includes('--ignore-bootstrap-admins'),
|
||||
};
|
||||
}
|
||||
|
||||
// Resolve the Postgres target ONCE, with production defaults, and hand the same
|
||||
// explicit values to every child. Otherwise the block knexfile happens to pick
|
||||
// decides the database name, and the migration can land somewhere the running
|
||||
// application will never open (#1038 review).
|
||||
function normalisedPgEnv() {
|
||||
const { pgConnectionFromEnv } = require('../src/utils/databaseEngine');
|
||||
const c = pgConnectionFromEnv();
|
||||
return {
|
||||
DB_HOST: String(c.host),
|
||||
DB_PORT: String(c.port),
|
||||
DB_USER: String(c.user),
|
||||
DB_NAME: String(c.database),
|
||||
};
|
||||
}
|
||||
|
||||
function runPhase(phase, client, extraArgs = []) {
|
||||
// The child's stdout is NOT a private channel: winston logs to the console
|
||||
// outside production and whenever LOG_TO_CONSOLE=true, so the payload comes
|
||||
// back through a file instead.
|
||||
const resultFile = path.join(
|
||||
fs.mkdtempSync(path.join(os.tmpdir(), `picpeak-phase-${phase}-`)), 'result',
|
||||
);
|
||||
try {
|
||||
const res = spawnSync(
|
||||
process.execPath,
|
||||
[__filename, `--phase=${phase}`, `--result-file=${resultFile}`, ...extraArgs],
|
||||
{
|
||||
cwd: BACKEND_ROOT,
|
||||
env: {
|
||||
...process.env,
|
||||
...normalisedPgEnv(),
|
||||
DATABASE_CLIENT: client,
|
||||
// Production semantics for the child regardless of how the CLI was
|
||||
// invoked: the development block ignores DB_SSL, so a managed Postgres
|
||||
// that requires TLS could not be migrated into at all.
|
||||
NODE_ENV: 'production',
|
||||
},
|
||||
stdio: ['ignore', 'inherit', 'inherit'],
|
||||
encoding: 'utf8',
|
||||
},
|
||||
);
|
||||
if (res.status !== 0) {
|
||||
throw new Error(`${phase} phase failed (exit ${res.status})`);
|
||||
}
|
||||
return fs.existsSync(resultFile) ? fs.readFileSync(resultFile, 'utf8').trim() : '';
|
||||
} finally {
|
||||
fs.rmSync(path.dirname(resultFile), { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
// ── phases (each runs in its own process, with DATABASE_CLIENT pinned) ────────
|
||||
|
||||
async function phaseExport() {
|
||||
const { createPicpeak } = require('../src/services/picpeakExportService');
|
||||
const outDir = fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-sqlite-migration-'));
|
||||
// Rows only. This moves an install between engines on the SAME machine, so
|
||||
// every file is already where it belongs; hauling business docs through /tmp
|
||||
// would just risk filling the temp disk.
|
||||
try {
|
||||
const { filePath } = await createPicpeak({ includePhotos: false, includeFiles: false, outDir });
|
||||
return filePath;
|
||||
} catch (err) {
|
||||
// createPicpeak leaves a caller-supplied outDir alone on failure, and a
|
||||
// partial archive still contains password hashes and credentials.
|
||||
fs.rmSync(outDir, { recursive: true, force: true });
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// Tables that are EMPTY on a freshly migrated schema, so any row in them means
|
||||
// a human has used this install. Used to protect the target from being wiped
|
||||
// and to decide whether the source is worth migrating (#1038 review). Tables
|
||||
// missing on a given branch are skipped.
|
||||
const USER_DATA_TABLES = [
|
||||
'events', 'photos', 'photo_feedback', 'admin_users', 'customer_accounts',
|
||||
'quotes', 'invoices', 'projects', 'expenses', 'inbound_documents',
|
||||
];
|
||||
|
||||
async function tablesWithData(db, tables, { ignoreBootstrapAdmins = false } = {}) {
|
||||
const { adminsIndicateUse } = require('../src/utils/databaseEngine');
|
||||
const found = {};
|
||||
for (const table of tables) {
|
||||
if (!(await db.schema.hasTable(table))) continue;
|
||||
if (table === 'admin_users' && ignoreBootstrapAdmins) {
|
||||
// Match probePgData: one never-used seeded admin is not "user data", or
|
||||
// the migration would demand --force against an empty target.
|
||||
const cols = ['must_change_password'];
|
||||
if (await db.schema.hasColumn('admin_users', 'last_login')) cols.push('last_login');
|
||||
const rows = await db('admin_users').select(cols);
|
||||
if (adminsIndicateUse(rows)) found[table] = rows.length;
|
||||
continue;
|
||||
}
|
||||
const row = await db(table).count('* as count').first();
|
||||
const count = Number(row?.count || 0);
|
||||
if (count > 0) found[table] = count;
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
async function phaseUserData(ignoreBootstrapAdmins) {
|
||||
const { db } = require('../src/database/db');
|
||||
return JSON.stringify(await tablesWithData(db, USER_DATA_TABLES, { ignoreBootstrapAdmins }));
|
||||
}
|
||||
|
||||
// Fingerprint EVERY table the export carries, not a hand-picked few: writes to
|
||||
// an unlisted table were invisible, and count+maxId alone misses in-place
|
||||
// UPDATEs (an event edit, a password change). max(updated_at) covers those
|
||||
// wherever the column exists. Still not a substitute for stopping the backend —
|
||||
// a table with neither `id` nor `updated_at` can be edited unnoticed — which is
|
||||
// why the script says so up front.
|
||||
async function phaseFingerprint() {
|
||||
const { db } = require('../src/database/db');
|
||||
const { listDataTables } = require('../src/services/picpeakExportService');
|
||||
const out = {};
|
||||
for (const table of await listDataTables()) {
|
||||
const entry = {};
|
||||
try {
|
||||
entry.count = Number((await db(table).count('* as count').first())?.count || 0);
|
||||
} catch (_) {
|
||||
continue; // table vanished mid-run; the export would fail on it anyway
|
||||
}
|
||||
for (const [key, col] of [['maxId', 'id'], ['maxUpdated', 'updated_at']]) {
|
||||
try {
|
||||
const row = await db(table).max(`${col} as v`).first();
|
||||
if (row && row.v !== null && row.v !== undefined) entry[key] = String(row.v);
|
||||
} catch (_) { /* column doesn't exist on this table */ }
|
||||
}
|
||||
out[table] = entry;
|
||||
}
|
||||
return JSON.stringify(out);
|
||||
}
|
||||
|
||||
async function phaseMigrateSchema() {
|
||||
// runMigrations() exits the process itself (0 on success, 1 on failure), so the
|
||||
// child's exit code is the result — nothing to return.
|
||||
const { runMigrations } = require('../migrations/run-migrations-safe');
|
||||
await runMigrations();
|
||||
}
|
||||
|
||||
async function phaseImport(archivePath) {
|
||||
const { importFromPicpeak } = require('../src/services/picpeakImportService');
|
||||
// No currentAdminId: this is a CLI, there is no operator session to preserve.
|
||||
// The SQLite install's own admin accounts come across with everything else.
|
||||
// sqlite → pg is allowed by validateManifest's direction policy (#1041) —
|
||||
// the same gate the upload/restore UI uses, no separate opt-in flag.
|
||||
const summary = await importFromPicpeak({ picpeakPath: archivePath });
|
||||
return JSON.stringify(summary || {});
|
||||
}
|
||||
|
||||
function summariseUserData(found) {
|
||||
return Object.entries(found).map(([t, n]) => `${t}=${n}`).join(', ');
|
||||
}
|
||||
|
||||
function describeDrift(before, after) {
|
||||
const drifted = [];
|
||||
for (const table of new Set([...Object.keys(before), ...Object.keys(after)])) {
|
||||
const a = before[table] || {};
|
||||
const b = after[table] || {};
|
||||
if (a.count !== b.count) {
|
||||
drifted.push(`${table}: ${a.count ?? 0} rows → ${b.count ?? 0}`);
|
||||
} else if (a.maxId !== b.maxId || a.maxUpdated !== b.maxUpdated) {
|
||||
drifted.push(`${table}: rows edited in place (max id ${a.maxId ?? '-'} → ${b.maxId ?? '-'}, `
|
||||
+ `last update ${a.maxUpdated ?? '-'} → ${b.maxUpdated ?? '-'})`);
|
||||
}
|
||||
}
|
||||
return drifted;
|
||||
}
|
||||
|
||||
// Set once the export exists; every failure path clears it (the archive holds
|
||||
// plaintext secrets, so leaving it behind on error is not acceptable).
|
||||
let archiveToClean = null;
|
||||
|
||||
function cleanupArchive() {
|
||||
if (!archiveToClean) return;
|
||||
try {
|
||||
fs.rmSync(path.dirname(archiveToClean), { recursive: true, force: true });
|
||||
} catch (err) {
|
||||
console.error(` WARNING: could not remove ${archiveToClean} (${err.message}) — it contains`
|
||||
+ ' plaintext secrets, delete it by hand.');
|
||||
}
|
||||
archiveToClean = null;
|
||||
}
|
||||
|
||||
// ── orchestration ────────────────────────────────────────────────────────────
|
||||
|
||||
async function main() {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
|
||||
// Child phase. The knex pool holds the event loop open, so finish by flushing
|
||||
// stdout and exiting explicitly — otherwise the parent's spawnSync waits on a
|
||||
// process that will never end by itself.
|
||||
if (args.phase) {
|
||||
const payload = args.phase === 'export' ? await phaseExport()
|
||||
: args.phase === 'fingerprint' ? await phaseFingerprint()
|
||||
: args.phase === 'user-data' ? await phaseUserData(args.ignoreBootstrapAdmins)
|
||||
: args.phase === 'import' ? await phaseImport(args.archive)
|
||||
: await phaseMigrateSchema();
|
||||
if (args.resultFile) fs.writeFileSync(args.resultFile, String(payload ?? ''));
|
||||
// The knex pool holds the event loop open; exit explicitly or the parent's
|
||||
// spawnSync waits on a process that will never end by itself.
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const { resolveSqlitePath } = require('../src/utils/databaseEngine');
|
||||
const sqlitePath = resolveSqlitePath();
|
||||
|
||||
console.log('PicPeak — SQLite → PostgreSQL migration\n');
|
||||
|
||||
if (!fs.existsSync(sqlitePath)) {
|
||||
console.error(`No SQLite database at ${sqlitePath}. Nothing to migrate.`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (process.env.DATABASE_CLIENT && process.env.DATABASE_CLIENT !== 'pg') {
|
||||
console.error(
|
||||
`This deployment pins DATABASE_CLIENT=${process.env.DATABASE_CLIENT}.\n`
|
||||
+ 'After the migration the application must run on PostgreSQL — the SQLite file is\n'
|
||||
+ 'renamed out of the way, so a restart with this setting would create a NEW, empty\n'
|
||||
+ 'SQLite database and serve that instead of your data.\n\n'
|
||||
+ 'Set DATABASE_CLIENT=pg (or remove it) in your deployment, then run this again.'
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Not a refusal: an unset NODE_ENV is exactly the state the affected installs
|
||||
// are in, and refusing would block the people this script is for. The success
|
||||
// marker makes the boot resolve to Postgres regardless; this just tells the
|
||||
// operator to make it explicit.
|
||||
if (!process.env.DATABASE_CLIENT && require('../knexfile').client !== 'pg') {
|
||||
console.log(
|
||||
'Note: this environment resolves to SQLite (NODE_ENV is not "production" and\n'
|
||||
+ 'DATABASE_CLIENT is unset). The migration will still complete and the marker it\n'
|
||||
+ 'writes makes the app use PostgreSQL afterwards, but set NODE_ENV=production (or\n'
|
||||
+ 'DATABASE_CLIENT=pg) so the configuration says what is actually happening.\n'
|
||||
);
|
||||
}
|
||||
|
||||
if (!process.env.DB_HOST && !process.env.DB_PASSWORD) {
|
||||
console.error(
|
||||
'No PostgreSQL settings found (DB_HOST / DB_PASSWORD). Set them the way the\n'
|
||||
+ 'backend does, then re-run this script inside the container.'
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(
|
||||
'Stop the backend before running this. If it keeps serving while the copy runs,\n'
|
||||
+ 'anything written after the export is left behind in SQLite and becomes invisible\n'
|
||||
+ 'once the engine switches. This script checks for that afterwards and fails loudly,\n'
|
||||
+ 'but stopping the container first is the only way to be sure.\n'
|
||||
);
|
||||
|
||||
const sourceData = JSON.parse(runPhase('user-data', 'sqlite3'));
|
||||
console.log(` source : ${sqlitePath} — ${summariseUserData(sourceData) || 'no user data'}`);
|
||||
if (!Object.keys(sourceData).length) {
|
||||
console.error(
|
||||
'\nThe SQLite database holds no user data at all (no galleries, admins, customers or\n'
|
||||
+ 'accounting records). There is nothing to migrate.'
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
const sqliteBefore = JSON.parse(runPhase('fingerprint', 'sqlite3'));
|
||||
|
||||
// Read the target BEFORE creating the schema: migration 001 seeds a bootstrap
|
||||
// admin when ADMIN_PASSWORD is set (common on legacy installs), and counting
|
||||
// that as "user data" would refuse a migration into a genuinely empty
|
||||
// database — pushing the operator towards --force for no reason.
|
||||
const { hasMigrationInProgress, migrationInProgressPath } = require('../src/utils/databaseEngine');
|
||||
// The retry allowance is bound to the TARGET, not just to this SQLite file:
|
||||
// if the operator repointed DB_HOST/DB_NAME since the failed attempt, the
|
||||
// rows in front of us belong to some other database and must not be replaced
|
||||
// without an explicit --force.
|
||||
const pgEnv = normalisedPgEnv();
|
||||
const targetId = `${pgEnv.DB_HOST}:${pgEnv.DB_PORT}/${pgEnv.DB_NAME}`;
|
||||
let retryingOwnRun = false;
|
||||
if (hasMigrationInProgress(sqlitePath)) {
|
||||
try {
|
||||
const pin = JSON.parse(fs.readFileSync(migrationInProgressPath(sqlitePath), 'utf8'));
|
||||
retryingOwnRun = pin.target === targetId;
|
||||
if (!retryingOwnRun) {
|
||||
console.log(` (an earlier attempt targeted ${pin.target}; this run targets ${targetId})`);
|
||||
}
|
||||
} catch (_) {
|
||||
retryingOwnRun = false; // unreadable pin — treat as unknown, require --force
|
||||
}
|
||||
}
|
||||
const targetData = JSON.parse(runPhase('user-data', 'pg', ['--ignore-bootstrap-admins']));
|
||||
console.log(` target : postgres — ${summariseUserData(targetData) || 'empty'}`);
|
||||
if (retryingOwnRun && Object.keys(targetData).length) {
|
||||
// Whatever is in Postgres came from a previous attempt of THIS script that
|
||||
// never completed — re-running is the documented recovery, so don't make
|
||||
// the operator reach for a destructive-sounding flag to do it.
|
||||
console.log(' (an earlier migration did not finish; re-running replaces what it left behind)');
|
||||
} else if (Object.keys(targetData).length && !args.force) {
|
||||
console.error(
|
||||
`\nPostgreSQL already holds user data (${summariseUserData(targetData)}).\n`
|
||||
+ 'The import REPLACES every table, so this would delete it — including admins,\n'
|
||||
+ 'customers and accounting records that have no galleries attached.\n'
|
||||
+ 'Re-run with --force only if you are certain you want that data gone.'
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Pin the boot to SQLite for the duration. Everything below writes to
|
||||
// Postgres — schema creation alone seeds a bootstrap admin when
|
||||
// ADMIN_PASSWORD is set — and a run that dies half way would otherwise leave
|
||||
// Postgres looking occupied enough for the next restart to switch to it.
|
||||
const inProgress = migrationInProgressPath(sqlitePath);
|
||||
fs.writeFileSync(inProgress, JSON.stringify({
|
||||
started_at: new Date().toISOString(),
|
||||
target: targetId,
|
||||
}, null, 2));
|
||||
|
||||
// Now build the schema — the import replaces table CONTENTS, it never creates
|
||||
// them, and a fresh database has no tables at all.
|
||||
//
|
||||
// core/001_init.js writes data/ADMIN_CREDENTIALS.txt when ADMIN_PASSWORD is
|
||||
// set, and that data directory belongs to the SOURCE install — so bootstrapping
|
||||
// the schema would replace the operator's real credentials file with ones for
|
||||
// a temporary admin the import then discards. Preserve it across the phase.
|
||||
const credFile = path.join(BACKEND_ROOT, 'data', 'ADMIN_CREDENTIALS.txt');
|
||||
const credBefore = fs.existsSync(credFile) ? fs.readFileSync(credFile) : null;
|
||||
console.log('\n Preparing PostgreSQL schema…');
|
||||
try {
|
||||
runPhase('migrate-schema', 'pg');
|
||||
} finally {
|
||||
if (credBefore !== null) fs.writeFileSync(credFile, credBefore);
|
||||
else fs.rmSync(credFile, { force: true });
|
||||
}
|
||||
|
||||
console.log('\n Exporting rows from SQLite…');
|
||||
const archive = runPhase('export', 'sqlite3');
|
||||
// From here on, every exit path must remove the archive: it holds password
|
||||
// hashes, SMTP credentials and API keys in plaintext.
|
||||
archiveToClean = args.keepArchive ? null : archive;
|
||||
const sizeMb = (fs.statSync(archive).size / 1024 / 1024).toFixed(1);
|
||||
console.log(` archive: ${archive} (${sizeMb} MB)`);
|
||||
|
||||
// Check BEFORE touching Postgres: if the backend wrote to SQLite while the
|
||||
// export ran, the snapshot is already incomplete and there is no reason to
|
||||
// load it. Bailing here leaves Postgres exactly as it was.
|
||||
const driftDuringExport = describeDrift(sqliteBefore, JSON.parse(runPhase('fingerprint', 'sqlite3')));
|
||||
if (driftDuringExport.length) {
|
||||
console.error(
|
||||
'\nSQLite CHANGED WHILE THE EXPORT RAN — the backend is still writing to it:\n'
|
||||
+ driftDuringExport.map((d) => ` ${d}`).join('\n')
|
||||
+ '\n\nNothing was loaded into Postgres, and this install stays pinned to SQLite\n'
|
||||
+ 'until a run completes. Stop the backend and run this again.'
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log('\n Loading into PostgreSQL…');
|
||||
runPhase('import', 'pg', [`--archive=${archive}`]);
|
||||
|
||||
// And again afterwards: writes can also land while the load runs, and those
|
||||
// rows would vanish from view the moment the engine switches.
|
||||
const driftDuringImport = describeDrift(sqliteBefore, JSON.parse(runPhase('fingerprint', 'sqlite3')));
|
||||
if (driftDuringImport.length) {
|
||||
console.error(
|
||||
'\nSQLite CHANGED WHILE THE IMPORT RAN — the backend is still writing to it:\n'
|
||||
+ driftDuringImport.map((d) => ` ${d}`).join('\n')
|
||||
+ '\n\nPostgres now holds an incomplete copy. Your SQLite data is intact and stays\n'
|
||||
+ 'the one being served — the boot is pinned to it until a run completes. Stop the\n'
|
||||
+ 'backend and run this again; the import replaces every table, so re-running is safe.'
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Row-for-row comparison of the whole database, not just galleries: every
|
||||
// table the export carried must have arrived with the same row count.
|
||||
const targetAfter = JSON.parse(runPhase('fingerprint', 'pg'));
|
||||
// Only a SHORTFALL is a problem. The import legitimately adds rows of its own
|
||||
// afterwards — setSessionsValidAfter() writes an app_settings row so tokens
|
||||
// minted before the restore stop authenticating — and a target that gained
|
||||
// rows has not lost anything.
|
||||
const missing = [];
|
||||
const gained = [];
|
||||
const skipped = [];
|
||||
for (const [table, src] of Object.entries(sqliteBefore)) {
|
||||
const dst = targetAfter[table];
|
||||
if (!dst) {
|
||||
// SQLite-only tables exist: initializeDatabase() builds an `events_new`
|
||||
// scratch table and, if its legacy copy throws, the catch leaves the empty
|
||||
// table behind (db.js). The importer correctly skips tables Postgres does
|
||||
// not have — so an ABSENT table only matters if it actually held rows.
|
||||
// Flagging empty ones failed the whole migration after the data had
|
||||
// already landed, leaving the install pinned to SQLite forever.
|
||||
if (src.count > 0) missing.push(`${table}: ${src.count} rows, no such table in Postgres`);
|
||||
else skipped.push(table);
|
||||
continue;
|
||||
}
|
||||
if (dst.count < src.count) missing.push(`${table}: ${src.count} rows → ${dst.count}`);
|
||||
else if (dst.count > src.count) gained.push(`${table}: ${src.count} → ${dst.count}`);
|
||||
}
|
||||
if (skipped.length) {
|
||||
console.log(` (empty SQLite-only tables with no Postgres counterpart, skipped: ${skipped.join(', ')})`);
|
||||
}
|
||||
if (gained.length) console.log(` (rows added by the import itself: ${gained.join(', ')})`);
|
||||
console.log(`\n PostgreSQL now holds ${summariseUserData(JSON.parse(runPhase('user-data', 'pg')))}.`);
|
||||
|
||||
if (missing.length) {
|
||||
console.error(
|
||||
'\nROW COUNTS DO NOT MATCH — Postgres did not receive everything:\n'
|
||||
+ missing.map((m) => ` ${m}`).join('\n')
|
||||
+ '\n\nYour SQLite data is untouched and stays the one being served — the boot is\n'
|
||||
+ 'pinned to it until a run completes. Report this with the list above.'
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Pin the engine choice so a later "Postgres looks empty" moment can never
|
||||
// send the install back to this now-stale file.
|
||||
const { migrationMarkerPath } = require('../src/utils/databaseEngine');
|
||||
const marker = migrationMarkerPath(sqlitePath);
|
||||
const retired = `${sqlitePath}.pre-postgres-${new Date().toISOString().replace(/[:.]/g, '-')}`;
|
||||
|
||||
// Marker FIRST, rename second. The other order has a window where a failure
|
||||
// (a full disk, say) leaves the source renamed away with no success marker:
|
||||
// the next run reports "No SQLite database", the in-progress pin is still
|
||||
// there, and the operator never sees the rollback path. Writing the marker
|
||||
// first means a failure here leaves everything exactly where it was.
|
||||
fs.writeFileSync(marker, JSON.stringify({
|
||||
migrated_at: new Date().toISOString(),
|
||||
retired_sqlite_file: null,
|
||||
target: targetId,
|
||||
}, null, 2));
|
||||
|
||||
let retiredTo = null;
|
||||
try {
|
||||
fs.renameSync(sqlitePath, retired);
|
||||
retiredTo = retired;
|
||||
fs.writeFileSync(marker, JSON.stringify({
|
||||
migrated_at: new Date().toISOString(),
|
||||
retired_sqlite_file: retiredTo,
|
||||
target: targetId,
|
||||
}, null, 2));
|
||||
} catch (err) {
|
||||
// The marker already pins the engine to Postgres, so leaving the file in
|
||||
// place is safe — it just is not renamed out of the way.
|
||||
console.log(` (could not rename the SQLite file: ${err.message} — leaving it in place)`);
|
||||
}
|
||||
// Success — release the pin. Order matters: the success marker exists before
|
||||
// the pin is dropped, so no restart in between can pick the wrong engine.
|
||||
fs.rmSync(inProgress, { force: true });
|
||||
|
||||
if (args.keepArchive) {
|
||||
console.log(` archive kept at ${archive} — it contains plaintext secrets, delete it when done`);
|
||||
} else {
|
||||
cleanupArchive();
|
||||
}
|
||||
|
||||
console.log(`
|
||||
Done. Your data is now in PostgreSQL.
|
||||
|
||||
rollback copy : ${retiredTo || sqlitePath}
|
||||
marker : ${marker}
|
||||
|
||||
Restart the container to pick up PostgreSQL. Keep the rollback copy until you
|
||||
have confirmed the galleries look right.
|
||||
|
||||
To roll back, all three steps are needed — with data on both sides the boot
|
||||
picks PostgreSQL, so restoring the file alone changes nothing:
|
||||
|
||||
1. rm ${marker}
|
||||
2. mv ${retiredTo || sqlitePath} ${sqlitePath}
|
||||
3. set DATABASE_CLIENT=sqlite3 in your deployment
|
||||
`);
|
||||
}
|
||||
|
||||
process.on('exit', cleanupArchive);
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(`\nMigration failed: ${err.message}`);
|
||||
console.error('Nothing was changed in SQLite; your data is still there.');
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,51 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Prints the database client this boot should use — `pg` or `sqlite3` — for
|
||||
* wait-for-db.sh to export as DATABASE_CLIENT (#1038).
|
||||
*
|
||||
* Runs BEFORE the migration step on purpose: the decision has to be made while
|
||||
* the Postgres target is still untouched, so an install that has been
|
||||
* unknowingly running on SQLite keeps serving from its SQLite file instead of
|
||||
* coming up against an empty database.
|
||||
*
|
||||
* stdout is the client and nothing else — the caller captures it. Everything
|
||||
* human-readable goes to stderr so it lands in the container log.
|
||||
*/
|
||||
|
||||
const knexConfig = require('../knexfile');
|
||||
|
||||
// Must cover every level resolveBootEngine uses. An incomplete shim threw
|
||||
// inside the conflict path, was swallowed by the catch below, and fell back to
|
||||
// the configured client — silently choosing the engine this is meant to refuse
|
||||
// to choose.
|
||||
const logger = {
|
||||
info: (m) => process.stderr.write(`${m}\n`),
|
||||
warn: (m) => process.stderr.write(`${m}\n`),
|
||||
error: (m) => process.stderr.write(`${m}\n`),
|
||||
debug: () => {},
|
||||
};
|
||||
|
||||
// Distinct exit code for "two populated databases, no record of which is
|
||||
// current" (#1038). Callers must stop rather than pick one.
|
||||
const CONFLICT_EXIT = 3;
|
||||
|
||||
(async () => {
|
||||
let client = knexConfig.client;
|
||||
try {
|
||||
const { resolveBootEngine } = require('../src/utils/databaseEngine');
|
||||
const decision = await resolveBootEngine({ knexConfig, logger });
|
||||
if (decision.reason === 'ambiguous-both-populated'
|
||||
|| decision.reason === 'marker-target-mismatch') {
|
||||
process.exit(CONFLICT_EXIT);
|
||||
}
|
||||
({ client } = decision);
|
||||
} catch (err) {
|
||||
// Never let engine detection stop a boot: fall back to whatever knexfile
|
||||
// resolved, which is exactly the behaviour before this script existed.
|
||||
logger.warn(`Database engine detection failed (${err.message}); using ${client}`);
|
||||
}
|
||||
process.stdout.write(String(client || ''));
|
||||
process.exit(0);
|
||||
})();
|
||||
@@ -14,14 +14,17 @@ const bcrypt = require('bcrypt');
|
||||
const path = require('path');
|
||||
require('dotenv').config({ path: path.join(__dirname, '../.env') });
|
||||
|
||||
// Use the application's own connection, like every sibling script here
|
||||
// (reset-admin-password, create-admin, show-admin-credentials, reset-admin-mfa).
|
||||
// This file used to hand-roll its own knex config, which meant: it read
|
||||
// DB_CLIENT — a variable nothing else in the codebase sets — and so defaulted
|
||||
// to Postgres on SQLite installs; and it defaulted to database `picpeak_dev`,
|
||||
// a name no other component uses. Setting a password could therefore silently
|
||||
// target a different database than the one the application serves (#1038).
|
||||
const { db } = require('../src/database/db');
|
||||
const knex = require('knex');
|
||||
const db = knex({
|
||||
client: process.env.DB_CLIENT || 'pg',
|
||||
connection: {
|
||||
host: process.env.DB_HOST || 'localhost',
|
||||
port: process.env.DB_PORT || 5432,
|
||||
user: process.env.DB_USER || 'picpeak',
|
||||
password: process.env.DB_PASSWORD || 'picpeak',
|
||||
database: process.env.DB_NAME || 'picpeak_dev'
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Validate password strength
|
||||
@@ -108,10 +111,8 @@ async function setAdminPassword() {
|
||||
.where('username', 'admin')
|
||||
.update({
|
||||
password_hash: hashedPassword,
|
||||
// ISO strings, not Date objects — they round-trip on both engines, and
|
||||
// this script now runs on SQLite installs too.
|
||||
password_changed_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString()
|
||||
password_changed_at: new Date(),
|
||||
updated_at: new Date()
|
||||
});
|
||||
|
||||
if (updated === 0) {
|
||||
|
||||
+1
-78
@@ -4,61 +4,11 @@ require('dotenv').config();
|
||||
const { validateEnvironment } = require('./src/config/validateEnv');
|
||||
validateEnvironment();
|
||||
|
||||
// Resolve which database engine this process should use, BEFORE anything
|
||||
// requires knexfile/db (#1038). wait-for-db.sh normally does this and exports
|
||||
// DATABASE_CLIENT, but a Kubernetes manifest that sets `command`/`args`, or a
|
||||
// plain `docker run … node server.js`, bypasses the entrypoint entirely — and
|
||||
// those are exactly the deployments this fix is for. Without this, such an
|
||||
// install would resolve to Postgres (NODE_ENV is baked into the image now) and
|
||||
// come up against an empty database while its SQLite data sat there unseen.
|
||||
//
|
||||
// spawnSync because the decision needs an async Postgres probe and this must
|
||||
// happen before the first `require` of knexfile. It short-circuits without
|
||||
// probing when DATABASE_CLIENT is already set, so the entrypoint path pays
|
||||
// nothing.
|
||||
// Also run it when a migration pin exists: an explicit DATABASE_CLIENT=pg
|
||||
// would otherwise skip the check and start against a half-migrated Postgres
|
||||
// while SQLite is still the database of record.
|
||||
if (!process.env.DATABASE_CLIENT
|
||||
|| require('./src/utils/databaseEngine').hasMigrationInProgress()) {
|
||||
const { spawnSync } = require('child_process');
|
||||
const probe = spawnSync(
|
||||
process.execPath,
|
||||
[require('path').join(__dirname, 'scripts', 'resolve-db-engine.js')],
|
||||
{ encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'] }
|
||||
);
|
||||
// Exit 3: two populated databases and no record of which is authoritative.
|
||||
// The resolver has printed the comparison and the two ways to resolve it;
|
||||
// starting either engine would hide the other's data.
|
||||
if (probe.status === 3) {
|
||||
process.exit(1);
|
||||
}
|
||||
const resolved = (probe.stdout || '').trim();
|
||||
if (probe.status === 0 && resolved) {
|
||||
process.env.DATABASE_CLIENT = resolved;
|
||||
// Pin the CONNECTION too, not just the client. knexfile's development block
|
||||
// defaults Postgres to localhost/postgres/photo_sharing and production to
|
||||
// db/picpeak/picpeak, so naming only the client can point this process at a
|
||||
// different database than the resolver probed — with SQLite already retired.
|
||||
if (resolved === 'pg') {
|
||||
const conn = require('./src/utils/databaseEngine').pgConnectionFromEnv();
|
||||
process.env.DB_HOST = String(conn.host);
|
||||
process.env.DB_PORT = String(conn.port);
|
||||
process.env.DB_USER = String(conn.user);
|
||||
process.env.DB_NAME = String(conn.database);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize logger early to capture startup logs
|
||||
const logger = require('./src/utils/logger');
|
||||
logger.info('Server starting up', {
|
||||
nodeVersion: process.version,
|
||||
environment: process.env.NODE_ENV || 'development',
|
||||
// Which database this process actually talks to (#1038). Nothing logged this
|
||||
// before, so an install silently running on SQLite with Postgres configured
|
||||
// had no way to notice.
|
||||
database: require('./src/utils/databaseEngine').describeEngine(require('./knexfile')),
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
@@ -70,9 +20,6 @@ const path = require('path');
|
||||
const { initializeDatabase, db } = require('./src/database/db');
|
||||
const { startFileWatcher } = require('./src/services/fileWatcher');
|
||||
const { startExpirationChecker } = require('./src/services/expirationChecker');
|
||||
const { startTransferCleanup } = require('./src/services/transferCleanupService');
|
||||
const { startDownloadJobCleanup } = require('./src/services/downloadJobCleanupService');
|
||||
const { startRevealScheduler } = require('./src/services/revealScheduler');
|
||||
const { startInvoiceScheduler } = require('./src/services/invoiceSchedulerService');
|
||||
const { initializeTransporter, startEmailQueueProcessor } = require('./src/services/emailProcessor');
|
||||
const { startBackupService } = require('./src/services/backupService');
|
||||
@@ -547,7 +494,7 @@ app.use('/uploads', setCorsHeaders, secureStatic(path.join(storagePath, 'uploads
|
||||
// are stable (e.g. Inter/400.woff2), so an admin replacing the file on disk
|
||||
// must be able to roll out the change to clients. With max-age + Last-Modified
|
||||
// (set by express.static from file mtime), browsers send If-Modified-Since
|
||||
// after expiry and pick up the new version automatically. See https://docs.picpeak.app/guides/custom-fonts
|
||||
// after expiry and pick up the new version automatically. See docs/fonts.md
|
||||
// "Replacing an existing font" for the documented rollout strategy.
|
||||
const fontStaticOpts = { maxAge: '7d' };
|
||||
app.use(
|
||||
@@ -773,7 +720,6 @@ app.use('/api/admin/photo-export', require('./src/routes/adminPhotoExport'));
|
||||
app.use('/api/admin/css-templates', require('./src/routes/adminCssTemplates'));
|
||||
app.use('/api/admin/events', require('./src/routes/adminEventRename'));
|
||||
app.use('/api/admin/users', require('./src/routes/adminUsers'));
|
||||
app.use('/api/admin/roles', require('./src/routes/adminRoles'));
|
||||
// Customer portal (#354). The customerPortal feature flag is a
|
||||
// VISIBILITY toggle for the admin surface, not a kill switch for
|
||||
// customer access. Enforcement:
|
||||
@@ -838,12 +784,8 @@ app.use('/api/admin/ledger', require('./src/routes/adminLedger'));
|
||||
app.use('/api/admin/vat-codes', require('./src/routes/adminVatCodes'));
|
||||
app.use('/api/admin/system-health', require('./src/routes/adminSystemHealth'));
|
||||
app.use('/api/admin/dev', require('./src/routes/adminDev'));
|
||||
app.use('/api/admin/transfers', require('./src/routes/adminTransfers'));
|
||||
app.use('/api/public/quotes', require('./src/routes/publicQuotes'));
|
||||
app.use('/api/public/contracts', require('./src/routes/publicContracts'));
|
||||
// PicTransfer (#997): recipient download + client upload, token-authenticated.
|
||||
app.use('/api/public/transfer', require('./src/routes/publicTransfer'));
|
||||
app.use('/api/public/transfer-upload', require('./src/routes/publicTransferUpload'));
|
||||
app.use('/api/public/payment-check', require('./src/routes/publicPaymentCheck'));
|
||||
app.use('/api/public/workflow-approvals', require('./src/routes/publicWorkflowApprovals'));
|
||||
app.use('/api/admin/event-types', require('./src/routes/adminEventTypes'));
|
||||
@@ -961,14 +903,6 @@ async function startServer() {
|
||||
|
||||
// Start expiration checker
|
||||
startExpirationChecker();
|
||||
// PicTransfer retention sweep (#997): expire links, notify admins, and
|
||||
// hard-delete client uploads once the grace window elapses.
|
||||
startTransferCleanup();
|
||||
// Custom-resolution download archives (#858) are disposable renditions —
|
||||
// sweep them once their TTL passes so .download-cache doesn't grow forever.
|
||||
startDownloadJobCleanup();
|
||||
// Reveal-mode scheduler (#838): minutely stamp for scheduled reveals.
|
||||
startRevealScheduler();
|
||||
// CRM invoice scheduler: hourly tick to flush scheduled-send invoices
|
||||
// + run the overdue reminder ladder. No-op when the `bills` feature
|
||||
// flag is OFF (the service short-circuits on empty result sets).
|
||||
@@ -1049,17 +983,6 @@ async function startServer() {
|
||||
logger.warn('built-in workflow seed failed at boot:', err.message);
|
||||
}
|
||||
|
||||
// Self-heal the RBAC catalog: ensure super_admin holds every permission
|
||||
// (the "Admin tracks all" guarantee) and the solo_photographer preset
|
||||
// exists. New perms never need a compensation migration. See
|
||||
// _permissionsBoot.js + project_permission_gating.
|
||||
try {
|
||||
const { seedPermissionsAtBoot } = require('./src/services/_permissionsBoot');
|
||||
await seedPermissionsAtBoot(db, logger);
|
||||
} catch (err) {
|
||||
logger.warn('permissions self-heal failed at boot:', err.message);
|
||||
}
|
||||
|
||||
// Install-from-backup trigger. If `RESTORE_ON_INSTALL` (or
|
||||
// `.txt`) exists in the /backup mount AND the DB is empty, run
|
||||
// the restore HERE before any admin UI surfaces. Lets admins
|
||||
|
||||
@@ -33,13 +33,6 @@ jest.mock('../utils/tokenRevocation', () => ({
|
||||
isTokenRevoked: jest.fn(),
|
||||
}));
|
||||
|
||||
// The global session cutoff (added for .picpeak restore invalidation) queries
|
||||
// app_settings; stub it to "no cutoff" so it doesn't consume this suite's
|
||||
// one-shot db() mock. Its own behaviour is covered by utils/sessionCutoff.test.js.
|
||||
jest.mock('../utils/sessionCutoff', () => ({
|
||||
isTokenBeforeCutoff: jest.fn().mockResolvedValue(false),
|
||||
}));
|
||||
|
||||
jest.mock('../utils/tokenUtils', () => ({
|
||||
getCustomerTokenFromRequest: jest.fn(),
|
||||
}));
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
/**
|
||||
* Emoji reactions (#839): the fixed, curated reaction set. Guests pick ONE
|
||||
* of these per photo (changeable). Kept as a shared constant so the
|
||||
* validator, the service and the export layer can never drift apart.
|
||||
*
|
||||
* Mirrored in frontend/src/services/feedback.service.ts (REACTION_EMOJIS) —
|
||||
* update both together.
|
||||
*/
|
||||
const REACTION_EMOJIS = ['❤️', '😂', '😍', '👏', '🎉'];
|
||||
|
||||
module.exports = { REACTION_EMOJIS };
|
||||
@@ -100,7 +100,7 @@ async function apiTokenAuth(req, res, next) {
|
||||
}
|
||||
|
||||
// Touch last_used_at — async, don't block the request.
|
||||
db('api_tokens').where({ id: row.id }).update({ last_used_at: new Date().toISOString() })
|
||||
db('api_tokens').where({ id: row.id }).update({ last_used_at: new Date() })
|
||||
.catch((err) => logger.debug('api_tokens last_used update failed', { err: err.message }));
|
||||
|
||||
// Same shape adminAuth produces, so requirePermission / ownership helpers
|
||||
|
||||
@@ -3,7 +3,6 @@ const { db } = require('../database/db');
|
||||
const { formatBoolean } = require('../utils/dbCompat');
|
||||
const { isMissingRolesSchema } = require('../utils/dbErrors');
|
||||
const { isTokenRevoked } = require('../utils/tokenRevocation');
|
||||
const { isTokenBeforeCutoff } = require('../utils/sessionCutoff');
|
||||
const logger = require('../utils/logger');
|
||||
const { getAdminTokenFromRequest, getGalleryTokenFromRequest } = require('../utils/tokenUtils');
|
||||
|
||||
@@ -40,13 +39,6 @@ async function adminAuth(req, res, next) {
|
||||
});
|
||||
return res.status(401).json({ error: 'Token has been revoked', code: 'TOKEN_REVOKED' });
|
||||
}
|
||||
|
||||
// Reject any session issued before the global cutoff (set by a .picpeak
|
||||
// restore, which can reassign admin ids). Forces every pre-restore admin
|
||||
// session to re-authenticate against the restored data.
|
||||
if (await isTokenBeforeCutoff(decoded)) {
|
||||
return res.status(401).json({ error: 'Session invalidated', code: 'SESSION_INVALIDATED' });
|
||||
}
|
||||
|
||||
// Verify token type
|
||||
if (decoded.type !== 'admin') {
|
||||
@@ -88,10 +80,9 @@ async function adminAuth(req, res, next) {
|
||||
// the fallback below fabricates super_admin, so a transient query failure
|
||||
// (connection reset, deadlock, statement timeout, pool exhaustion) must
|
||||
// not become a free privilege upgrade for every scoped admin. Rethrow →
|
||||
// outer catch → 401, which is already how every other transient DB fault
|
||||
// in this try block behaves (isTokenRevoked / isTokenBeforeCutoff both
|
||||
// hit the DB here). apiTokenAuth takes the same posture on the v1
|
||||
// surface, differing only in its 500.
|
||||
// outer catch → 401, which is already how a transient DB fault in this
|
||||
// try block behaves (isTokenRevoked hits the DB here). apiTokenAuth takes
|
||||
// the same posture on the v1 surface, differing only in its 500.
|
||||
if (!isMissingRolesSchema(joinError)) throw joinError;
|
||||
// Fallback: roles table may not exist yet during upgrade
|
||||
// Query without role join - user will have no role info but can still authenticate
|
||||
@@ -175,12 +166,7 @@ async function galleryAuth(req, res, next) {
|
||||
if (await isTokenRevoked(decoded)) {
|
||||
return res.status(401).json({ error: 'Session has been invalidated', code: 'TOKEN_REVOKED' });
|
||||
}
|
||||
|
||||
// Reject sessions issued before the global restore cutoff.
|
||||
if (await isTokenBeforeCutoff(decoded)) {
|
||||
return res.status(401).json({ error: 'Session invalidated', code: 'SESSION_INVALIDATED' });
|
||||
}
|
||||
|
||||
|
||||
// Verify token type
|
||||
if (decoded.type !== 'gallery') {
|
||||
return res.status(403).json({ error: 'Invalid access token' });
|
||||
@@ -244,11 +230,6 @@ async function photoAuth(req, res, next) {
|
||||
return res.status(401).json({ error: 'Token has been revoked', code: 'TOKEN_REVOKED' });
|
||||
}
|
||||
|
||||
// Reject sessions issued before the global restore cutoff.
|
||||
if (await isTokenBeforeCutoff(decoded)) {
|
||||
return res.status(401).json({ error: 'Session invalidated', code: 'SESSION_INVALIDATED' });
|
||||
}
|
||||
|
||||
// Allow both admin and gallery tokens
|
||||
if (decoded.type === 'admin') {
|
||||
const admin = await db('admin_users')
|
||||
|
||||
@@ -13,7 +13,6 @@ const jwt = require('jsonwebtoken');
|
||||
const { db } = require('../database/db');
|
||||
const { formatBoolean } = require('../utils/dbCompat');
|
||||
const { isTokenRevoked } = require('../utils/tokenRevocation');
|
||||
const { isTokenBeforeCutoff } = require('../utils/sessionCutoff');
|
||||
const logger = require('../utils/logger');
|
||||
const { getCustomerTokenFromRequest } = require('../utils/tokenUtils');
|
||||
|
||||
@@ -62,11 +61,6 @@ async function customerAuth(req, res, next) {
|
||||
return res.status(401).json({ error: 'Token has been revoked', code: 'TOKEN_REVOKED' });
|
||||
}
|
||||
|
||||
// Reject sessions issued before the global restore cutoff.
|
||||
if (await isTokenBeforeCutoff(decoded)) {
|
||||
return res.status(401).json({ error: 'Session invalidated', code: 'SESSION_INVALIDATED' });
|
||||
}
|
||||
|
||||
if (decoded.type !== 'customer') {
|
||||
logger.warn('[customerAuth] wrong token type', {
|
||||
url: req.originalUrl,
|
||||
|
||||
@@ -34,26 +34,20 @@ async function getRateLimitSettings() {
|
||||
.where('setting_key', 'feedback_rate_limits')
|
||||
.first();
|
||||
|
||||
// Defaults FIRST, stored values override: persisted rows predate newer
|
||||
// action types (`reaction`, #839) — returning the stored object alone
|
||||
// would silently drop their intended defaults to the generic 100/h.
|
||||
const defaults = {
|
||||
if (settings && settings.setting_value) {
|
||||
// setting_value is already a JSON object in PostgreSQL
|
||||
return typeof settings.setting_value === 'string'
|
||||
? JSON.parse(settings.setting_value)
|
||||
: settings.setting_value;
|
||||
}
|
||||
|
||||
// Default settings
|
||||
return {
|
||||
rating: { max: 100, window: 3600 }, // 100 ratings per hour
|
||||
comment: { max: 20, window: 3600 }, // 20 comments per hour
|
||||
like: { max: 200, window: 3600 }, // 200 likes per hour
|
||||
favorite: { max: 100, window: 3600 }, // 100 favorites per hour
|
||||
reaction: { max: 200, window: 3600 } // reactions churn like likes (#839)
|
||||
favorite: { max: 100, window: 3600 } // 100 favorites per hour
|
||||
};
|
||||
|
||||
if (settings && settings.setting_value) {
|
||||
// setting_value is already a JSON object in PostgreSQL
|
||||
const stored = typeof settings.setting_value === 'string'
|
||||
? JSON.parse(settings.setting_value)
|
||||
: settings.setting_value;
|
||||
return { ...defaults, ...stored };
|
||||
}
|
||||
|
||||
return defaults;
|
||||
} catch (error) {
|
||||
logger.error('Error getting rate limit settings:', error);
|
||||
// Return defaults on error
|
||||
@@ -61,8 +55,7 @@ async function getRateLimitSettings() {
|
||||
rating: { max: 100, window: 3600 },
|
||||
comment: { max: 20, window: 3600 },
|
||||
like: { max: 200, window: 3600 },
|
||||
favorite: { max: 100, window: 3600 },
|
||||
reaction: { max: 200, window: 3600 }
|
||||
favorite: { max: 100, window: 3600 }
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,75 +4,22 @@ const { formatBoolean } = require('../utils/dbCompat');
|
||||
const { getGalleryTokenFromRequest } = require('../utils/tokenUtils');
|
||||
const logger = require('../utils/logger');
|
||||
|
||||
/**
|
||||
* True when a logged-in admin is explicitly previewing this gallery (#868).
|
||||
*
|
||||
* Two conditions, both required:
|
||||
* 1. The explicit intent flag `?admin_preview=1` is present. The plain share
|
||||
* link stays byte-identical to a guest's, so the password gate is still
|
||||
* testable as a guest while logged in as admin — and the bypass is visible
|
||||
* in the URL without being reusable (it carries no secret).
|
||||
* 2. A VERIFIED admin session — the httpOnly `admin_token` cookie (rides along
|
||||
* on same-origin API calls) or an Authorization: Bearer header, never the
|
||||
* URL. Must decode as `type: 'admin'`, issuer `picpeak-auth`.
|
||||
*
|
||||
* The cookie is tried FIRST and the Bearer is accepted only when it is itself an
|
||||
* admin token (#981 review): the frontend attaches a gallery Bearer to gallery
|
||||
* endpoints, and a header-first, type-blind read would let a coexisting gallery
|
||||
* session shadow the admin cookie and wrongly disable the preview.
|
||||
*
|
||||
* Fails closed on any verification error. Replaces the old `?preview=<raw-JWT>`
|
||||
* scheme, which leaked a 24h admin token into the address bar.
|
||||
*/
|
||||
// Check if the request carries a valid admin preview token (Feature 3)
|
||||
function isAdminPreview(req) {
|
||||
if (req.query?.admin_preview !== '1') return false;
|
||||
// Cookie first, then a Bearer — but only an admin-typed token satisfies it.
|
||||
const candidates = [];
|
||||
if (req.cookies?.admin_token) candidates.push(req.cookies.admin_token);
|
||||
const header = req.headers?.authorization;
|
||||
if (header && header.startsWith('Bearer ')) candidates.push(header.slice(7));
|
||||
for (const token of candidates) {
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET, { issuer: 'picpeak-auth' });
|
||||
if (decoded.type === 'admin') return true;
|
||||
} catch { /* try the next candidate */ }
|
||||
const previewToken = req.query?.preview;
|
||||
if (!previewToken) return false;
|
||||
try {
|
||||
const decoded = jwt.verify(previewToken, process.env.JWT_SECRET, { issuer: 'picpeak-auth' });
|
||||
return decoded.type === 'admin';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Middleware to verify gallery access
|
||||
async function verifyGalleryAccess(req, res, next) {
|
||||
try {
|
||||
const requestedSlug = req.params.slug || req.requestedSlug;
|
||||
|
||||
// Admin preview (#868) is resolved BEFORE any gallery credential (#981
|
||||
// review): a coexisting gallery token/Bearer must not shadow it, and the
|
||||
// admin session must never fall into the `type !== 'gallery'` reject path
|
||||
// below. Per-request bypass — draft + password relaxed, NO gallery JWT
|
||||
// minted (a lingering guest cookie would muddy the coexisting-cookies case).
|
||||
// req.isAdminPreview flags downstream logging to keep it out of guest stats.
|
||||
if (isAdminPreview(req)) {
|
||||
if (!requestedSlug) {
|
||||
return res.status(401).json({ error: 'No token provided' });
|
||||
}
|
||||
const previewEvent = await withRetry(async () => db('events')
|
||||
.where({ slug: requestedSlug, is_active: formatBoolean(true), is_archived: formatBoolean(false) })
|
||||
.select('*').first());
|
||||
if (!previewEvent) {
|
||||
return res.status(404).json({ error: 'Gallery not found or expired' });
|
||||
}
|
||||
req.event = previewEvent;
|
||||
req.isAdminPreview = true;
|
||||
req.sessionID = `gallery_admin_preview_${previewEvent.id}`;
|
||||
req.clientInfo = {
|
||||
ip: req.ip || req.connection.remoteAddress || 'unknown',
|
||||
userAgent: req.get('User-Agent') || 'unknown',
|
||||
fingerprint: `${req.ip}-${req.get('User-Agent')}`.substring(0, 32),
|
||||
timestamp: Date.now()
|
||||
};
|
||||
return next();
|
||||
}
|
||||
|
||||
const token = getGalleryTokenFromRequest(req, requestedSlug);
|
||||
let event;
|
||||
|
||||
@@ -81,14 +28,19 @@ async function verifyGalleryAccess(req, res, next) {
|
||||
return res.status(401).json({ error: 'No token provided' });
|
||||
}
|
||||
|
||||
event = await withRetry(async () => db('events')
|
||||
.where({
|
||||
slug: requestedSlug,
|
||||
is_active: formatBoolean(true),
|
||||
is_archived: formatBoolean(false),
|
||||
is_draft: formatBoolean(false)
|
||||
})
|
||||
.select('*').first());
|
||||
const adminPreview = isAdminPreview(req);
|
||||
event = await withRetry(async () => {
|
||||
const q = db('events')
|
||||
.where({
|
||||
slug: requestedSlug,
|
||||
is_active: formatBoolean(true),
|
||||
is_archived: formatBoolean(false)
|
||||
});
|
||||
if (!adminPreview) {
|
||||
q.where({ is_draft: formatBoolean(false) });
|
||||
}
|
||||
return await q.select('*').first();
|
||||
});
|
||||
|
||||
if (!event) {
|
||||
return res.status(404).json({ error: 'Gallery not found or expired' });
|
||||
@@ -109,7 +61,7 @@ async function verifyGalleryAccess(req, res, next) {
|
||||
|
||||
return res.status(401).json({ error: 'No token provided' });
|
||||
}
|
||||
|
||||
|
||||
// Try to verify with issuer first, fallback to no issuer for backward compatibility
|
||||
let decoded;
|
||||
try {
|
||||
@@ -137,34 +89,42 @@ async function verifyGalleryAccess(req, res, next) {
|
||||
return res.status(403).json({ error: 'Invalid token type for gallery access' });
|
||||
}
|
||||
|
||||
// If we have a slug in the URL params or from pre-middleware, verify it matches.
|
||||
// (Admin preview never reaches here — it returns above — so drafts stay
|
||||
// filtered for every real gallery-token request.)
|
||||
// If we have a slug in the URL params or from pre-middleware, verify it matches
|
||||
if (requestedSlug) {
|
||||
// Verify by slug and ensure it matches the token's event
|
||||
event = await withRetry(async () => db('events')
|
||||
.where({
|
||||
slug: requestedSlug,
|
||||
is_active: formatBoolean(true),
|
||||
is_archived: formatBoolean(false),
|
||||
is_draft: formatBoolean(false)
|
||||
})
|
||||
.select('*').first());
|
||||
|
||||
const adminPreviewToken = isAdminPreview(req);
|
||||
event = await withRetry(async () => {
|
||||
const q = db('events')
|
||||
.where({
|
||||
slug: requestedSlug,
|
||||
is_active: formatBoolean(true),
|
||||
is_archived: formatBoolean(false)
|
||||
});
|
||||
if (!adminPreviewToken) {
|
||||
q.where({ is_draft: formatBoolean(false) });
|
||||
}
|
||||
return await q.select('*').first();
|
||||
});
|
||||
|
||||
// Verify the token's eventId matches
|
||||
if (event && event.id !== decoded.eventId) {
|
||||
return res.status(403).json({ error: 'Token does not match requested gallery' });
|
||||
}
|
||||
} else {
|
||||
// Fallback to using eventId from token
|
||||
event = await withRetry(async () => db('events')
|
||||
.where({
|
||||
id: decoded.eventId,
|
||||
is_active: formatBoolean(true),
|
||||
is_archived: formatBoolean(false),
|
||||
is_draft: formatBoolean(false)
|
||||
})
|
||||
.select('*').first());
|
||||
const adminPreviewFallback = isAdminPreview(req);
|
||||
event = await withRetry(async () => {
|
||||
const q = db('events')
|
||||
.where({
|
||||
id: decoded.eventId,
|
||||
is_active: formatBoolean(true),
|
||||
is_archived: formatBoolean(false)
|
||||
});
|
||||
if (!adminPreviewFallback) {
|
||||
q.where({ is_draft: formatBoolean(false) });
|
||||
}
|
||||
return await q.select('*').first();
|
||||
});
|
||||
}
|
||||
|
||||
if (!event) {
|
||||
@@ -204,11 +164,6 @@ async function verifyGalleryAccess(req, res, next) {
|
||||
logger.debug('[verifyGalleryAccess] Event located', { eventId: event.id, slug: event.slug });
|
||||
req.event = event;
|
||||
req.accessLevel = decoded.accessLevel || 'guest';
|
||||
// Customer-portal provenance (#746/#849): portal-minted tokens carry
|
||||
// via:'customer' but NO accessLevel (they default to guest), while
|
||||
// PIN-client logins carry accessLevel:'client' without `via`. Activity
|
||||
// attribution/dedup needs the distinction, so surface it explicitly.
|
||||
req.viaCustomer = decoded.via === 'customer';
|
||||
req.sessionID = decoded.sessionId || `gallery_${event.id}_${Date.now()}`;
|
||||
|
||||
// Create client info for logging (similar to secureImageMiddleware but simpler)
|
||||
|
||||
@@ -73,15 +73,6 @@ async function maintenanceMiddleware(req, res, next) {
|
||||
// entries here matched nothing, which is exactly why the lockout happened).
|
||||
const skipPaths = [
|
||||
'/api/auth/admin/login',
|
||||
// The second factor is part of the same login — without this, any
|
||||
// MFA-enrolled admin gets a 503 on the verify step and cannot sign in
|
||||
// at all while maintenance mode is on.
|
||||
'/api/auth/admin/login/mfa',
|
||||
// SSO variants of the admin login (#798) — same reasoning: an SSO-only
|
||||
// (JIT-provisioned) admin has no password, so blocking these would make
|
||||
// maintenance mode admin-proof for them.
|
||||
'/api/auth/admin/sso/login',
|
||||
'/api/auth/admin/sso/callback',
|
||||
'/api/auth/session',
|
||||
'/api/public/settings',
|
||||
'/health'
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user