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 |
+1
-32
@@ -5,10 +5,7 @@
|
||||
.env.*
|
||||
docker-compose*.yml
|
||||
.DS_Store
|
||||
# **/ so backend/node_modules and frontend/node_modules are excluded too —
|
||||
# the root-context Dockerfile.aio COPYs those directories and must get its
|
||||
# deps from its builder stages, never from the host checkout.
|
||||
**/node_modules
|
||||
node_modules
|
||||
npm-debug.log
|
||||
coverage
|
||||
.nyc_output
|
||||
@@ -21,31 +18,3 @@ storage/events/archived/*
|
||||
storage/thumbnails/*
|
||||
data/*.db
|
||||
logs/*
|
||||
|
||||
# Dockerfile.aio builds from the REPOSITORY ROOT and Docker reads only this
|
||||
# file — backend/.dockerignore is never consulted — so the unprefixed rules
|
||||
# above miss backend/data, backend/logs and backend/storage. A checkout that has
|
||||
# been used to run PicPeak would otherwise bake its database, photos, logs and
|
||||
# SETUP_TOKEN into a published image layer.
|
||||
# backend/data wholesale, not a suffix list. It holds only runtime state and is
|
||||
# gitignored in full (.gitignore: `data/`), while suffix rules kept letting real
|
||||
# secrets through: a used checkout here carries ADMIN_CREDENTIALS.txt alongside
|
||||
# the database, plus -journal files and any DATABASE_PATH that does not end in
|
||||
# .db. Any of those in a published layer is a credential leak.
|
||||
backend/data
|
||||
backend/logs
|
||||
backend/storage
|
||||
|
||||
# Same root-context trap, one level deeper: the `.env`, `.env.*` and `data/*.db`
|
||||
# rules above are unanchored only in appearance — Docker matches them against the
|
||||
# path from the build context, so they catch `./.env` and never `backend/.env`.
|
||||
# A checkout that has been used to run PicPeak locally keeps its JWT_SECRET,
|
||||
# DB_PASSWORD and SMTP credentials there, and `COPY backend/ .` puts the file at
|
||||
# /app/.env in the published layer. Match at any depth instead, the way
|
||||
# **/node_modules above already does.
|
||||
**/.env
|
||||
**/.env.*
|
||||
**/*.db
|
||||
**/*.db-journal
|
||||
**/*.sqlite*
|
||||
frontend/dist
|
||||
|
||||
+13
-87
@@ -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)
|
||||
@@ -73,32 +65,21 @@ DB_NAME=picpeak_prod
|
||||
#ADMIN_EMAIL=admin@yourdomain.com
|
||||
#ADMIN_PASSWORD=your_secure_admin_password_here
|
||||
|
||||
# Email Configuration — OPTIONAL, and normally left alone.
|
||||
# SMTP is configured in the setup wizard / Settings -> Email and stored in the
|
||||
# database (email_configs); that is what the mail queue actually sends with.
|
||||
# These variables are a legacy path kept for config-as-code deployments: when
|
||||
# SMTP_HOST is set, the initial migration seeds the database row from it.
|
||||
# Developers running the `dev` compose profile want SMTP_HOST=mailhog here so
|
||||
# that seed points at the mailhog container.
|
||||
# Email Configuration
|
||||
# For Gmail: use app-specific password
|
||||
# For SendGrid: SMTP_USER=apikey, SMTP_PASS=your-api-key
|
||||
#SMTP_HOST=smtp.gmail.com
|
||||
#SMTP_PORT=587
|
||||
#SMTP_SECURE=false
|
||||
#SMTP_USER=your-email@gmail.com
|
||||
#SMTP_PASS=your-app-specific-password
|
||||
#EMAIL_FROM=noreply@yourdomain.com
|
||||
SMTP_HOST=smtp.gmail.com
|
||||
SMTP_PORT=587
|
||||
SMTP_SECURE=false
|
||||
SMTP_USER=your-email@gmail.com
|
||||
SMTP_PASS=your-app-specific-password
|
||||
EMAIL_FROM=noreply@yourdomain.com
|
||||
|
||||
# Application URLs — OPTIONAL. Leave unset for the normal install.
|
||||
# The public origin is captured by the setup wizard (it proposes the address
|
||||
# you opened the browser at) and stored as the `general_site_url` setting, so
|
||||
# you can change it later in Settings -> General without touching this file.
|
||||
# Setting FRONTEND_URL here OVERRIDES that setting and makes the field
|
||||
# read-only in the admin UI - use it only for config-as-code deployments.
|
||||
# Application URLs
|
||||
# Use full origin with scheme, no trailing slash.
|
||||
# Admin UI is served by the frontend at /admin.
|
||||
#FRONTEND_URL=https://yourdomain.com
|
||||
#ADMIN_URL=https://yourdomain.com
|
||||
FRONTEND_URL=https://yourdomain.com
|
||||
ADMIN_URL=https://yourdomain.com
|
||||
|
||||
# Static HTML title + description used for social link previews when the
|
||||
# fetcher doesn't trigger the per-event OG endpoint — most notably the
|
||||
@@ -111,10 +92,9 @@ BRAND_TITLE=PicPeak
|
||||
BRAND_DESCRIPTION=Photo gallery shared with PicPeak.
|
||||
|
||||
# API URL for email assets (logos, images in notification emails)
|
||||
# OPTIONAL: when unset this is derived from the resolved public origin + /api,
|
||||
# so the wizard's answer covers it. Set it only for split-origin deployments
|
||||
# where the API lives on a different host than the gallery.
|
||||
#API_URL=https://yourdomain.com/api
|
||||
# This must be the publicly accessible URL where email recipients can load images.
|
||||
# If not set, defaults to http://localhost:3001 which will show broken images in emails.
|
||||
API_URL=https://yourdomain.com/api
|
||||
|
||||
# Frontend API base
|
||||
# For pre-built images and production behind a reverse proxy, keep '/api'.
|
||||
@@ -127,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)
|
||||
@@ -235,55 +210,6 @@ LOGS=./logs
|
||||
# attempts is exponential: 1m, 5m, 30m, 2h, 12h.
|
||||
# WEBHOOK_MAX_ATTEMPTS=5
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Face recognition — "People in this gallery" (#1074, optional)
|
||||
# -----------------------------------------------------------------------------
|
||||
# Requires the optional picpeak-ml sidecar container:
|
||||
# docker compose --profile faces up -d
|
||||
#
|
||||
# NONE of these variables do anything until the `faces` feature flag is
|
||||
# enabled in Admin → Settings, AND the per-event "Detect people in this
|
||||
# gallery" toggle is switched on. Both default to OFF. With the flag off the
|
||||
# backend never contacts the sidecar, so leaving these at their defaults on an
|
||||
# install without the container is completely inert.
|
||||
#
|
||||
# Face embeddings are biometric data (GDPR Art. 9 special category in the EU).
|
||||
# The photographer is the controller and needs a lawful basis for the people
|
||||
# in their photos — see docs/feature-face-recognition.md before enabling.
|
||||
#
|
||||
# NOT AVAILABLE ON THE ALL-IN-ONE IMAGE. The single-container build sets
|
||||
# PICPEAK_SINGLE_CONTAINER=true and the backend refuses to enable face
|
||||
# recognition there regardless of these variables or the feature flag: that
|
||||
# image runs the backend, frontend, database and every worker in one
|
||||
# container, with no ML sidecar to talk to, and face detection would compete
|
||||
# with image processing for the same CPU and memory. Use the standard
|
||||
# multi-container deployment if you want this feature.
|
||||
#
|
||||
# FACE_ML_TOKEN (no default — REQUIRED to run the sidecar)
|
||||
# Shared secret between the backend and the sidecar. The sidecar refuses to
|
||||
# start without it rather than serving anonymously, so an accidentally
|
||||
# published port is never a free face-detection API. Generate with:
|
||||
# openssl rand -hex 32
|
||||
# FACE_ML_TOKEN=
|
||||
#
|
||||
# FACE_ML_URL (default: http://picpeak-ml:8000)
|
||||
# Defaults to the sidecar's compose service name, so the standard
|
||||
# deployment needs no configuration here. Only change it if you run the
|
||||
# sidecar outside the default compose network.
|
||||
# FACE_ML_URL=http://picpeak-ml:8000
|
||||
#
|
||||
# FACE_PROCESSOR_CONCURRENCY (default: 1)
|
||||
# Face-detection workers in the backend. Defaults to 1 deliberately: face
|
||||
# scanning shares a host with Sharp image processing, which is the real
|
||||
# memory pressure (see UPLOAD_PROCESSOR_CONCURRENCY). Raise only on hosts
|
||||
# with headroom to spare.
|
||||
# FACE_PROCESSOR_CONCURRENCY=1
|
||||
#
|
||||
# FACE_ORT_THREADS (default: 1)
|
||||
# ONNX Runtime threads inside the sidecar. More threads mean faster
|
||||
# per-photo inference and higher RSS.
|
||||
# FACE_ORT_THREADS=1
|
||||
|
||||
# Note on FRONTEND_API_URL (documentation only):
|
||||
# When using pre-built frontend images, runtime env vars cannot override the built JS.
|
||||
# Do NOT rely on FRONTEND_API_URL in Compose. Instead, keep VITE_API_URL=/api and
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
# picpeak — All-in-one
|
||||
|
||||
**picpeak** is an open-source, self-hosted **photo-sharing platform for photographers**, with an optional CRM / accounting suite. This image is the **all-in-one** build: the backend, the built web UI and SQLite in **one container, one process** — no compose file, no separate database, no reverse proxy to wire up.
|
||||
|
||||
- 📦 **Source, docs & issues:** https://github.com/PicPeak/picpeak
|
||||
- 🧩 **Multi-container images:** [`picpeak/backend`](https://hub.docker.com/r/picpeak/backend) + [`picpeak/frontend`](https://hub.docker.com/r/picpeak/frontend)
|
||||
|
||||
## Supported tags
|
||||
- `latest` / `stable` — latest stable release
|
||||
- `x.y.z` — a pinned release (**recommended for production**)
|
||||
- `beta` / `main` — latest build from `main` (may be unstable)
|
||||
- **Architectures:** `linux/amd64`, `linux/arm64` (x86 and ARM NAS)
|
||||
|
||||
## Quick start
|
||||
|
||||
docker run -d --name picpeak -p 3000:3000 \
|
||||
-v picpeak:/data \
|
||||
-e JWT_SECRET="$(openssl rand -base64 48)" \
|
||||
picpeak/aio:stable
|
||||
|
||||
Then open **http://localhost:3000/admin** and complete the setup wizard. Read the one-time setup token with:
|
||||
|
||||
docker exec picpeak cat /data/db/SETUP_TOKEN
|
||||
|
||||
> 🔗 Share links need to know your address. The image defaults `FRONTEND_URL` to `http://localhost:3000`; pass `-e FRONTEND_URL=https://photos.example.com` (or set the site URL in Settings) before you send a gallery to a client.
|
||||
|
||||
## Ports & volumes
|
||||
- Container port **3000** (HTTP; put your own TLS terminator in front for public use).
|
||||
- **One volume: `/data`** — back it up and you have backed up the install.
|
||||
- `/data/db` — `picpeak.db` and `SETUP_TOKEN`
|
||||
- `/data/storage` — originals, thumbnails, archives
|
||||
- `/data/logs`, `/data/backup`
|
||||
|
||||
## External Postgres
|
||||
SQLite is this image's default, not its only option. Point it at an existing database exactly like the backend image:
|
||||
|
||||
-e DATABASE_CLIENT=pg -e DB_HOST=… -e DB_USER=… -e DB_PASSWORD=…
|
||||
|
||||
## How it differs from the compose stack
|
||||
- **SQLite takes one writer at a time** — right for a home server, a NAS or a single studio; the compose stack with PostgreSQL is what scales.
|
||||
- **No Redis** — background jobs run in-process.
|
||||
- **Face recognition is unavailable** here. It needs the separate [`picpeak/ml`](https://hub.docker.com/r/picpeak/ml) sidecar, and a second image-processing pipeline competing with thumbnailing for one container's CPU would just make the install slow. Run the multi-container deployment for that feature.
|
||||
|
||||
You can move to the full stack later without reinstalling: take a `.picpeak` backup and restore it there.
|
||||
|
||||
## Docs
|
||||
Volume layout, the external-Postgres variant, TLS, updates and the limits: **https://docs.picpeak.app/deployment/single-container**
|
||||
@@ -1,56 +0,0 @@
|
||||
# picpeak — ML sidecar (face detection)
|
||||
|
||||
**picpeak** is an open-source, self-hosted **photo-sharing platform for photographers**. This image is the **optional face-detection sidecar**: it detects faces in one image and returns a bounding box, five landmarks, quality signals and a 512-d embedding per face.
|
||||
|
||||
**Nothing else.** No database, no volumes, no state, no egress, no model download at runtime. Clustering, person identity, thresholds and every privacy decision live in the picpeak backend, where the data already is — this service forgets each image the moment it answers.
|
||||
|
||||
If you don't run this container, the feature does not exist.
|
||||
|
||||
- 📦 **Source, docs & issues:** https://github.com/PicPeak/picpeak
|
||||
- 🧩 **Runs with:** [`picpeak/backend`](https://hub.docker.com/r/picpeak/backend) + [`picpeak/frontend`](https://hub.docker.com/r/picpeak/frontend)
|
||||
|
||||
## Supported tags
|
||||
- `latest` / `stable` — latest stable release
|
||||
- `x.y.z` — a pinned release (**recommended for production** — keep it on the **same** tag as the backend)
|
||||
- `beta` / `main` — latest build from `main` (may be unstable)
|
||||
- **Architectures:** `linux/amd64`, `linux/arm64`
|
||||
|
||||
> The sidecar's API contract is versioned with the backend that calls it, so `PICPEAK_CHANNEL` resolves the same string across all picpeak images.
|
||||
|
||||
## Turning it on
|
||||
The maintained compose file already contains this service behind a profile — you do not write it by hand:
|
||||
|
||||
docker compose --profile faces up -d
|
||||
|
||||
Then two deliberate actions in the app, neither of which is installing this container:
|
||||
|
||||
1. Enable the **`faces`** feature flag in admin settings.
|
||||
2. Enable **"Detect people in this gallery"** per event.
|
||||
|
||||
**Nothing in the backend touches this service while the flag is off**, so an install without this container never attempts a connection.
|
||||
|
||||
## Configuration
|
||||
| | |
|
||||
|---|---|
|
||||
| `FACE_ML_TOKEN` | **Required.** The container **refuses to start** without it, so an accidentally published port is never a free face-detection API. Must match the backend's `FACE_ML_TOKEN`. |
|
||||
| `FACE_ORT_THREADS` | ONNX Runtime threads (default `1`). |
|
||||
|
||||
Port **8000**, no volumes, no published ports needed — the backend reaches it on the compose network. `FACE_ML_URL` defaults to `http://picpeak-ml:8000` (the compose service name), so the standard deployment needs no URL configuration.
|
||||
|
||||
## API
|
||||
All endpoints except `/health` require the `X-Face-ML-Token` header.
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| `GET /health` | `{"status": "ok"}` — unauthenticated, used by the healthcheck |
|
||||
| `GET /info` | `{detector, embedder, model_version, dim}` |
|
||||
| `POST /faces` | multipart `image` → `{model_version, faces: [...]}` |
|
||||
|
||||
## Models
|
||||
YuNet (detection) + FaceNet-512 (embedding), **both MIT**, baked into the image and verified by SHA-256 at build time — never downloaded at runtime, so airgapped installs work and a model cannot change under a running deployment. See [`ml/LICENSES.md`](https://github.com/PicPeak/picpeak/blob/main/ml/LICENSES.md) for why these and not InsightFace's non-commercial weights.
|
||||
|
||||
## Not available on the all-in-one image
|
||||
[`picpeak/aio`](https://hub.docker.com/r/picpeak/aio) sets `PICPEAK_SINGLE_CONTAINER=true` and the backend refuses to enable face recognition there — a second image-processing pipeline competing with thumbnailing for one small container's CPU would not fail loudly, it would just make the install slow. Run the multi-container deployment for this feature.
|
||||
|
||||
## Docs
|
||||
**https://docs.picpeak.app** · sidecar internals, model conversion and the alignment/threshold contract: [`ml/README.md`](https://github.com/PicPeak/picpeak/blob/main/ml/README.md)
|
||||
@@ -1,8 +1,6 @@
|
||||
# Docker Build and Push Workflow
|
||||
|
||||
This GitHub Actions workflow automatically builds and pushes Docker images for the backend, the frontend, the all-in-one image and the optional ML sidecar to GitHub Container Registry (ghcr.io). On the canonical org repo every one of them is mirrored to Docker Hub as `docker.io/picpeak/{backend,frontend,aio,ml}`; forks build the same images GHCR-only.
|
||||
|
||||
The **all-in-one image** (`<repo>/aio`, built from `Dockerfile.aio` at the repo root, #1042) bundles the backend and the built frontend into a single container with SQLite as the default engine — one `docker run`, no compose. It follows the same per-arch build → digest-merge → per-version tag scheme as the other two images, is mirrored to Docker Hub (`docker.io/picpeak/aio`) alongside GHCR on the canonical org repo, and every PR additionally runs a `smoke-aio` job that boots the image and asserts the SPA shell, brand-title rendering, immutable asset caching, and the SQLite engine resolution.
|
||||
This GitHub Actions workflow automatically builds and pushes Docker images for both the backend and frontend to GitHub Container Registry (ghcr.io).
|
||||
|
||||
## Features
|
||||
|
||||
@@ -12,7 +10,6 @@ The **all-in-one image** (`<repo>/aio`, built from `Dockerfile.aio` at the repo
|
||||
- 🔒 **Security scanning** with Trivy vulnerability scanner
|
||||
- 💾 **Build caching** for faster subsequent builds
|
||||
- 📊 **Build summaries** in GitHub Actions UI
|
||||
- 📝 **Docker Hub pages** for `aio` and `ml` synced from `.github/dockerhub/*.md` on every `main` merge (`dockerhub-descriptions` job). `backend` and `frontend` pages are still hand-maintained in the Hub UI — add `.github/dockerhub/{backend,frontend}.md` with their current text before putting them under the same job.
|
||||
|
||||
## Authentication
|
||||
|
||||
@@ -55,11 +52,6 @@ docker pull ghcr.io/picpeak/picpeak/backend:v1.0.0
|
||||
|
||||
# Pull for specific architecture
|
||||
docker pull --platform linux/arm64 ghcr.io/picpeak/picpeak/backend:latest
|
||||
|
||||
# The same images on Docker Hub (identical tags, identical digests)
|
||||
docker pull picpeak/backend:latest
|
||||
docker pull picpeak/aio:stable
|
||||
docker pull picpeak/ml:stable
|
||||
```
|
||||
|
||||
### Using in Docker Compose
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -28,41 +28,7 @@ permissions:
|
||||
jobs:
|
||||
backend:
|
||||
runs-on: ubuntu-latest
|
||||
# 20, not 10. This job normally finishes in ~3 minutes, but it is the only
|
||||
# one that boots Postgres and runs the full integration suite, so it is the
|
||||
# only one exposed to runner contention — observed spread has reached 9.2
|
||||
# minutes, and a release PR (#1088) was cancelled at 10.3 with every test
|
||||
# passing and jest still running. A cancelled job reads as a red X on a
|
||||
# green branch, which costs a re-run and a diagnosis every time it happens.
|
||||
#
|
||||
# The cap is a runaway guard, not a performance budget; 20 leaves real
|
||||
# headroom over the worst observed run while still killing a hung suite
|
||||
# well inside the hour GitHub would otherwise allow. frontend and ml keep
|
||||
# 10 — they take seconds and have never come close.
|
||||
timeout-minutes: 20
|
||||
|
||||
# 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
|
||||
timeout-minutes: 10
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
@@ -86,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:
|
||||
@@ -124,33 +87,3 @@ jobs:
|
||||
- name: Run Vitest suite
|
||||
working-directory: ./frontend
|
||||
run: npm test -- --run
|
||||
|
||||
# Optional face-detection sidecar (#1074). Runs on every PR regardless of
|
||||
# whether the feature is enabled anywhere — these tests need no model
|
||||
# weights (they stub the pipeline out) and cover the auth boundary, the
|
||||
# request guards and the alignment geometry, which is where a mistake is a
|
||||
# security problem or a silent accuracy problem rather than a visible bug.
|
||||
ml:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
# Matches ml/Dockerfile's base image, so a wheel that resolves here
|
||||
# resolves in the image too.
|
||||
python-version: '3.12'
|
||||
cache: 'pip'
|
||||
cache-dependency-path: ml/requirements.txt
|
||||
|
||||
- name: Install ml deps
|
||||
working-directory: ./ml
|
||||
run: pip install -r requirements.txt pytest httpx
|
||||
|
||||
- name: Run pytest suite
|
||||
working-directory: ./ml
|
||||
run: python -m pytest tests/ -q
|
||||
|
||||
+2
-15
@@ -130,18 +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/
|
||||
|
||||
# Python artifacts — the picpeak-ml sidecar (#1074) is the only Python in
|
||||
# this tree, but bytecode and virtualenvs must never be committed.
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.pytest_cache/
|
||||
ml/.venv/
|
||||
ml/venv/
|
||||
# Locally produced model weights. The image fetches these by pinned URL and
|
||||
# SHA-256 at build time; a 90MB blob must not end up in git history.
|
||||
ml/*.onnx
|
||||
ml/*.h5
|
||||
# Generated CRM/accounting documents (runtime) — never commit
|
||||
backend/storage/business-docs/
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "3.111.1-beta.0"
|
||||
".": "3.83.0-beta.0"
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
{".":"3.44.0"}
|
||||
{".":"3.45.14"}
|
||||
|
||||
+932
-1691
File diff suppressed because it is too large
Load Diff
-178
@@ -1,178 +0,0 @@
|
||||
# All-in-one image (#1042): one container, one Node process.
|
||||
#
|
||||
# The backend serves the built frontend itself via server.js's SERVE_FRONTEND
|
||||
# block (SPA fallback, OG crawler intercept, brand-title render, immutable
|
||||
# asset caching) — no nginx, no supervisor, no bundled Postgres/Redis. SQLite
|
||||
# is the explicit default engine; pointing DB_HOST/DB_USER/DB_PASSWORD (+
|
||||
# DATABASE_CLIENT=pg) at an external Postgres works exactly like the backend
|
||||
# image. Build context is the REPO ROOT (both backend/ and frontend/ are
|
||||
# needed): docker build -f Dockerfile.aio .
|
||||
#
|
||||
# KEEP IN SYNC: the runtime stage below mirrors backend/Dockerfile's
|
||||
# production stage (base image, apk set, npm removal, nodejs user, fontconfig
|
||||
# registration, directory layout, healthcheck, entrypoint). When
|
||||
# backend/Dockerfile changes, change this file too — the aio smoke job in
|
||||
# docker-build.yml catches boot-level drift, not package-level drift.
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Frontend build — mirrors frontend/Dockerfile's builder stage
|
||||
# ---------------------------------------------------------------------------
|
||||
FROM node:22-alpine AS frontend-builder
|
||||
|
||||
ARG CACHEBUST=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY frontend/package*.json ./
|
||||
RUN npm ci --legacy-peer-deps
|
||||
|
||||
COPY frontend/ .
|
||||
RUN npm run build
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Backend deps — mirrors backend/Dockerfile's builder stage
|
||||
# ---------------------------------------------------------------------------
|
||||
FROM node:22-alpine AS backend-builder
|
||||
|
||||
ARG CACHEBUST=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY backend/package*.json ./
|
||||
RUN npm ci --omit=dev
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Runtime — mirrors backend/Dockerfile's production stage + the frontend dist
|
||||
# ---------------------------------------------------------------------------
|
||||
FROM node:22-alpine
|
||||
|
||||
ARG CACHEBUST=1
|
||||
ARG BUILD_DATE
|
||||
ARG VCS_REF
|
||||
ARG VERSION
|
||||
|
||||
LABEL org.opencontainers.image.source="https://github.com/PicPeak/picpeak"
|
||||
LABEL org.opencontainers.image.description="PicPeak all-in-one (backend + frontend, single container)"
|
||||
LABEL org.opencontainers.image.licenses="MIT"
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Explicit engine selection (#1038/#1042): SQLite is this image's DEFAULT
|
||||
# engine — set explicitly, never inferred, and wait-for-db.sh skips its
|
||||
# Postgres readiness wait for it. Point the container at an external Postgres
|
||||
# by overriding DATABASE_CLIENT=pg and setting DB_HOST/DB_USER/DB_PASSWORD,
|
||||
# exactly like the backend image. The boot resolver still logs the engine and
|
||||
# refuses the populated-both conflict.
|
||||
# STORAGE_PATH: getStoragePath() falls back to path.join(__dirname,
|
||||
# '../../../storage') — which resolves to the container-root `/storage` here,
|
||||
# writable by root but EACCES for the nodejs user after the su-exec drop.
|
||||
# Compose masks this by setting STORAGE_PATH=/app/storage; this image must
|
||||
# pin the same path (it is the directory the Dockerfile creates and chowns).
|
||||
ENV NODE_ENV=production \
|
||||
DATABASE_CLIENT=sqlite3
|
||||
|
||||
# See backend/Dockerfile for the rationale of each of the following blocks.
|
||||
RUN echo "cachebust=${CACHEBUST}" && apk upgrade --no-cache
|
||||
|
||||
RUN rm -rf /usr/local/lib/node_modules/npm /usr/local/bin/npm /usr/local/bin/npx
|
||||
|
||||
# sqlite — DatabaseBackupService.createSQLiteBackup() SPAWNS the `sqlite3`
|
||||
# CLI for `.backup` and PRAGMA integrity_check; the npm module does not
|
||||
# ship that binary. backend/Dockerfile omits it because compose always runs
|
||||
# Postgres — this image defaults to SQLite, so without it every database
|
||||
# backup fails with ENOENT.
|
||||
RUN apk add --no-cache dumb-init postgresql-client sqlite ffmpeg su-exec \
|
||||
fontconfig ttf-dejavu ttf-liberation poppler-utils exiftool && \
|
||||
fc-cache -f
|
||||
|
||||
RUN addgroup -g 1001 -S nodejs && adduser -S nodejs -u 1001
|
||||
|
||||
COPY --from=backend-builder --chown=nodejs:nodejs /app/node_modules ./node_modules
|
||||
COPY --chown=nodejs:nodejs backend/ .
|
||||
|
||||
RUN chmod -R a+r /app && chmod +x wait-for-db.sh
|
||||
|
||||
RUN printf '<?xml version="1.0"?>\n<!DOCTYPE fontconfig SYSTEM "fonts.dtd">\n<fontconfig>\n <dir>/app/assets/fonts</dir>\n</fontconfig>\n' > /etc/fonts/conf.d/99-picpeak-fonts.conf && \
|
||||
fc-cache -f /app/assets/fonts
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# One volume, one layout (#1042 scope: "single data layout on one volume")
|
||||
# ---------------------------------------------------------------------------
|
||||
# /data/db picpeak.db (+ -wal/-shm) and SETUP_TOKEN
|
||||
# /data/storage originals, thumbnails, archives
|
||||
# /data/logs application logs
|
||||
# /data/backup built-in backup output; /backup symlinks here
|
||||
#
|
||||
# `-v picpeak:/data` and nothing else to remember — back up /data and you have
|
||||
# backed up the install. /backup is where migrations 029 + 030 seed the backup
|
||||
# destinations, so it is symlinked in rather than left dangling.
|
||||
ENV DATA_ROOT=/data \
|
||||
DATA_DIR=/data/db \
|
||||
DATABASE_PATH=/data/db/picpeak.db \
|
||||
STORAGE_PATH=/data/storage \
|
||||
LOG_DIR=/data/logs \
|
||||
BACKUP_DIR=/data/backup
|
||||
|
||||
# FRONTEND_URL is deliberately NOT set here (#705). It used to default to
|
||||
# http://localhost:3000 so share links would not come out relative, but a
|
||||
# baked-in value OVERRIDES the general_site_url setting the setup wizard
|
||||
# writes — so a single-container install could never configure its own public
|
||||
# address, and the Settings field would show as env-pinned for everyone.
|
||||
# getFrontendBaseUrl() now resolves the setting, then the origin the request
|
||||
# arrived on, and getAbsoluteFrontendUrl() still ends at http://localhost:3000,
|
||||
# so links stay absolute without pinning anything. Override with
|
||||
# -e FRONTEND_URL=https://photos.example.com for config-as-code deployments.
|
||||
|
||||
# /app/storage is a second entrance to the same volume. The business-document
|
||||
# writers (quoteService, invoice sending/reminders, contract signatures) build
|
||||
# their paths from `path.join(process.cwd(), 'storage', ...)` and never consult
|
||||
# STORAGE_PATH. Compose hides that because it sets STORAGE_PATH=/app/storage
|
||||
# with WORKDIR /app, so the two happen to be the same directory; here they are
|
||||
# not, and /app is root-owned, so a quote or invoice PDF would fail to write as
|
||||
# UID 1001 — and be lost with the container even if it succeeded. Teaching
|
||||
# those services STORAGE_PATH is the real fix and belongs in its own change;
|
||||
# the symlink restores the coincidence compose already relies on.
|
||||
RUN mkdir -p /data/db /data/storage/events/active /data/storage/events/archived \
|
||||
/data/storage/thumbnails /data/logs \
|
||||
/data/backup/picpeak /data/backup/database && \
|
||||
ln -s /data/backup /backup && \
|
||||
ln -s /data/storage /app/storage && \
|
||||
chown -R nodejs:nodejs /data
|
||||
|
||||
VOLUME ["/data"]
|
||||
|
||||
# The frontend bundle, served by server.js's SERVE_FRONTEND block. Explicit
|
||||
# opt-in rather than the dist-exists autodetect, so the behavior is pinned
|
||||
# even if the autodetect heuristic ever changes.
|
||||
COPY --from=frontend-builder --chown=nodejs:nodejs /app/dist /app/frontend/dist
|
||||
ENV SERVE_FRONTEND=true \
|
||||
FRONTEND_DIR=/app/frontend/dist
|
||||
|
||||
# Marks this as the single-container build. The backend refuses to enable face
|
||||
# recognition (#1074) when it sees this, on performance grounds: that feature
|
||||
# needs a separate ML container this image does not contain, and it would add
|
||||
# a second image-processing pipeline competing with Sharp for the CPU and
|
||||
# memory of a container sized for one photographer plus guests browsing. The
|
||||
# failure would not be loud — just a slow install that looks broken.
|
||||
#
|
||||
# An explicit marker rather than inferring it from SERVE_FRONTEND or the
|
||||
# SQLite path: legitimate multi-container deployments do both of those, and
|
||||
# none of them should lose the feature by accident.
|
||||
ENV PICPEAK_SINGLE_CONTAINER=true
|
||||
|
||||
# No USER directive — same as backend/Dockerfile: the container starts as root
|
||||
# so wait-for-db.sh can chown bind-mounted volumes to UID 1001, then drops
|
||||
# privileges via su-exec (#484).
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
# Shell form so it resolves $PORT: a hard-coded 3000 marks an otherwise healthy
|
||||
# container unhealthy forever the moment anyone overrides the port.
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \
|
||||
CMD wget --no-verbose --tries=1 --spider "http://localhost:${PORT:-3000}/health" || exit 1
|
||||
|
||||
ENTRYPOINT ["dumb-init", "--"]
|
||||
# --max-http-header-size matches nginx's `large_client_header_buffers 4 32k`.
|
||||
# Requests reach Node directly here, and its 16 KiB default would reject a guest
|
||||
# carrying several per-gallery JWT cookies before Express ever saw them.
|
||||
CMD ["./wait-for-db.sh", "node", "--max-http-header-size=32768", "server.js"]
|
||||
@@ -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,aio,ml}` (and on Docker Hub as `picpeak/{backend,frontend,aio,ml}`) 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,90 +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`:
|
||||
|
||||
### Or: one container, no compose file
|
||||
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.
|
||||
|
||||
For a home server, a NAS, or a single small studio, the all-in-one image runs the whole app as one process with SQLite — no compose file, no separate database, no reverse proxy to wire up:
|
||||
> 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`).
|
||||
|
||||
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).
|
||||
|
||||
**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.
|
||||
|
||||
## 🔄 Release Channels
|
||||
|
||||
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.
|
||||
|
||||
### Stable Channel (Recommended)
|
||||
- Production-ready releases
|
||||
- Thoroughly tested before release
|
||||
- Docker tags: `stable`, `latest`, or specific version like `v2.3.0`
|
||||
|
||||
### 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`
|
||||
|
||||
### Switching Channels
|
||||
|
||||
Set the `PICPEAK_CHANNEL` environment variable in your `.env` file:
|
||||
|
||||
```bash
|
||||
docker run -d --name picpeak -p 3000:3000 \
|
||||
-v picpeak:/data \
|
||||
-e JWT_SECRET="$(openssl rand -base64 48)" \
|
||||
ghcr.io/picpeak/picpeak/aio:main
|
||||
# For stable releases (default)
|
||||
PICPEAK_CHANNEL=stable
|
||||
|
||||
# For beta releases
|
||||
PICPEAK_CHANNEL=beta
|
||||
|
||||
# For a specific version
|
||||
PICPEAK_CHANNEL=v2.3.0
|
||||
```
|
||||
|
||||
Then open **http://localhost:3000/admin** and read the setup token with `docker exec picpeak cat /data/db/SETUP_TOKEN`.
|
||||
Then update your containers:
|
||||
|
||||
`:main` is the active-development tag, and today it is the only one the all-in-one image has — `Dockerfile.aio` landed after the current stable release, so `:stable` and `:latest` first appear for this image once the aio build reaches the `stable` branch. Switch to `:stable` then, or pin a version tag (`3.107.4-beta.0`) if you would rather not track `main`.
|
||||
```bash
|
||||
docker compose -f docker-compose.production.yml pull
|
||||
docker compose -f docker-compose.production.yml up -d
|
||||
```
|
||||
|
||||
The compose stack above is still the right choice for anything busier — SQLite takes one writer at a time, and Postgres is what scales. You can move to it later without reinstalling: take a `.picpeak` backup and restore it into the full stack. See **[Single-container install](https://docs.picpeak.app/deployment/single-container)** for the volume layout, the external-Postgres variant, TLS, and the limits.
|
||||
### Update Notifications
|
||||
|
||||
### Docker images
|
||||
The admin dashboard automatically notifies you when updates are available for your channel. To disable update checks, set:
|
||||
|
||||
| | GHCR | Docker Hub |
|
||||
|---|---|---|
|
||||
| Backend | `ghcr.io/picpeak/picpeak/backend` | [`picpeak/backend`](https://hub.docker.com/r/picpeak/backend) |
|
||||
| Frontend | `ghcr.io/picpeak/picpeak/frontend` | [`picpeak/frontend`](https://hub.docker.com/r/picpeak/frontend) |
|
||||
| All-in-one | `ghcr.io/picpeak/picpeak/aio` | [`picpeak/aio`](https://hub.docker.com/r/picpeak/aio) |
|
||||
| ML sidecar (optional) | `ghcr.io/picpeak/picpeak/ml` | [`picpeak/ml`](https://hub.docker.com/r/picpeak/ml) |
|
||||
|
||||
Both registries get the same digests and the same tags — `stable`/`latest`, a pinned `x.y.z`, and `beta`/`main` for the active development channel — for `linux/amd64` and `linux/arm64`. Keep every image in one install on the **same** tag.
|
||||
|
||||
## 🌟 Why 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
|
||||
- **🌍 Multi-Language** — built-in i18n (EN, DE)
|
||||
|
||||
## ✨ Features
|
||||
|
||||
**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.
|
||||
|
||||
**For clients** — clean mobile-optimized galleries, one-click bulk downloads, smart search, **People in this gallery** face grouping (opt-in per gallery, needs the optional [ML sidecar](ml/README.md)), optional guest uploads, and download protection (watermarking + right-click prevention).
|
||||
|
||||
**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).
|
||||
|
||||
<details>
|
||||
<summary><strong>🧾 For studios — CRM & Accounting (Beta, off by default)</strong></summary>
|
||||
|
||||
- 📝 **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
|
||||
|
||||
</details>
|
||||
|
||||
> [!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
|
||||
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) |
|
||||
| 📦 Single-container install (one `docker run`, SQLite) | [docs.picpeak.app/deployment/single-container](https://docs.picpeak.app/deployment/single-container) |
|
||||
| ⚙️ 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
|
||||
|
||||
@@ -164,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,217 +0,0 @@
|
||||
/**
|
||||
* Auto-category rule engine (#1074 phase 3).
|
||||
*
|
||||
* The rules themselves are simple enough to read. What needs testing is the
|
||||
* promise around them: this engine may only ever fill an EMPTY category, and
|
||||
* everything it touches must be reversible. A photographer's own assignment
|
||||
* is a decision; this is a heuristic, and the heuristic never wins.
|
||||
*/
|
||||
|
||||
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-autocat-')), 'db.sqlite',
|
||||
);
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'autocat-test-secret';
|
||||
|
||||
const { bootCrmDb } = require('./helpers/crmDb');
|
||||
|
||||
let db; let cleanup; let engine;
|
||||
|
||||
async function seedEvent(slug) {
|
||||
const [row] = await db('events').insert({
|
||||
slug,
|
||||
event_type: 'wedding',
|
||||
event_name: slug,
|
||||
event_date: '2026-01-01',
|
||||
host_email: 'h@example.com',
|
||||
admin_email: 'a@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: `${slug}-share`,
|
||||
expires_at: new Date().toISOString(),
|
||||
face_recognition_enabled: true,
|
||||
}).returning('id');
|
||||
return typeof row === 'object' ? row.id : row;
|
||||
}
|
||||
|
||||
/** A scanned photo with `faceCount` faces, each `faceSide` px square. */
|
||||
async function addScannedPhoto(eventId, faceCount, { faceSide = 400, categoryId = null } = {}) {
|
||||
const [p] = await db('photos').insert({
|
||||
event_id: eventId,
|
||||
filename: `${Math.random()}.jpg`,
|
||||
path: '/tmp/x.jpg',
|
||||
type: 'individual',
|
||||
width: 1000,
|
||||
height: 1000,
|
||||
processing_status: 'complete',
|
||||
face_status: 'done',
|
||||
face_count: faceCount,
|
||||
category_id: categoryId,
|
||||
}).returning('id');
|
||||
const photoId = typeof p === 'object' ? p.id : p;
|
||||
|
||||
for (let i = 0; i < faceCount; i++) {
|
||||
await db('photo_faces').insert({
|
||||
photo_id: photoId,
|
||||
event_id: eventId,
|
||||
bbox_x: 10, bbox_y: 10, bbox_w: faceSide, bbox_h: faceSide,
|
||||
det_score: 0.95,
|
||||
model_version: 'test-v1',
|
||||
created_at: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
return photoId;
|
||||
}
|
||||
|
||||
async function enable(on) {
|
||||
const existing = await db('app_settings')
|
||||
.where('setting_key', 'face_auto_categorize_enabled').first();
|
||||
if (existing) {
|
||||
await db('app_settings')
|
||||
.where('setting_key', 'face_auto_categorize_enabled')
|
||||
.update({ setting_value: JSON.stringify(on) });
|
||||
}
|
||||
}
|
||||
|
||||
async function categoryOf(photoId) {
|
||||
const photo = await db('photos').where({ id: photoId }).first();
|
||||
if (!photo.category_id) return null;
|
||||
const cat = await db('photo_categories').where({ id: photo.category_id }).first();
|
||||
return cat?.slug ?? null;
|
||||
}
|
||||
|
||||
describe('faceAutoCategories (#1074 phase 3)', () => {
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
engine = require('../../src/services/faceAutoCategories');
|
||||
await enable(true);
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => { if (cleanup) await cleanup(); });
|
||||
|
||||
describe('rules', () => {
|
||||
it('sorts by face count, and by face size for portraits', async () => {
|
||||
const eventId = await seedEvent('rules');
|
||||
// 400px face in a 1000x1000 frame = 16% of the frame, over the 8% floor.
|
||||
const portrait = await addScannedPhoto(eventId, 1, { faceSide: 400 });
|
||||
const details = await addScannedPhoto(eventId, 0);
|
||||
const small = await addScannedPhoto(eventId, 3);
|
||||
const group = await addScannedPhoto(eventId, 9);
|
||||
|
||||
await engine.categorizeEvent(eventId);
|
||||
|
||||
expect(await categoryOf(details)).toBe('details');
|
||||
expect(await categoryOf(portrait)).toBe('portraits');
|
||||
expect(await categoryOf(small)).toBe('small-groups');
|
||||
expect(await categoryOf(group)).toBe('groups');
|
||||
});
|
||||
|
||||
it('does not call a distant single face a portrait', async () => {
|
||||
// One person in a wide landscape is not a portrait of them. 60px in a
|
||||
// 1000x1000 frame is 0.36% — far below the 8% floor.
|
||||
const eventId = await seedEvent('small-face');
|
||||
const distant = await addScannedPhoto(eventId, 1, { faceSide: 60 });
|
||||
|
||||
await engine.categorizeEvent(eventId);
|
||||
|
||||
expect(await categoryOf(distant)).toBeNull();
|
||||
});
|
||||
|
||||
it('ignores photos that have not been scanned', async () => {
|
||||
const eventId = await seedEvent('unscanned');
|
||||
const [p] = await db('photos').insert({
|
||||
event_id: eventId, filename: 'u.jpg', path: '/tmp/u.jpg', type: 'individual',
|
||||
processing_status: 'complete', face_status: 'pending',
|
||||
}).returning('id');
|
||||
const photoId = typeof p === 'object' ? p.id : p;
|
||||
|
||||
await engine.categorizeEvent(eventId);
|
||||
expect(await categoryOf(photoId)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('the promise', () => {
|
||||
it('NEVER overwrites a category a person chose', async () => {
|
||||
// The single most important behaviour in this file.
|
||||
const eventId = await seedEvent('no-overwrite');
|
||||
const [c] = await db('photo_categories').insert({
|
||||
name: 'Ceremony', slug: 'ceremony', is_global: false, event_id: eventId,
|
||||
created_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
const ceremonyId = typeof c === 'object' ? c.id : c;
|
||||
|
||||
// 9 faces — the rules would call this "groups" if they were allowed to.
|
||||
const claimed = await addScannedPhoto(eventId, 9, { categoryId: ceremonyId });
|
||||
|
||||
await engine.categorizeEvent(eventId);
|
||||
|
||||
expect(await categoryOf(claimed)).toBe('ceremony');
|
||||
const row = await db('photos').where({ id: claimed }).first();
|
||||
expect(row.auto_categorized).toBeFalsy();
|
||||
});
|
||||
|
||||
it('marks only what it assigned, so undo is exact', async () => {
|
||||
const eventId = await seedEvent('undo');
|
||||
const [c] = await db('photo_categories').insert({
|
||||
name: 'Ceremony', slug: 'ceremony-2', is_global: false, event_id: eventId,
|
||||
created_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
const ceremonyId = typeof c === 'object' ? c.id : c;
|
||||
|
||||
const manual = await addScannedPhoto(eventId, 4, { categoryId: ceremonyId });
|
||||
const auto = await addScannedPhoto(eventId, 4);
|
||||
|
||||
await engine.categorizeEvent(eventId);
|
||||
expect(await categoryOf(auto)).toBe('small-groups');
|
||||
|
||||
const result = await engine.undoEvent(eventId);
|
||||
|
||||
expect(result.cleared).toBe(1);
|
||||
// The automatic one is cleared...
|
||||
expect(await categoryOf(auto)).toBeNull();
|
||||
// ...and the photographer's own choice survives untouched.
|
||||
expect(await categoryOf(manual)).toBe('ceremony-2');
|
||||
});
|
||||
|
||||
it('is a no-op while the setting is off', async () => {
|
||||
const eventId = await seedEvent('disabled');
|
||||
const photoId = await addScannedPhoto(eventId, 0);
|
||||
|
||||
await enable(false);
|
||||
const result = await engine.categorizeEvent(eventId);
|
||||
await enable(true);
|
||||
|
||||
expect(result.skipped).toBe(true);
|
||||
expect(await categoryOf(photoId)).toBeNull();
|
||||
});
|
||||
|
||||
it('is idempotent — a second run assigns nothing new', async () => {
|
||||
const eventId = await seedEvent('idempotent');
|
||||
await addScannedPhoto(eventId, 0);
|
||||
await addScannedPhoto(eventId, 7);
|
||||
|
||||
const first = await engine.categorizeEvent(eventId);
|
||||
const second = await engine.categorizeEvent(eventId);
|
||||
|
||||
expect(first.assigned).toBe(2);
|
||||
expect(second.assigned).toBe(0);
|
||||
});
|
||||
|
||||
it('reuses one category per slug rather than creating duplicates', async () => {
|
||||
const eventId = await seedEvent('reuse');
|
||||
await addScannedPhoto(eventId, 0);
|
||||
await addScannedPhoto(eventId, 0);
|
||||
await addScannedPhoto(eventId, 0);
|
||||
|
||||
await engine.categorizeEvent(eventId);
|
||||
|
||||
const details = await db('photo_categories')
|
||||
.where({ slug: 'details' })
|
||||
.where(function () { this.where('event_id', eventId).orWhere('is_global', true); });
|
||||
expect(details).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,325 +0,0 @@
|
||||
/**
|
||||
* Clustering engine (#1074).
|
||||
*
|
||||
* Uses synthetic embeddings with known identities rather than real faces: the
|
||||
* question here is whether the ALGORITHM groups vectors correctly, which is
|
||||
* separable from whether the model produces good vectors. Model quality is
|
||||
* the spike's job.
|
||||
*/
|
||||
|
||||
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-faceclust-')), 'db.sqlite',
|
||||
);
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'faceclust-test-secret';
|
||||
|
||||
const { bootCrmDb } = require('./helpers/crmDb');
|
||||
|
||||
let db; let cleanup; let clustering;
|
||||
|
||||
/** Deterministic unit vector for identity `id`, jittered by `variant`. */
|
||||
function makeEmbedding(id, variant = 0, dim = 64) {
|
||||
const vec = new Float32Array(dim);
|
||||
for (let i = 0; i < dim; i++) {
|
||||
vec[i] = Math.sin((i + 1) * (id + 1) * 0.7) + variant * 0.02 * Math.cos(i * 3.1);
|
||||
}
|
||||
let norm = 0;
|
||||
for (let i = 0; i < dim; i++) norm += vec[i] * vec[i];
|
||||
norm = Math.sqrt(norm);
|
||||
for (let i = 0; i < dim; i++) vec[i] /= norm;
|
||||
return vec;
|
||||
}
|
||||
|
||||
async function seedEvent(slug) {
|
||||
const [row] = await db('events').insert({
|
||||
slug,
|
||||
event_type: 'wedding',
|
||||
event_name: slug,
|
||||
event_date: '2026-01-01',
|
||||
host_email: 'h@example.com',
|
||||
admin_email: 'a@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: `${slug}-share`,
|
||||
expires_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
return typeof row === 'object' ? row.id : row;
|
||||
}
|
||||
|
||||
async function insertFace(eventId, embedding, overrides = {}) {
|
||||
const [p] = await db('photos').insert({
|
||||
event_id: eventId,
|
||||
filename: `${Math.random()}.jpg`,
|
||||
path: '/tmp/x.jpg',
|
||||
type: 'individual',
|
||||
}).returning('id');
|
||||
const photoId = typeof p === 'object' ? p.id : p;
|
||||
|
||||
const row = {
|
||||
photo_id: photoId,
|
||||
event_id: eventId,
|
||||
bbox_x: 0, bbox_y: 0, bbox_w: 200, bbox_h: 200,
|
||||
det_score: 0.99,
|
||||
embedding: clustering.packEmbedding(embedding),
|
||||
model_version: 'test-v1',
|
||||
created_at: new Date().toISOString(),
|
||||
...overrides,
|
||||
};
|
||||
const [f] = await db('photo_faces').insert(row).returning('id');
|
||||
return { ...row, id: typeof f === 'object' ? f.id : f };
|
||||
}
|
||||
|
||||
describe('faceClustering (#1074)', () => {
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
clustering = require('../../src/services/faceClustering');
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => { if (cleanup) await cleanup(); });
|
||||
|
||||
describe('embedding round-trip', () => {
|
||||
it('survives pack/unpack through the BLOB column exactly', async () => {
|
||||
const original = makeEmbedding(1);
|
||||
const eventId = await seedEvent('roundtrip');
|
||||
const face = await insertFace(eventId, original);
|
||||
|
||||
const stored = await db('photo_faces').where({ id: face.id }).first();
|
||||
const restored = clustering.unpackEmbedding(stored.embedding);
|
||||
|
||||
expect(restored).toHaveLength(original.length);
|
||||
for (let i = 0; i < original.length; i++) {
|
||||
expect(restored[i]).toBeCloseTo(original[i], 6);
|
||||
}
|
||||
});
|
||||
|
||||
it('returns null for a corrupt blob rather than throwing', () => {
|
||||
expect(clustering.unpackEmbedding(Buffer.from([1, 2, 3]))).toBeNull();
|
||||
expect(clustering.unpackEmbedding(null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('assignment', () => {
|
||||
it('groups the same identity and separates different ones', async () => {
|
||||
const eventId = await seedEvent('grouping');
|
||||
const faces = [];
|
||||
// Three identities, four shots each, interleaved so assignment order
|
||||
// is not conveniently grouped.
|
||||
for (let variant = 0; variant < 4; variant++) {
|
||||
for (const identity of [1, 2, 3]) {
|
||||
faces.push(await insertFace(eventId, makeEmbedding(identity, variant)));
|
||||
}
|
||||
}
|
||||
|
||||
await clustering.assignFaces(eventId, faces);
|
||||
|
||||
const people = await db('event_people').where({ event_id: eventId });
|
||||
expect(people).toHaveLength(3);
|
||||
|
||||
// Every face of one identity must share a person id.
|
||||
const rows = await db('photo_faces').where({ event_id: eventId }).select('id', 'person_id');
|
||||
const byPerson = new Map();
|
||||
for (const r of rows) {
|
||||
byPerson.set(r.person_id, (byPerson.get(r.person_id) || 0) + 1);
|
||||
}
|
||||
expect([...byPerson.values()].sort()).toEqual([4, 4, 4]);
|
||||
});
|
||||
|
||||
it('leaves low-quality faces unassigned instead of spawning junk people', async () => {
|
||||
const eventId = await seedEvent('quality-floor');
|
||||
const good = await insertFace(eventId, makeEmbedding(5));
|
||||
// Tiny bbox — below the 40px floor.
|
||||
const tiny = await insertFace(eventId, makeEmbedding(6), { bbox_w: 12, bbox_h: 12 });
|
||||
// Weak detection score.
|
||||
const weak = await insertFace(eventId, makeEmbedding(7), { det_score: 0.2 });
|
||||
|
||||
await clustering.assignFaces(eventId, [good, tiny, weak]);
|
||||
|
||||
const rows = await db('photo_faces')
|
||||
.whereIn('id', [good.id, tiny.id, weak.id])
|
||||
.select('id', 'person_id');
|
||||
const map = Object.fromEntries(rows.map((r) => [r.id, r.person_id]));
|
||||
|
||||
expect(map[good.id]).not.toBeNull();
|
||||
// Still stored — they show in "this photo contains" — just unassigned.
|
||||
expect(map[tiny.id]).toBeNull();
|
||||
expect(map[weak.id]).toBeNull();
|
||||
expect(await db('event_people').where({ event_id: eventId })).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('never mixes embedding spaces from different model versions', async () => {
|
||||
const eventId = await seedEvent('model-version');
|
||||
const a = await insertFace(eventId, makeEmbedding(9), { model_version: 'v1' });
|
||||
await clustering.assignFaces(eventId, [a]);
|
||||
|
||||
// Same vector, different model. Comparable numerically, meaningless
|
||||
// semantically — it must NOT join the v1 cluster.
|
||||
const b = await insertFace(eventId, makeEmbedding(9), { model_version: 'v2' });
|
||||
await clustering.assignFaces(eventId, [b]);
|
||||
|
||||
const people = await db('event_people').where({ event_id: eventId });
|
||||
expect(people).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('merge and split', () => {
|
||||
it('merge moves every face and removes the source person', async () => {
|
||||
const eventId = await seedEvent('merge');
|
||||
const f1 = await insertFace(eventId, makeEmbedding(11));
|
||||
const f2 = await insertFace(eventId, makeEmbedding(21));
|
||||
await clustering.assignFaces(eventId, [f1, f2]);
|
||||
|
||||
const people = await db('event_people').where({ event_id: eventId }).orderBy('id');
|
||||
expect(people).toHaveLength(2);
|
||||
|
||||
await clustering.mergePeople(eventId, [people[1].id], people[0].id);
|
||||
|
||||
expect(await db('event_people').where({ event_id: eventId })).toHaveLength(1);
|
||||
const remaining = await db('event_people').where({ event_id: eventId }).first();
|
||||
expect(remaining.face_count_total).toBe(2);
|
||||
const orphaned = await db('photo_faces')
|
||||
.where({ event_id: eventId }).whereNull('person_id');
|
||||
expect(orphaned).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('split pulls the named faces into a new person', async () => {
|
||||
const eventId = await seedEvent('split');
|
||||
const faces = [];
|
||||
for (let v = 0; v < 4; v++) faces.push(await insertFace(eventId, makeEmbedding(13, v)));
|
||||
await clustering.assignFaces(eventId, faces);
|
||||
|
||||
const person = await db('event_people').where({ event_id: eventId }).first();
|
||||
expect(person.face_count_total).toBe(4);
|
||||
|
||||
const newId = await clustering.splitPerson(eventId, person.id, [faces[0].id, faces[1].id]);
|
||||
expect(newId).toBeTruthy();
|
||||
|
||||
const original = await db('event_people').where({ id: person.id }).first();
|
||||
const created = await db('event_people').where({ id: newId }).first();
|
||||
expect(original.face_count_total).toBe(2);
|
||||
expect(created.face_count_total).toBe(2);
|
||||
});
|
||||
|
||||
it('deletes a person left with no faces rather than keeping a ghost', async () => {
|
||||
const eventId = await seedEvent('empty-person');
|
||||
const f = await insertFace(eventId, makeEmbedding(15));
|
||||
await clustering.assignFaces(eventId, [f]);
|
||||
const person = await db('event_people').where({ event_id: eventId }).first();
|
||||
|
||||
await db('photo_faces').where({ id: f.id }).update({ person_id: null });
|
||||
await clustering.recomputeCentroid(person.id);
|
||||
|
||||
expect(await db('event_people').where({ id: person.id }).first()).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('regressions from external review', () => {
|
||||
it('merge carries a name and suppression onto the survivor', async () => {
|
||||
// A merge used to move the faces and delete the source outright, so a
|
||||
// photographer-entered name vanished and a person they had hidden came
|
||||
// back guest-visible.
|
||||
const eventId = await seedEvent('merge-metadata');
|
||||
const a = await insertFace(eventId, makeEmbedding(61));
|
||||
const b = await insertFace(eventId, makeEmbedding(62));
|
||||
await clustering.assignFaces(eventId, [a, b]);
|
||||
|
||||
const [p1, p2] = await db('event_people').where({ event_id: eventId }).orderBy('id');
|
||||
// Target is unnamed and visible; the SOURCE carries the human state.
|
||||
await db('event_people').where({ id: p2.id }).update({ label: 'Anna', is_hidden: true });
|
||||
|
||||
await clustering.mergePeople(eventId, [p2.id], p1.id);
|
||||
|
||||
const survivor = await db('event_people').where({ id: p1.id }).first();
|
||||
expect(survivor.label).toBe('Anna');
|
||||
expect(!!survivor.is_hidden).toBe(true);
|
||||
});
|
||||
|
||||
it('recluster keeps hidden/ignored on people that were never named', async () => {
|
||||
// The old query remembered only rows with a label, so a suppressed
|
||||
// bystander came back visible after one "Re-group people".
|
||||
const eventId = await seedEvent('recluster-suppression');
|
||||
const faces = [];
|
||||
for (let v = 0; v < 3; v++) faces.push(await insertFace(eventId, makeEmbedding(71, v)));
|
||||
await clustering.assignFaces(eventId, faces);
|
||||
|
||||
const person = await db('event_people').where({ event_id: eventId }).first();
|
||||
expect(person.label).toBeNull();
|
||||
await db('event_people').where({ id: person.id }).update({ is_ignored: true });
|
||||
|
||||
await clustering.recluster(eventId);
|
||||
|
||||
const after = await db('event_people').where({ event_id: eventId });
|
||||
expect(after.length).toBeGreaterThan(0);
|
||||
expect(after.every((p) => !!p.is_ignored)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('recluster', () => {
|
||||
it('re-derives clusters and preserves photographer-assigned names', async () => {
|
||||
// This is the property that makes re-clustering safe to offer as a
|
||||
// button: without it, one click silently discards every typed name.
|
||||
const eventId = await seedEvent('recluster');
|
||||
const faces = [];
|
||||
for (let v = 0; v < 3; v++) {
|
||||
faces.push(await insertFace(eventId, makeEmbedding(31, v)));
|
||||
faces.push(await insertFace(eventId, makeEmbedding(32, v)));
|
||||
}
|
||||
await clustering.assignFaces(eventId, faces);
|
||||
|
||||
const people = await db('event_people').where({ event_id: eventId }).orderBy('id');
|
||||
expect(people).toHaveLength(2);
|
||||
await db('event_people').where({ id: people[0].id }).update({ label: 'Anna' });
|
||||
await db('event_people').where({ id: people[1].id }).update({ label: 'Ben' });
|
||||
|
||||
const count = await clustering.recluster(eventId);
|
||||
expect(count).toBe(2);
|
||||
|
||||
const after = await db('event_people').where({ event_id: eventId });
|
||||
const labels = after.map((p) => p.label).filter(Boolean).sort();
|
||||
expect(labels).toEqual(['Anna', 'Ben']);
|
||||
});
|
||||
|
||||
it('is stable across repeated runs', async () => {
|
||||
const eventId = await seedEvent('recluster-stable');
|
||||
const faces = [];
|
||||
for (let v = 0; v < 3; v++) {
|
||||
for (const id of [41, 42]) faces.push(await insertFace(eventId, makeEmbedding(id, v)));
|
||||
}
|
||||
await clustering.assignFaces(eventId, faces);
|
||||
|
||||
const first = await clustering.recluster(eventId);
|
||||
const second = await clustering.recluster(eventId);
|
||||
expect(second).toBe(first);
|
||||
});
|
||||
});
|
||||
|
||||
describe('consolidate', () => {
|
||||
it('refuses to merge two people the photographer named differently', async () => {
|
||||
// A human assertion this heuristic does not get to overrule.
|
||||
const eventId = await seedEvent('consolidate-labels');
|
||||
const a = await insertFace(eventId, makeEmbedding(51));
|
||||
await clustering.assignFaces(eventId, [a]);
|
||||
const first = await db('event_people').where({ event_id: eventId }).first();
|
||||
|
||||
// A near-identical centroid that would otherwise merge.
|
||||
const [inserted] = await db('event_people').insert({
|
||||
event_id: eventId,
|
||||
centroid: clustering.packEmbedding(makeEmbedding(51, 0.01)),
|
||||
face_count_total: 1,
|
||||
model_version: 'test-v1',
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
const secondId = typeof inserted === 'object' ? inserted.id : inserted;
|
||||
|
||||
await db('event_people').where({ id: first.id }).update({ label: 'Anna' });
|
||||
await db('event_people').where({ id: secondId }).update({ label: 'Ben' });
|
||||
|
||||
await clustering.consolidate(eventId);
|
||||
|
||||
expect(await db('event_people').where({ event_id: eventId })).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,239 +0,0 @@
|
||||
/**
|
||||
* External imports are queued for face scanning, in the right order (#1090).
|
||||
*
|
||||
* Managed uploads are enqueued by photoProcessor, which writes face_status
|
||||
* 'pending' once a photo is processed (photoProcessor.js:573 — "the only
|
||||
* correct place to enqueue"). External media never goes through photoProcessor:
|
||||
* adminExternalMedia inserts rows directly, so they stayed NULL and were only
|
||||
* ever picked up by a manual Re-scan.
|
||||
*
|
||||
* The ordering matters as much as the enqueue. events.external_path is written
|
||||
* only AFTER the whole import loop, so marking rows 'pending' as they are
|
||||
* inserted publishes claimable work while the event still points at the old
|
||||
* directory — or none at all, on a first import. The face worker polls
|
||||
* continuously, would resolve those photos against the wrong path, and mark
|
||||
* them permanently 'failed', a state only an explicit Re-scan clears.
|
||||
*
|
||||
* This drives the real route rather than re-implementing it, so removing the
|
||||
* enqueue fails the first test and moving it back onto the insert fails the
|
||||
* second.
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const express = require('express');
|
||||
const request = require('supertest');
|
||||
|
||||
describe('external import queues faces (#1090)', () => {
|
||||
let tmpDir; let db; let app; let mediaRoot;
|
||||
// Recorded from inside the per-photo thumbnail call, i.e. mid-loop.
|
||||
let pendingSeenDuringLoop = 0;
|
||||
let externalPathDuringLoop;
|
||||
// When set to an event id, the mocked thumbnail call turns detection on
|
||||
// mid-loop, standing in for an admin flipping the toggle during an import.
|
||||
let flipFacesOnDuringLoop = null;
|
||||
// Stands in for a concurrent Re-scan completing a row mid-import.
|
||||
let markDoneDuringLoop = false;
|
||||
|
||||
beforeAll(async () => {
|
||||
tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'picpeak-extenq-'));
|
||||
mediaRoot = path.join(tmpDir, 'media');
|
||||
await fs.promises.mkdir(path.join(mediaRoot, 'nas', 'individual'), { recursive: true });
|
||||
for (const name of ['a.jpg', 'b.jpg', 'c.jpg']) {
|
||||
await fs.promises.writeFile(path.join(mediaRoot, 'nas', 'individual', name), 'not-a-real-jpeg');
|
||||
}
|
||||
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.TEST_DATABASE_PATH = path.join(tmpDir, 'data', 'db.sqlite');
|
||||
await fs.promises.mkdir(path.dirname(process.env.TEST_DATABASE_PATH), { recursive: true });
|
||||
process.env.STORAGE_PATH = path.join(tmpDir, 'storage');
|
||||
process.env.EXTERNAL_MEDIA_ROOT = mediaRoot;
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'extenq-secret';
|
||||
|
||||
jest.resetModules();
|
||||
|
||||
jest.doMock('../../src/middleware/auth', () => ({
|
||||
adminAuth: (req, _res, next) => { req.admin = { id: 1, username: 'tester', roleName: 'admin' }; next(); },
|
||||
}));
|
||||
jest.doMock('../../src/middleware/permissions', () => ({
|
||||
requirePermission: () => (_req, _res, next) => next(),
|
||||
}));
|
||||
jest.doMock('../../src/middleware/ownership', () => ({
|
||||
requireEventOwnership: (_req, _res, next) => next(),
|
||||
}));
|
||||
|
||||
// Runs once per photo, inside the import loop — the only hook that can
|
||||
// observe the intermediate state the ordering bug would expose.
|
||||
jest.doMock('../../src/services/imageProcessor', () => ({
|
||||
generateThumbnail: jest.fn(async () => {
|
||||
const { db: liveDb } = require('../../src/database/db');
|
||||
const rows = await liveDb('photos').where({ face_status: 'pending' });
|
||||
pendingSeenDuringLoop += rows.length;
|
||||
const ev = await liveDb('events').first();
|
||||
externalPathDuringLoop = ev ? ev.external_path : undefined;
|
||||
if (markDoneDuringLoop) {
|
||||
const rows = await liveDb('photos').orderBy('id', 'asc').limit(1);
|
||||
if (rows.length) {
|
||||
await liveDb('photos').where({ id: rows[0].id }).update({ face_status: 'done' });
|
||||
}
|
||||
}
|
||||
if (flipFacesOnDuringLoop) {
|
||||
await liveDb('events').where({ id: flipFacesOnDuringLoop })
|
||||
.update({ face_recognition_enabled: true });
|
||||
}
|
||||
return 'thumbnails/mock.jpg';
|
||||
}),
|
||||
ensureThumbnail: jest.fn(),
|
||||
}));
|
||||
|
||||
jest.doMock('../../src/utils/logger', () => ({
|
||||
debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn(),
|
||||
}));
|
||||
|
||||
// bootCrmDb runs every migrations/core/*.up() directly — knex's Migrator
|
||||
// deadlocks on 001_init's nested initializeDatabase() call.
|
||||
({ db } = await require('./helpers/crmDb').bootCrmDb());
|
||||
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api/admin/external-media', require('../../src/routes/adminExternalMedia'));
|
||||
}, 180000);
|
||||
|
||||
afterAll(async () => {
|
||||
if (db) await db.destroy?.();
|
||||
await fs.promises.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
|
||||
});
|
||||
|
||||
async function seedEvent({ facesEnabled, flagOn }) {
|
||||
await db('feature_flags').insert({ key: 'faces', value: flagOn })
|
||||
.onConflict('key').merge()
|
||||
.catch(async () => { await db('feature_flags').where({ key: 'faces' }).update({ value: flagOn }); });
|
||||
// The flag read is TTL-cached (requireFeatureFlag.js:26-34); production
|
||||
// invalidates after every write, and so must this.
|
||||
require('../../src/middleware/requireFeatureFlag').invalidateFeatureFlagCache();
|
||||
|
||||
await db('photos').del();
|
||||
await db('events').del();
|
||||
const [e] = await db('events').insert({
|
||||
slug: `extenq-${Math.random().toString(36).slice(2, 8)}`,
|
||||
event_type: 'wedding',
|
||||
event_name: 'extenq',
|
||||
event_date: '2026-01-01',
|
||||
host_email: 'h@example.com',
|
||||
admin_email: 'a@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: `extenq-${Math.random()}`,
|
||||
expires_at: new Date().toISOString(),
|
||||
face_recognition_enabled: facesEnabled,
|
||||
source_mode: 'reference',
|
||||
}).returning('id');
|
||||
|
||||
pendingSeenDuringLoop = 0;
|
||||
externalPathDuringLoop = undefined;
|
||||
markDoneDuringLoop = false;
|
||||
return typeof e === 'object' ? e.id : e;
|
||||
}
|
||||
|
||||
async function runImport(eventId) {
|
||||
return request(app)
|
||||
.post(`/api/admin/external-media/events/${eventId}/import-external`)
|
||||
.send({ external_path: 'nas', recursive: true });
|
||||
}
|
||||
|
||||
it('queues imported photos when detection is on', async () => {
|
||||
const eventId = await seedEvent({ facesEnabled: true, flagOn: true });
|
||||
|
||||
const res = await runImport(eventId);
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
const photos = await db('photos').where({ event_id: eventId });
|
||||
expect(photos.length).toBeGreaterThan(0);
|
||||
// The regression: these stayed NULL and waited for a manual Re-scan.
|
||||
expect(photos.every((p) => p.face_status === 'pending')).toBe(true);
|
||||
});
|
||||
|
||||
it('does not publish claimable rows before events.external_path is written', async () => {
|
||||
const eventId = await seedEvent({ facesEnabled: true, flagOn: true });
|
||||
|
||||
await runImport(eventId);
|
||||
|
||||
// Observed from inside the loop: nothing is claimable yet. The event path
|
||||
// is already committed (see the test above), so this is no longer load
|
||||
// bearing for correctness — but keeping the enqueue at the end is what lets
|
||||
// the feature setting be read after the loop, so the invariant stays.
|
||||
expect(pendingSeenDuringLoop).toBe(0);
|
||||
|
||||
// ...and afterwards both are in place.
|
||||
const ev = await db('events').where({ id: eventId }).first();
|
||||
expect(ev.external_path).toBe('nas');
|
||||
expect((await db('photos').where({ event_id: eventId, face_status: 'pending' })).length)
|
||||
.toBe((await db('photos').where({ event_id: eventId })).length);
|
||||
});
|
||||
|
||||
it('honours a toggle flipped DURING the import', async () => {
|
||||
// The setting is read after the loop, not before: on a large library the
|
||||
// loop runs for minutes, and the toggle endpoint only queues rows that
|
||||
// already existed when it fired. Reading it up front would strand every
|
||||
// photo imported after that moment at NULL forever.
|
||||
const eventId = await seedEvent({ facesEnabled: false, flagOn: true });
|
||||
flipFacesOnDuringLoop = eventId;
|
||||
|
||||
await runImport(eventId);
|
||||
flipFacesOnDuringLoop = null;
|
||||
|
||||
const photos = await db('photos').where({ event_id: eventId });
|
||||
expect(photos.length).toBeGreaterThan(0);
|
||||
expect(photos.every((p) => p.face_status === 'pending')).toBe(true);
|
||||
});
|
||||
|
||||
it('commits events.external_path before the first row is inserted', async () => {
|
||||
// enqueueEvent accepts processing_status NULL (faceProcessor.js:243-246),
|
||||
// which these inserts leave unset — so a toggle or Re-scan firing mid-import
|
||||
// can queue partial rows. If the event still pointed at the old directory
|
||||
// they would resolve against it and burn to 'failed'. Setting the path
|
||||
// first also means a half-finished import leaves rows that still resolve,
|
||||
// instead of rows stranded against the previous path.
|
||||
const eventId = await seedEvent({ facesEnabled: true, flagOn: true });
|
||||
|
||||
await runImport(eventId);
|
||||
|
||||
// Sampled from inside the per-photo thumbnail call, i.e. while rows are
|
||||
// still being inserted.
|
||||
expect(externalPathDuringLoop).toBe('nas');
|
||||
});
|
||||
|
||||
it('does not re-queue rows a concurrent scan already handled', async () => {
|
||||
// Committing the event path before the loop means a toggle or Re-scan
|
||||
// firing mid-import can now genuinely queue and even finish some of these
|
||||
// rows. A blanket update at the end would drag 'done' rows back to
|
||||
// 'pending' for a duplicate sidecar scan and knock 'processing' rows out
|
||||
// from under the worker.
|
||||
const eventId = await seedEvent({ facesEnabled: true, flagOn: true });
|
||||
markDoneDuringLoop = true;
|
||||
|
||||
await runImport(eventId);
|
||||
markDoneDuringLoop = false;
|
||||
|
||||
const done = await db('photos').where({ event_id: eventId, face_status: 'done' });
|
||||
expect(done.length).toBeGreaterThan(0); // the concurrent scan's work survived
|
||||
});
|
||||
|
||||
it('leaves face_status untouched when the per-event toggle is off', async () => {
|
||||
const eventId = await seedEvent({ facesEnabled: false, flagOn: true });
|
||||
await runImport(eventId);
|
||||
const photos = await db('photos').where({ event_id: eventId });
|
||||
expect(photos.length).toBeGreaterThan(0);
|
||||
expect(photos.every((p) => p.face_status === null)).toBe(true);
|
||||
});
|
||||
|
||||
it('leaves face_status untouched when the global flag is off', async () => {
|
||||
// Installs without the feature must never accumulate face_status rows —
|
||||
// the same invariant photoProcessor's guard protects.
|
||||
const eventId = await seedEvent({ facesEnabled: true, flagOn: false });
|
||||
await runImport(eventId);
|
||||
const photos = await db('photos').where({ event_id: eventId });
|
||||
expect(photos.length).toBeGreaterThan(0);
|
||||
expect(photos.every((p) => p.face_status === null)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,163 +0,0 @@
|
||||
/**
|
||||
* External / reference photos are scannable (#1090).
|
||||
*
|
||||
* faceProcessor used to short-circuit every photo with source_origin
|
||||
* 'external' or 'reference' to 'skipped', because resolvePhotoStorageKey
|
||||
* returns null for anything outside managed storage and ensurePreviewImage
|
||||
* could not build a preview for it. #1078 removed that limitation —
|
||||
* ensurePreviewImage now reads externals straight off the mount and writes
|
||||
* the preview into managed storage — but the guard stayed, so the whole
|
||||
* feature was a no-op on external-media installs. The reporter's gallery sat
|
||||
* at 0/3230 with every row 'skipped' and no error.
|
||||
*
|
||||
* These pin both halves: the guard is gone, and a photo whose source is
|
||||
* genuinely missing still fails rather than being quietly skipped — the blanket
|
||||
* skip used to absorb that case too, so a real breakage looked like an
|
||||
* unsupported one.
|
||||
*/
|
||||
|
||||
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-faceext-')), 'db.sqlite',
|
||||
);
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'faceext-test-secret';
|
||||
// A real, existing media root. getExternalMediaRoot only honours the env var
|
||||
// if the directory exists and caches it on first call, so this has to be set
|
||||
// up before anything requires externalMediaService.
|
||||
process.env.EXTERNAL_MEDIA_ROOT = path.join(path.dirname(process.env.TEST_DATABASE_PATH), 'media');
|
||||
fs.mkdirSync(path.join(process.env.EXTERNAL_MEDIA_ROOT, 'share', 'individual'), { recursive: true });
|
||||
// Non-empty on purpose: an empty directory is read as an unmounted share
|
||||
// (faceTransientSource.test.js), so a "healthy storage, dead photo" fixture
|
||||
// needs a sibling present or it defers instead of failing.
|
||||
fs.writeFileSync(path.join(process.env.EXTERNAL_MEDIA_ROOT, 'share', 'individual', 'sibling.jpg'), 'x');
|
||||
|
||||
const sharp = require('sharp');
|
||||
|
||||
let mockPreviewBuffer;
|
||||
// Set per-test: what ensurePreviewImage returns for the photo under test.
|
||||
let previewKeyResult; // eslint-disable-line prefer-const
|
||||
const mockEnsurePreviewImage = jest.fn(async () => previewKeyResult);
|
||||
const mockDetectFaces = jest.fn();
|
||||
|
||||
jest.mock('../../src/services/imageProcessor', () => ({
|
||||
...jest.requireActual('../../src/services/imageProcessor'),
|
||||
ensurePreviewImage: (...args) => mockEnsurePreviewImage(...args),
|
||||
}));
|
||||
|
||||
jest.mock('../../src/services/storage', () => ({
|
||||
getStorage: () => ({ get: async () => mockPreviewBuffer }),
|
||||
}));
|
||||
|
||||
jest.mock('../../src/services/faceClient', () => ({
|
||||
detectFaces: (...args) => mockDetectFaces(...args),
|
||||
SidecarUnavailableError: class extends Error {},
|
||||
}));
|
||||
|
||||
const { bootCrmDb } = require('./helpers/crmDb');
|
||||
|
||||
let db; let cleanup; let faceProcessor;
|
||||
|
||||
async function seedPhoto({ sourceOrigin = 'managed', sourceMode = 'managed' } = {}) {
|
||||
const [e] = await db('events').insert({
|
||||
slug: `ext-${Math.random().toString(36).slice(2, 8)}`,
|
||||
event_type: 'wedding',
|
||||
event_name: 'ext',
|
||||
event_date: '2026-01-01',
|
||||
host_email: 'h@example.com',
|
||||
admin_email: 'a@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: `ext-${Math.random()}`,
|
||||
expires_at: new Date().toISOString(),
|
||||
face_recognition_enabled: true,
|
||||
source_mode: sourceMode,
|
||||
external_path: 'share',
|
||||
}).returning('id');
|
||||
const eventId = typeof e === 'object' ? e.id : e;
|
||||
|
||||
const [p] = await db('photos').insert({
|
||||
event_id: eventId,
|
||||
filename: 'ext.jpg',
|
||||
path: '/tmp/ext.jpg',
|
||||
type: 'individual',
|
||||
width: 1920,
|
||||
height: 1440,
|
||||
processing_status: 'complete',
|
||||
face_status: 'processing',
|
||||
source_origin: sourceOrigin,
|
||||
external_relpath: sourceOrigin === 'managed' ? null : 'individual/ext.jpg',
|
||||
}).returning('id');
|
||||
return { eventId, photoId: typeof p === 'object' ? p.id : p };
|
||||
}
|
||||
|
||||
describe('face scanning of external/reference photos (#1090)', () => {
|
||||
beforeAll(async () => {
|
||||
mockPreviewBuffer = await sharp({
|
||||
create: { width: 1920, height: 1440, channels: 3, background: { r: 20, g: 40, b: 80 } },
|
||||
}).jpeg().toBuffer();
|
||||
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
await db('feature_flags').insert({ key: 'faces', value: true })
|
||||
.onConflict('key').merge()
|
||||
.catch(async () => { await db('feature_flags').where({ key: 'faces' }).update({ value: true }); });
|
||||
faceProcessor = require('../../src/services/faceProcessor');
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => { if (cleanup) await cleanup(); });
|
||||
|
||||
beforeEach(() => {
|
||||
mockEnsurePreviewImage.mockClear();
|
||||
mockDetectFaces.mockClear();
|
||||
previewKeyResult = 'previews/preview_ext.jpg';
|
||||
mockDetectFaces.mockResolvedValue({
|
||||
model_version: 'test-v1',
|
||||
faces: [{
|
||||
bbox: [100, 100, 50, 50],
|
||||
score: 0.99,
|
||||
landmarks: [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]],
|
||||
yaw: 0, pitch: 0, blur: 500,
|
||||
embedding: Array.from({ length: 64 }, (_, i) => (i === 0 ? 1 : 0)),
|
||||
}],
|
||||
});
|
||||
});
|
||||
|
||||
it.each(['external', 'reference'])('scans a %s photo instead of skipping it', async (origin) => {
|
||||
const { photoId } = await seedPhoto({ sourceOrigin: origin, sourceMode: 'reference' });
|
||||
|
||||
const result = await faceProcessor.processPhotoFaces(photoId);
|
||||
|
||||
// The regression: this used to return 'skipped' without ever building a
|
||||
// preview or contacting the sidecar.
|
||||
expect(result.status).not.toBe('skipped');
|
||||
expect(mockEnsurePreviewImage).toHaveBeenCalled();
|
||||
expect(mockDetectFaces).toHaveBeenCalled();
|
||||
|
||||
const photo = await db('photos').where({ id: photoId }).first();
|
||||
expect(photo.face_status).toBe('done');
|
||||
expect(await db('photo_faces').where({ photo_id: photoId }).first()).toBeTruthy();
|
||||
});
|
||||
|
||||
it('fails, not skips, when the external source is genuinely gone', async () => {
|
||||
// A missing file is a property of that photo, so it should be visible as a
|
||||
// failure the admin can act on — not silently absorbed the way the old
|
||||
// blanket skip did.
|
||||
//
|
||||
// The containing directory exists here on purpose. An absent directory is
|
||||
// a dropped mount, which defers rather than fails
|
||||
// (faceTransientSource.test.js); this is the other case — healthy storage,
|
||||
// dead photo.
|
||||
previewKeyResult = null;
|
||||
const { photoId } = await seedPhoto({ sourceOrigin: 'external', sourceMode: 'reference' });
|
||||
|
||||
const result = await faceProcessor.processPhotoFaces(photoId);
|
||||
|
||||
expect(result.status).toBe('failed');
|
||||
expect(mockDetectFaces).not.toHaveBeenCalled();
|
||||
const photo = await db('photos').where({ id: photoId }).first();
|
||||
expect(photo.face_status).toBe('failed');
|
||||
expect(photo.face_error).toMatch(/preview/i);
|
||||
});
|
||||
});
|
||||
@@ -1,415 +0,0 @@
|
||||
/**
|
||||
* Privacy and visibility guarantees for face recognition (#1074).
|
||||
*
|
||||
* These are the tests that matter most in this feature. Two of them cover
|
||||
* defects that would be invisible in normal use:
|
||||
*
|
||||
* - The people strip is computed from face rows, which have no concept of
|
||||
* photo visibility. Handing a guest a raw count leaks how many hidden
|
||||
* photos someone appears in, and a cover face picked without scoping
|
||||
* renders a crop of a photo the guest may not open.
|
||||
*
|
||||
* - Face embeddings are biometric data. They must not ride along in a
|
||||
* .picpeak export, which gets handed to clients and moved between
|
||||
* operators.
|
||||
*/
|
||||
|
||||
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-faceprivacy-')), 'db.sqlite',
|
||||
);
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'faceprivacy-test-secret';
|
||||
|
||||
const { bootCrmDb } = require('./helpers/crmDb');
|
||||
|
||||
let db; let cleanup; let clustering; let peopleService; let faceProcessor;
|
||||
|
||||
function makeEmbedding(id, variant = 0, dim = 64) {
|
||||
const vec = new Float32Array(dim);
|
||||
for (let i = 0; i < dim; i++) {
|
||||
vec[i] = Math.sin((i + 1) * (id + 1) * 0.7) + variant * 0.02 * Math.cos(i * 3.1);
|
||||
}
|
||||
let norm = 0;
|
||||
for (let i = 0; i < dim; i++) norm += vec[i] * vec[i];
|
||||
norm = Math.sqrt(norm);
|
||||
for (let i = 0; i < dim; i++) vec[i] /= norm;
|
||||
return vec;
|
||||
}
|
||||
|
||||
async function seedEvent(slug) {
|
||||
const [row] = await db('events').insert({
|
||||
slug,
|
||||
event_type: 'wedding',
|
||||
event_name: slug,
|
||||
event_date: '2026-01-01',
|
||||
host_email: 'h@example.com',
|
||||
admin_email: 'a@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: `${slug}-share`,
|
||||
expires_at: new Date().toISOString(),
|
||||
face_recognition_enabled: true,
|
||||
}).returning('id');
|
||||
return typeof row === 'object' ? row.id : row;
|
||||
}
|
||||
|
||||
async function addPhotoWithFace(eventId, embedding, { visibility = 'visible', score = 0.99 } = {}) {
|
||||
const [p] = await db('photos').insert({
|
||||
event_id: eventId,
|
||||
filename: `${Math.random()}.jpg`,
|
||||
path: '/tmp/x.jpg',
|
||||
type: 'individual',
|
||||
visibility,
|
||||
processing_status: 'complete',
|
||||
}).returning('id');
|
||||
const photoId = typeof p === 'object' ? p.id : p;
|
||||
|
||||
const row = {
|
||||
photo_id: photoId,
|
||||
event_id: eventId,
|
||||
bbox_x: 0, bbox_y: 0, bbox_w: 200, bbox_h: 200,
|
||||
det_score: score,
|
||||
embedding: clustering.packEmbedding(embedding),
|
||||
model_version: 'test-v1',
|
||||
created_at: new Date().toISOString(),
|
||||
};
|
||||
const [f] = await db('photo_faces').insert(row).returning('id');
|
||||
return { photoId, face: { ...row, id: typeof f === 'object' ? f.id : f } };
|
||||
}
|
||||
|
||||
describe('face privacy and visibility (#1074)', () => {
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
clustering = require('../../src/services/faceClustering');
|
||||
peopleService = require('../../src/services/facePeopleService');
|
||||
faceProcessor = require('../../src/services/faceProcessor');
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => { if (cleanup) await cleanup(); });
|
||||
|
||||
describe('visibility scoping', () => {
|
||||
it('counts only photos the audience can actually see', async () => {
|
||||
const eventId = await seedEvent('visibility-count');
|
||||
const faces = [];
|
||||
// Same person: 3 visible photos, 4 hidden ones.
|
||||
for (let v = 0; v < 3; v++) {
|
||||
faces.push((await addPhotoWithFace(eventId, makeEmbedding(1, v))).face);
|
||||
}
|
||||
for (let v = 3; v < 7; v++) {
|
||||
faces.push((await addPhotoWithFace(eventId, makeEmbedding(1, v), { visibility: 'hidden' })).face);
|
||||
}
|
||||
await clustering.assignFaces(eventId, faces);
|
||||
|
||||
const guestView = await peopleService.listPeople(eventId, { isClient: false, minClusterSize: 1 });
|
||||
const clientView = await peopleService.listPeople(eventId, { isClient: true, minClusterSize: 1 });
|
||||
|
||||
expect(guestView).toHaveLength(1);
|
||||
// The leak this test exists to prevent: 3, never 7.
|
||||
expect(guestView[0].face_count).toBe(3);
|
||||
expect(clientView[0].face_count).toBe(7);
|
||||
});
|
||||
|
||||
it('never returns face_count_total to a guest', async () => {
|
||||
const eventId = await seedEvent('no-total-leak');
|
||||
const { face } = await addPhotoWithFace(eventId, makeEmbedding(2));
|
||||
await clustering.assignFaces(eventId, [face]);
|
||||
|
||||
const [person] = await peopleService.listPeople(eventId, { isClient: false, minClusterSize: 1 });
|
||||
expect(person).not.toHaveProperty('total_face_count');
|
||||
expect(person).not.toHaveProperty('is_hidden');
|
||||
});
|
||||
|
||||
it('picks a cover face from a photo the guest may open', async () => {
|
||||
const eventId = await seedEvent('cover-scoping');
|
||||
// The BEST face (highest score) is in a hidden photo — a naive
|
||||
// implementation would hand its crop to the guest.
|
||||
const hidden = await addPhotoWithFace(eventId, makeEmbedding(3, 0), {
|
||||
visibility: 'hidden', score: 0.99,
|
||||
});
|
||||
const visible = await addPhotoWithFace(eventId, makeEmbedding(3, 1), {
|
||||
visibility: 'visible', score: 0.80,
|
||||
});
|
||||
await clustering.assignFaces(eventId, [hidden.face, visible.face]);
|
||||
|
||||
const [guestPerson] = await peopleService.listPeople(eventId, { isClient: false, minClusterSize: 1 });
|
||||
expect(guestPerson.cover.photo_id).toBe(visible.photoId);
|
||||
expect(guestPerson.cover.photo_id).not.toBe(hidden.photoId);
|
||||
});
|
||||
|
||||
it('prefers the cover the photographer chose (#1096)', async () => {
|
||||
const eventId = await seedEvent('chosen-cover');
|
||||
// The auto-pick would take the 0.99 face. The photographer picked the
|
||||
// other one — without this the PATCH saved, the toast said so, and the
|
||||
// avatar reverted on the very next read.
|
||||
const best = await addPhotoWithFace(eventId, makeEmbedding(9, 0), { score: 0.99 });
|
||||
const chosen = await addPhotoWithFace(eventId, makeEmbedding(9, 1), { score: 0.70 });
|
||||
await clustering.assignFaces(eventId, [best.face, chosen.face]);
|
||||
|
||||
const [before] = await peopleService.listPeople(eventId, { isClient: true, minClusterSize: 1 });
|
||||
expect(before.cover.photo_id).toBe(best.photoId);
|
||||
// Clustering must not have written one: an automatic seed here would be
|
||||
// indistinguishable from a real choice the moment listPeople honours it.
|
||||
const seeded = await db('event_people').where({ id: before.id }).first();
|
||||
expect(seeded.cover_face_id).toBeFalsy();
|
||||
|
||||
await db('event_people').where({ id: before.id }).update({ cover_face_id: chosen.face.id });
|
||||
|
||||
const [after] = await peopleService.listPeople(eventId, { isClient: true, minClusterSize: 1 });
|
||||
expect(after.cover.photo_id).toBe(chosen.photoId);
|
||||
});
|
||||
|
||||
it('carries a chosen cover through a merge', async () => {
|
||||
const eventId = await seedEvent('cover-merge');
|
||||
const a = await addPhotoWithFace(eventId, makeEmbedding(20, 0), { score: 0.90 });
|
||||
const b = await addPhotoWithFace(eventId, makeEmbedding(60, 0), { score: 0.95 });
|
||||
await clustering.assignFaces(eventId, [a.face]);
|
||||
await clustering.assignFaces(eventId, [b.face]);
|
||||
const people = await db('event_people').where({ event_id: eventId }).orderBy('id');
|
||||
expect(people.length).toBeGreaterThan(1);
|
||||
|
||||
// The SOURCE carries the choice; the target has none.
|
||||
await db('event_people').where({ id: people[1].id }).update({ cover_face_id: b.face.id });
|
||||
await clustering.mergePeople(eventId, [people[1].id], people[0].id);
|
||||
|
||||
const target = await db('event_people').where({ id: people[0].id }).first();
|
||||
expect(target.cover_face_id).toBe(b.face.id);
|
||||
});
|
||||
|
||||
it('carries a chosen cover through a recluster', async () => {
|
||||
const eventId = await seedEvent('cover-recluster');
|
||||
const faces = [];
|
||||
for (let v = 0; v < 3; v++) {
|
||||
faces.push((await addPhotoWithFace(eventId, makeEmbedding(21, v), { score: 0.9 - v * 0.1 })).face);
|
||||
}
|
||||
await clustering.assignFaces(eventId, faces);
|
||||
const [person] = await db('event_people').where({ event_id: eventId });
|
||||
// Pick the WORST-scoring face, so an automatic re-pick would differ.
|
||||
const chosen = faces[2].id;
|
||||
await db('event_people').where({ id: person.id }).update({ cover_face_id: chosen });
|
||||
|
||||
await clustering.recluster(eventId);
|
||||
|
||||
const after = await db('event_people').where({ event_id: eventId }).whereNotNull('cover_face_id');
|
||||
expect(after).toHaveLength(1);
|
||||
expect(after[0].cover_face_id).toBe(chosen);
|
||||
});
|
||||
|
||||
it('falls back to a visible face when the chosen cover is hidden from this audience', async () => {
|
||||
const eventId = await seedEvent('chosen-cover-hidden');
|
||||
// Choosing a cover must never override the visibility scoping — that
|
||||
// would hand a guest a crop of a photo they cannot open.
|
||||
const hidden = await addPhotoWithFace(eventId, makeEmbedding(10, 0), {
|
||||
visibility: 'hidden', score: 0.99,
|
||||
});
|
||||
const visible = await addPhotoWithFace(eventId, makeEmbedding(10, 1), { score: 0.70 });
|
||||
await clustering.assignFaces(eventId, [hidden.face, visible.face]);
|
||||
|
||||
const [person] = await peopleService.listPeople(eventId, { isClient: true, minClusterSize: 1 });
|
||||
await db('event_people').where({ id: person.id }).update({ cover_face_id: hidden.face.id });
|
||||
|
||||
const [guestView] = await peopleService.listPeople(eventId, { isClient: false, minClusterSize: 1 });
|
||||
expect(guestView.cover.photo_id).toBe(visible.photoId);
|
||||
expect(guestView.cover.photo_id).not.toBe(hidden.photoId);
|
||||
});
|
||||
|
||||
it('drops a person entirely when all their photos are hidden', async () => {
|
||||
const eventId = await seedEvent('all-hidden');
|
||||
const faces = [];
|
||||
for (let v = 0; v < 3; v++) {
|
||||
faces.push((await addPhotoWithFace(eventId, makeEmbedding(4, v), { visibility: 'hidden' })).face);
|
||||
}
|
||||
await clustering.assignFaces(eventId, faces);
|
||||
|
||||
const guestView = await peopleService.listPeople(eventId, { isClient: false, minClusterSize: 1 });
|
||||
expect(guestView).toHaveLength(0);
|
||||
const clientView = await peopleService.listPeople(eventId, { isClient: true, minClusterSize: 1 });
|
||||
expect(clientView).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('omits hidden and ignored people from the guest response', async () => {
|
||||
const eventId = await seedEvent('hidden-people');
|
||||
const a = (await addPhotoWithFace(eventId, makeEmbedding(5))).face;
|
||||
const b = (await addPhotoWithFace(eventId, makeEmbedding(6))).face;
|
||||
await clustering.assignFaces(eventId, [a, b]);
|
||||
|
||||
const people = await db('event_people').where({ event_id: eventId }).orderBy('id');
|
||||
await db('event_people').where({ id: people[0].id }).update({ is_hidden: true });
|
||||
await db('event_people').where({ id: people[1].id }).update({ is_ignored: true });
|
||||
|
||||
const guestView = await peopleService.listPeople(eventId, { isClient: false, minClusterSize: 1 });
|
||||
expect(guestView).toHaveLength(0);
|
||||
const adminView = await peopleService.listPeople(eventId, { isClient: true, forAdmin: true });
|
||||
expect(adminView).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('does not attach a hidden person to a photo a guest can see', async () => {
|
||||
const eventId = await seedEvent('person-ids-hidden');
|
||||
const { photoId, face } = await addPhotoWithFace(eventId, makeEmbedding(7));
|
||||
await clustering.assignFaces(eventId, [face]);
|
||||
const person = await db('event_people').where({ event_id: eventId }).first();
|
||||
await db('event_people').where({ id: person.id }).update({ is_hidden: true });
|
||||
|
||||
const guestMap = await peopleService.getPersonIdsByPhoto(eventId, [photoId], { forAdmin: false });
|
||||
expect(guestMap.get(photoId)).toBeUndefined();
|
||||
|
||||
const adminMap = await peopleService.getPersonIdsByPhoto(eventId, [photoId], { forAdmin: true });
|
||||
expect(adminMap.get(photoId)).toEqual([person.id]);
|
||||
});
|
||||
|
||||
it('respects the minimum cluster size so one-off bystanders stay out', async () => {
|
||||
const eventId = await seedEvent('min-cluster');
|
||||
const solo = (await addPhotoWithFace(eventId, makeEmbedding(8))).face;
|
||||
const crowd = [];
|
||||
for (let v = 0; v < 4; v++) {
|
||||
crowd.push((await addPhotoWithFace(eventId, makeEmbedding(9, v))).face);
|
||||
}
|
||||
await clustering.assignFaces(eventId, [solo, ...crowd]);
|
||||
|
||||
const people = await peopleService.listPeople(eventId, { isClient: false, minClusterSize: 3 });
|
||||
expect(people).toHaveLength(1);
|
||||
expect(people[0].face_count).toBe(4);
|
||||
});
|
||||
});
|
||||
|
||||
describe('erasure', () => {
|
||||
it('purgeEvent removes every face row and resets the photos', async () => {
|
||||
const eventId = await seedEvent('purge');
|
||||
const faces = [];
|
||||
for (let v = 0; v < 3; v++) {
|
||||
faces.push((await addPhotoWithFace(eventId, makeEmbedding(10, v))).face);
|
||||
}
|
||||
await clustering.assignFaces(eventId, faces);
|
||||
await db('photos').where({ event_id: eventId }).update({ face_status: 'done', face_count: 1 });
|
||||
|
||||
expect(await db('photo_faces').where({ event_id: eventId })).not.toHaveLength(0);
|
||||
expect(await db('event_people').where({ event_id: eventId })).not.toHaveLength(0);
|
||||
|
||||
await faceProcessor.purgeEvent(eventId);
|
||||
|
||||
expect(await db('photo_faces').where({ event_id: eventId })).toHaveLength(0);
|
||||
expect(await db('event_people').where({ event_id: eventId })).toHaveLength(0);
|
||||
const photos = await db('photos').where({ event_id: eventId });
|
||||
expect(photos.every((p) => p.face_status === null && p.face_count === null)).toBe(true);
|
||||
});
|
||||
|
||||
it('purgePhotoFaces removes face rows WITHOUT relying on the FK cascade', async () => {
|
||||
// The regression this guards: PicPeak does not enable
|
||||
// `PRAGMA foreign_keys` on SQLite, so ON DELETE CASCADE never fires
|
||||
// there and biometric embeddings outlived the photo. The pragma is
|
||||
// explicitly OFF here so the assertion can only pass if the deletion
|
||||
// path purges the rows itself.
|
||||
await db.raw('PRAGMA foreign_keys = OFF');
|
||||
|
||||
const eventId = await seedEvent('purge-no-cascade');
|
||||
const faces = [];
|
||||
for (let v = 0; v < 3; v++) {
|
||||
faces.push((await addPhotoWithFace(eventId, makeEmbedding(20, v))).face);
|
||||
}
|
||||
await clustering.assignFaces(eventId, faces);
|
||||
|
||||
const person = await db('event_people').where({ event_id: eventId }).first();
|
||||
expect(person.face_count_total).toBe(3);
|
||||
|
||||
const victim = faces[0];
|
||||
await faceProcessor.purgePhotoFaces(victim.photo_id);
|
||||
|
||||
expect(await db('photo_faces').where({ photo_id: victim.photo_id })).toHaveLength(0);
|
||||
// …and the person it belonged to was rebuilt, not left with a stale count.
|
||||
const after = await db('event_people').where({ id: person.id }).first();
|
||||
expect(after.face_count_total).toBe(2);
|
||||
});
|
||||
|
||||
it('purging the last face of a person removes the person too', async () => {
|
||||
await db.raw('PRAGMA foreign_keys = OFF');
|
||||
const eventId = await seedEvent('purge-last-face');
|
||||
const { face, photoId } = await addPhotoWithFace(eventId, makeEmbedding(21));
|
||||
await clustering.assignFaces(eventId, [face]);
|
||||
expect(await db('event_people').where({ event_id: eventId })).toHaveLength(1);
|
||||
|
||||
await faceProcessor.purgePhotoFaces(photoId);
|
||||
|
||||
expect(await db('event_people').where({ event_id: eventId })).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('deleting an event removes its people and faces', async () => {
|
||||
await db.raw('PRAGMA foreign_keys = ON');
|
||||
const eventId = await seedEvent('event-delete');
|
||||
const { face } = await addPhotoWithFace(eventId, makeEmbedding(11));
|
||||
await clustering.assignFaces(eventId, [face]);
|
||||
|
||||
await db('photos').where({ event_id: eventId }).del();
|
||||
await db('events').where({ id: eventId }).del();
|
||||
|
||||
expect(await db('photo_faces').where({ event_id: eventId })).toHaveLength(0);
|
||||
expect(await db('event_people').where({ event_id: eventId })).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('all-in-one image block (#1042 / PR #1068)', () => {
|
||||
// Blocked for performance: the AIO image runs backend, frontend, SQLite
|
||||
// and every worker in one container, with no ML sidecar to talk to. The
|
||||
// failure there would not be loud — just a slow install that looks
|
||||
// broken — so the gate is asserted rather than assumed.
|
||||
const faceSettings = require('../../src/services/faceSettings');
|
||||
|
||||
afterEach(() => { delete process.env.PICPEAK_SINGLE_CONTAINER; });
|
||||
|
||||
it('reports the feature off regardless of the flag row', async () => {
|
||||
process.env.PICPEAK_SINGLE_CONTAINER = 'true';
|
||||
expect(faceSettings.isSingleContainerImage()).toBe(true);
|
||||
// Even with the flag ON in the database.
|
||||
await db('feature_flags').insert({ key: 'faces', value: true })
|
||||
.onConflict('key').merge()
|
||||
.catch(async () => {
|
||||
await db('feature_flags').where({ key: 'faces' }).update({ value: true });
|
||||
});
|
||||
expect(await faceSettings.isFeatureEnabled()).toBe(false);
|
||||
});
|
||||
|
||||
it('refuses per-event detection too', async () => {
|
||||
process.env.PICPEAK_SINGLE_CONTAINER = 'true';
|
||||
const eventId = await seedEvent('aio-block');
|
||||
const event = await db('events').where({ id: eventId }).first();
|
||||
expect(event.face_recognition_enabled).toBeTruthy();
|
||||
expect(await faceSettings.isEnabledForEvent(event)).toBe(false);
|
||||
});
|
||||
|
||||
it('accepts only explicit truthy markers', () => {
|
||||
for (const v of ['true', '1', 'yes', 'TRUE']) {
|
||||
process.env.PICPEAK_SINGLE_CONTAINER = v;
|
||||
expect(faceSettings.isSingleContainerImage()).toBe(true);
|
||||
}
|
||||
for (const v of ['false', '0', '', 'no']) {
|
||||
process.env.PICPEAK_SINGLE_CONTAINER = v;
|
||||
expect(faceSettings.isSingleContainerImage()).toBe(false);
|
||||
}
|
||||
delete process.env.PICPEAK_SINGLE_CONTAINER;
|
||||
expect(faceSettings.isSingleContainerImage()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('export and backup exclusion', () => {
|
||||
it('excludes both face tables from .picpeak exports', () => {
|
||||
const { EXCLUDED_TABLES } = require('../../src/services/picpeakExportService');
|
||||
expect(EXCLUDED_TABLES.has('photo_faces')).toBe(true);
|
||||
expect(EXCLUDED_TABLES.has('event_people')).toBe(true);
|
||||
});
|
||||
|
||||
it('excludes both face tables from the database backup table list', async () => {
|
||||
const databaseBackup = require('../../src/services/databaseBackup');
|
||||
const service = databaseBackup.DatabaseBackupService
|
||||
? new databaseBackup.DatabaseBackupService()
|
||||
: databaseBackup;
|
||||
if (typeof service.getTables !== 'function') return; // shape differs; covered by the export test
|
||||
|
||||
const tables = await service.getTables();
|
||||
expect(tables).not.toContain('photo_faces');
|
||||
expect(tables).not.toContain('event_people');
|
||||
// Sanity: the filter didn't eat everything.
|
||||
expect(tables).toContain('events');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,146 +0,0 @@
|
||||
/**
|
||||
* Bounding-box coordinate space (#1074).
|
||||
*
|
||||
* The sidecar reports boxes in the pixel space of the image it was HANDED —
|
||||
* the ≤1920px preview — while every consumer (the strip's avatar crop, the
|
||||
* admin manager, the auto-category portrait rule) compares them against
|
||||
* photos.width/height, the ORIGINAL dimensions. faceProcessor scales once so
|
||||
* everything downstream can assume original-image coordinates.
|
||||
*
|
||||
* This is the defect that survived longest in review, and it is invisible on
|
||||
* any photo already under 1920px — the entire demo gallery was 750px, so the
|
||||
* scale factor was always exactly 1.0 and the correction never ran. Verified
|
||||
* by hand afterwards on a real 4000x3000 upload (stored box moved from
|
||||
* 1493,204 to 3110,426 — a factor of 2.083, exactly 4000/1920). This test
|
||||
* exists so that verification does not have to be repeated by hand.
|
||||
*/
|
||||
|
||||
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-facescale-')), 'db.sqlite',
|
||||
);
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'facescale-test-secret';
|
||||
|
||||
// A 1920x1440 JPEG standing in for the preview rendition. faceProcessor reads
|
||||
// its dimensions with sharp to derive the scale, so it must be a real image.
|
||||
const sharp = require('sharp');
|
||||
|
||||
let mockPreviewBuffer;
|
||||
const mockSidecarBox = [1493, 204, 131, 161]; // what the sidecar sees on the preview
|
||||
|
||||
jest.mock('../../src/services/imageProcessor', () => ({
|
||||
...jest.requireActual('../../src/services/imageProcessor'),
|
||||
ensurePreviewImage: jest.fn(async () => 'previews/preview_test.jpg'),
|
||||
}));
|
||||
|
||||
jest.mock('../../src/services/storage', () => ({
|
||||
getStorage: () => ({ get: async () => mockPreviewBuffer }),
|
||||
}));
|
||||
|
||||
jest.mock('../../src/services/faceClient', () => ({
|
||||
detectFaces: jest.fn(async () => ({
|
||||
model_version: 'test-v1',
|
||||
faces: [{
|
||||
bbox: mockSidecarBox,
|
||||
score: 0.99,
|
||||
landmarks: [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]],
|
||||
yaw: 0, pitch: 0, blur: 500,
|
||||
embedding: Array.from({ length: 64 }, (_, i) => (i === 0 ? 1 : 0)),
|
||||
}],
|
||||
})),
|
||||
SidecarUnavailableError: class extends Error {},
|
||||
}));
|
||||
|
||||
const { bootCrmDb } = require('./helpers/crmDb');
|
||||
|
||||
let db; let cleanup; let faceProcessor;
|
||||
|
||||
async function seedPhoto(width, height) {
|
||||
const [e] = await db('events').insert({
|
||||
slug: `scale-${width}-${Math.random().toString(36).slice(2, 8)}`,
|
||||
event_type: 'wedding',
|
||||
event_name: 'scale',
|
||||
event_date: '2026-01-01',
|
||||
host_email: 'h@example.com',
|
||||
admin_email: 'a@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: `scale-${Math.random()}`,
|
||||
expires_at: new Date().toISOString(),
|
||||
face_recognition_enabled: true,
|
||||
}).returning('id');
|
||||
const eventId = typeof e === 'object' ? e.id : e;
|
||||
|
||||
const [p] = await db('photos').insert({
|
||||
event_id: eventId,
|
||||
filename: 'big.jpg',
|
||||
path: '/tmp/big.jpg',
|
||||
type: 'individual',
|
||||
width,
|
||||
height,
|
||||
processing_status: 'complete',
|
||||
face_status: 'processing',
|
||||
}).returning('id');
|
||||
return { eventId, photoId: typeof p === 'object' ? p.id : p };
|
||||
}
|
||||
|
||||
describe('face bbox coordinate space (#1074)', () => {
|
||||
beforeAll(async () => {
|
||||
mockPreviewBuffer = await sharp({
|
||||
create: { width: 1920, height: 1440, channels: 3, background: { r: 20, g: 40, b: 80 } },
|
||||
}).jpeg().toBuffer();
|
||||
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
// The faces flag gates everything; turn it on for this suite.
|
||||
await db('feature_flags').insert({ key: 'faces', value: true })
|
||||
.onConflict('key').merge()
|
||||
.catch(async () => { await db('feature_flags').where({ key: 'faces' }).update({ value: true }); });
|
||||
faceProcessor = require('../../src/services/faceProcessor');
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => { if (cleanup) await cleanup(); });
|
||||
|
||||
it('scales preview-space boxes into ORIGINAL image coordinates', async () => {
|
||||
// 4000px original, 1920px preview -> every coordinate must grow by 4000/1920.
|
||||
const { photoId } = await seedPhoto(4000, 3000);
|
||||
await faceProcessor.processPhotoFaces(photoId);
|
||||
|
||||
const face = await db('photo_faces').where({ photo_id: photoId }).first();
|
||||
const scale = 4000 / 1920;
|
||||
|
||||
expect(face.bbox_x).toBeCloseTo(mockSidecarBox[0] * scale, 1);
|
||||
expect(face.bbox_y).toBeCloseTo(mockSidecarBox[1] * scale, 1);
|
||||
expect(face.bbox_w).toBeCloseTo(mockSidecarBox[2] * scale, 1);
|
||||
expect(face.bbox_h).toBeCloseTo(mockSidecarBox[3] * scale, 1);
|
||||
|
||||
// The regression this guards: the raw preview-space value being stored.
|
||||
expect(face.bbox_x).not.toBeCloseTo(mockSidecarBox[0], 1);
|
||||
// And a sanity check that it lands inside the original frame.
|
||||
expect(face.bbox_x + face.bbox_w).toBeLessThanOrEqual(4000);
|
||||
});
|
||||
|
||||
it('leaves boxes untouched when the photo is already preview-sized', async () => {
|
||||
// The case that hid the bug: no downscale, so scale is exactly 1 and the
|
||||
// stored box equals what the sidecar reported.
|
||||
const { photoId } = await seedPhoto(1920, 1440);
|
||||
await faceProcessor.processPhotoFaces(photoId);
|
||||
|
||||
const face = await db('photo_faces').where({ photo_id: photoId }).first();
|
||||
expect(face.bbox_x).toBeCloseTo(mockSidecarBox[0], 1);
|
||||
expect(face.bbox_w).toBeCloseTo(mockSidecarBox[2], 1);
|
||||
});
|
||||
|
||||
it('falls back to unscaled rather than corrupting when width is unknown', async () => {
|
||||
// Pre-dimension-migration rows have no width. Storing a box scaled by
|
||||
// NaN/0 would be worse than storing an unscaled one.
|
||||
const { photoId } = await seedPhoto(null, null);
|
||||
await faceProcessor.processPhotoFaces(photoId);
|
||||
|
||||
const face = await db('photo_faces').where({ photo_id: photoId }).first();
|
||||
expect(Number.isFinite(face.bbox_x)).toBe(true);
|
||||
expect(face.bbox_x).toBeCloseTo(mockSidecarBox[0], 1);
|
||||
});
|
||||
});
|
||||
@@ -1,226 +0,0 @@
|
||||
/**
|
||||
* A deferred photo must not stall the queue.
|
||||
*
|
||||
* claimNextPhoto orders by id ascending, and the queue defaults to a single
|
||||
* worker. So returning an unreachable photo to 'pending' — the obvious way to
|
||||
* say "try again later" — makes that same row the oldest pending one forever:
|
||||
* the worker reclaims it after every backoff and never reaches a higher id.
|
||||
* One dead mount would stall face scanning for the entire install, including
|
||||
* unrelated events and fresh uploads.
|
||||
*
|
||||
* The row is instead left parked in 'processing' with its face_started_at
|
||||
* intact. It is not claimable, so the worker advances; the existing janitor
|
||||
* returns it to 'pending' after STUCK_TIMEOUT_MS, which is the retry.
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
|
||||
process.env.NODE_ENV = 'test';
|
||||
const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-defer-'));
|
||||
process.env.TEST_DATABASE_PATH = path.join(tmpRoot, 'db.sqlite');
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'defer-test-secret';
|
||||
|
||||
const { bootCrmDb } = require('./helpers/crmDb');
|
||||
|
||||
let db; let cleanup; let faceQueue; let faceProcessor;
|
||||
|
||||
describe('deferred photos do not block the queue', () => {
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
faceQueue = require('../../src/services/faceQueue');
|
||||
faceProcessor = require('../../src/services/faceProcessor');
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => {
|
||||
if (cleanup) await cleanup();
|
||||
await fs.promises.rm(tmpRoot, { recursive: true, force: true }).catch(() => {});
|
||||
});
|
||||
|
||||
it('exports TransientSourceError for the queue to branch on', () => {
|
||||
// The queue imports this from faceProcessor; if the export is dropped the
|
||||
// instanceof check silently becomes false and every deferral turns back
|
||||
// into a permanent failure.
|
||||
expect(typeof faceProcessor.TransientSourceError).toBe('function');
|
||||
expect(new faceProcessor.TransientSourceError(1, 'x'))
|
||||
.toBeInstanceOf(Error);
|
||||
});
|
||||
|
||||
it('does NOT return a deferred row to pending', () => {
|
||||
// Source inspection, deliberately. workerLoop is an unexported infinite
|
||||
// loop, so the branch cannot be driven directly, and asserting on database
|
||||
// state alone does not distinguish the fix from the bug — a version that
|
||||
// re-queues the row passes every state assertion in this file. What
|
||||
// actually matters is that this one branch does not call releaseToPending,
|
||||
// so that is what is pinned. Same approach as the contract tests added for
|
||||
// #596.
|
||||
const src = fs.readFileSync(
|
||||
path.join(__dirname, '..', '..', 'src', 'services', 'faceQueue.js'), 'utf8'
|
||||
);
|
||||
|
||||
const marker = 'if (err instanceof TransientSourceError) {';
|
||||
const start = src.indexOf(marker);
|
||||
expect(start).toBeGreaterThan(-1);
|
||||
|
||||
// The branch body, up to its closing brace.
|
||||
const body = src.slice(start, src.indexOf('\n }', start));
|
||||
expect(body).not.toMatch(/releaseToPending/);
|
||||
expect(body).toMatch(/continue/);
|
||||
|
||||
// And the sidecar branch, which SHOULD still release, so this test fails
|
||||
// if the two branches are ever collapsed back together.
|
||||
const sideStart = src.indexOf('if (err instanceof SidecarUnavailableError) {');
|
||||
expect(sideStart).toBeGreaterThan(-1);
|
||||
const sideBody = src.slice(sideStart, src.indexOf('\n }', sideStart));
|
||||
expect(sideBody).toMatch(/releaseToPending/);
|
||||
});
|
||||
|
||||
it('leaves a deferred row claimable-later, not claimable-now', async () => {
|
||||
// A row parked in 'processing' is invisible to claimNextPhoto, which only
|
||||
// ever selects face_status='pending' — that is what lets the worker move
|
||||
// past it instead of spinning on it.
|
||||
const [e] = await db('events').insert({
|
||||
slug: `defer-${Math.random().toString(36).slice(2, 8)}`,
|
||||
event_type: 'wedding',
|
||||
event_name: 'defer',
|
||||
event_date: '2026-01-01',
|
||||
host_email: 'h@example.com',
|
||||
admin_email: 'a@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: `defer-${Math.random()}`,
|
||||
expires_at: new Date().toISOString(),
|
||||
face_recognition_enabled: true,
|
||||
}).returning('id');
|
||||
const eventId = typeof e === 'object' ? e.id : e;
|
||||
|
||||
const [stuck] = await db('photos').insert({
|
||||
event_id: eventId,
|
||||
filename: 'stuck.jpg',
|
||||
path: 'd/stuck.jpg',
|
||||
type: 'individual',
|
||||
processing_status: 'complete',
|
||||
face_status: 'processing',
|
||||
face_started_at: new Date().toISOString(),
|
||||
source_origin: 'external',
|
||||
}).returning('id');
|
||||
const stuckId = typeof stuck === 'object' ? stuck.id : stuck;
|
||||
|
||||
const parked = await db('photos')
|
||||
.where({ id: stuckId, face_status: 'pending' })
|
||||
.first();
|
||||
expect(parked).toBeUndefined(); // not claimable while parked
|
||||
|
||||
// The janitor's contract is what turns the park into a retry: it resets
|
||||
// 'processing' rows whose face_started_at is older than the stuck timeout.
|
||||
// Backdate past it and the row becomes claimable again.
|
||||
const longAgo = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
|
||||
await db('photos').where({ id: stuckId }).update({ face_started_at: longAgo });
|
||||
|
||||
const cutoff = new Date(Date.now() - 600000).toISOString();
|
||||
const reset = await db('photos')
|
||||
.where('face_status', 'processing')
|
||||
.where('face_started_at', '<', cutoff)
|
||||
.update({ face_status: 'pending', face_started_at: null });
|
||||
|
||||
expect(reset).toBeGreaterThan(0);
|
||||
const after = await db('photos').where({ id: stuckId }).first();
|
||||
expect(after.face_status).toBe('pending');
|
||||
});
|
||||
|
||||
it('claimNextPhoto skips events inside their backoff window', async () => {
|
||||
// The per-event cooldown is what stops the janitor handing a whole dead
|
||||
// gallery back every sweep. Without the exclusion the worker walks all of
|
||||
// it again — one slow stat per photo against a possibly hard-mounted
|
||||
// share — before reaching any healthy event.
|
||||
const mk = async (name) => {
|
||||
const [e] = await db('events').insert({
|
||||
slug: `cd-${name}-${Math.random().toString(36).slice(2, 8)}`,
|
||||
event_type: 'wedding',
|
||||
event_name: name,
|
||||
event_date: '2026-01-01',
|
||||
host_email: 'h@example.com',
|
||||
admin_email: 'a@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: `cd-${name}-${Math.random()}`,
|
||||
expires_at: new Date().toISOString(),
|
||||
face_recognition_enabled: true,
|
||||
}).returning('id');
|
||||
const eventId = typeof e === 'object' ? e.id : e;
|
||||
const [p2] = await db('photos').insert({
|
||||
event_id: eventId,
|
||||
filename: `${name}.jpg`,
|
||||
path: `cd/${name}.jpg`,
|
||||
type: 'individual',
|
||||
processing_status: 'complete',
|
||||
face_status: 'pending',
|
||||
source_origin: 'external',
|
||||
}).returning('id');
|
||||
return { eventId, photoId: typeof p2 === 'object' ? p2.id : p2 };
|
||||
};
|
||||
|
||||
await db('photos').del();
|
||||
const dead = await mk('dead'); // lower id -> would win the FIFO
|
||||
const healthy = await mk('healthy');
|
||||
|
||||
// Without exclusion the dead event's row is claimed first...
|
||||
const first = await faceQueue.claimNextPhoto([]);
|
||||
expect(first.id).toBe(dead.photoId);
|
||||
await db('photos').where({ id: dead.photoId }).update({ face_status: 'pending' });
|
||||
|
||||
// ...and with it, the worker reaches the healthy event instead.
|
||||
const second = await faceQueue.claimNextPhoto([dead.eventId]);
|
||||
expect(second.id).toBe(healthy.photoId);
|
||||
});
|
||||
|
||||
it('backoff spares managed rows in a mixed-source event', async () => {
|
||||
// A reference event can hold managed uploads alongside imported external
|
||||
// ones. Excluding the whole event id would leave those unscanned for as
|
||||
// long as external rows keep renewing the cooldown — indefinitely, during
|
||||
// a real outage — even though their local source is fine.
|
||||
await db('photos').del();
|
||||
const [e] = await db('events').insert({
|
||||
slug: `mix-${Math.random().toString(36).slice(2, 8)}`,
|
||||
event_type: 'wedding',
|
||||
event_name: 'mix',
|
||||
event_date: '2026-01-01',
|
||||
host_email: 'h@example.com',
|
||||
admin_email: 'a@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: `mix-${Math.random()}`,
|
||||
expires_at: new Date().toISOString(),
|
||||
face_recognition_enabled: true,
|
||||
source_mode: 'reference',
|
||||
}).returning('id');
|
||||
const eventId = typeof e === 'object' ? e.id : e;
|
||||
|
||||
const add = async (origin, name) => {
|
||||
const [p2] = await db('photos').insert({
|
||||
event_id: eventId,
|
||||
filename: name,
|
||||
path: `mix/${name}`,
|
||||
type: 'individual',
|
||||
processing_status: 'complete',
|
||||
face_status: 'pending',
|
||||
source_origin: origin,
|
||||
}).returning('id');
|
||||
return typeof p2 === 'object' ? p2.id : p2;
|
||||
};
|
||||
await add('external', 'ext.jpg'); // lower id, would win the FIFO
|
||||
const managedId = await add('managed', 'man.jpg');
|
||||
|
||||
// Event is in backoff: the external row is skipped, the managed one is not.
|
||||
const claimed = await faceQueue.claimNextPhoto([eventId]);
|
||||
expect(claimed).toBeTruthy();
|
||||
expect(claimed.id).toBe(managedId);
|
||||
});
|
||||
|
||||
it('startQueue is exported and does not throw on import', () => {
|
||||
// faceQueue requires faceProcessor for TransientSourceError while
|
||||
// faceProcessor is itself required by the routes — a circular require here
|
||||
// would surface as an undefined export rather than a crash, so assert the
|
||||
// module actually loaded something usable.
|
||||
expect(faceQueue).toBeTruthy();
|
||||
expect(Object.keys(faceQueue).length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
@@ -1,209 +0,0 @@
|
||||
/**
|
||||
* A dropped mount defers a scan; a dead photo fails it.
|
||||
*
|
||||
* ensurePreviewImage returns null for both "this JPEG is corrupt" and "the
|
||||
* NFS share is gone", and #1090 made that distinction matter: external
|
||||
* libraries now reach this path, and network mounts drop far more often than
|
||||
* local disks. Failing on an outage strands the photo — faceQueue only ever
|
||||
* claims 'pending', and nothing re-queues a failure automatically, so a mount
|
||||
* that blinked mid-scan would cost an entire gallery a manual Re-scan.
|
||||
*
|
||||
* The probe checks the containing DIRECTORY rather than the file, because that
|
||||
* is what separates the two cases: a missing file inside a healthy directory
|
||||
* is a broken photo, an unreachable directory is broken storage.
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
|
||||
process.env.NODE_ENV = 'test';
|
||||
const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-transient-'));
|
||||
process.env.TEST_DATABASE_PATH = path.join(tmpRoot, 'db.sqlite');
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'transient-test-secret';
|
||||
// Created BEFORE anything requires externalMediaService: getExternalMediaRoot
|
||||
// only honours the env var if the directory already exists, and caches the
|
||||
// result on first call — set it later and every path silently resolves
|
||||
// against a fallback root instead.
|
||||
process.env.EXTERNAL_MEDIA_ROOT = path.join(tmpRoot, 'media');
|
||||
fs.mkdirSync(process.env.EXTERNAL_MEDIA_ROOT, { recursive: true });
|
||||
|
||||
let previewKeyResult = null;
|
||||
const mockEnsurePreviewImage = jest.fn(async () => previewKeyResult);
|
||||
|
||||
jest.mock('../../src/services/imageProcessor', () => ({
|
||||
...jest.requireActual('../../src/services/imageProcessor'),
|
||||
ensurePreviewImage: (...args) => mockEnsurePreviewImage(...args),
|
||||
}));
|
||||
|
||||
jest.mock('../../src/services/faceClient', () => ({
|
||||
detectFaces: jest.fn(async () => ({ model_version: 'test-v1', faces: [] })),
|
||||
SidecarUnavailableError: class extends Error {},
|
||||
}));
|
||||
|
||||
const { bootCrmDb } = require('./helpers/crmDb');
|
||||
|
||||
let db; let cleanup; let faceProcessor;
|
||||
|
||||
async function seedExternalPhoto({ externalPath, relpath = 'individual/a.jpg' }) {
|
||||
const [e] = await db('events').insert({
|
||||
slug: `tr-${Math.random().toString(36).slice(2, 8)}`,
|
||||
event_type: 'wedding',
|
||||
event_name: 'tr',
|
||||
event_date: '2026-01-01',
|
||||
host_email: 'h@example.com',
|
||||
admin_email: 'a@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: `tr-${Math.random()}`,
|
||||
expires_at: new Date().toISOString(),
|
||||
face_recognition_enabled: true,
|
||||
source_mode: 'reference',
|
||||
external_path: externalPath,
|
||||
}).returning('id');
|
||||
const eventId = typeof e === 'object' ? e.id : e;
|
||||
|
||||
const [p] = await db('photos').insert({
|
||||
event_id: eventId,
|
||||
filename: 'a.jpg',
|
||||
path: 'tr/a.jpg',
|
||||
type: 'individual',
|
||||
width: 4000,
|
||||
height: 3000,
|
||||
processing_status: 'complete',
|
||||
face_status: 'processing',
|
||||
source_origin: 'external',
|
||||
external_relpath: relpath,
|
||||
}).returning('id');
|
||||
return { eventId, photoId: typeof p === 'object' ? p.id : p };
|
||||
}
|
||||
|
||||
describe('transient source vs dead photo', () => {
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
await db('feature_flags').insert({ key: 'faces', value: true })
|
||||
.onConflict('key').merge()
|
||||
.catch(async () => { await db('feature_flags').where({ key: 'faces' }).update({ value: true }); });
|
||||
faceProcessor = require('../../src/services/faceProcessor');
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => {
|
||||
if (cleanup) await cleanup();
|
||||
await fs.promises.rm(tmpRoot, { recursive: true, force: true }).catch(() => {});
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
previewKeyResult = null; // i.e. ensurePreviewImage could not build one
|
||||
mockEnsurePreviewImage.mockClear();
|
||||
});
|
||||
|
||||
it('defers, not fails, when the source directory is unreachable', async () => {
|
||||
// Nothing was ever created under EXTERNAL_MEDIA_ROOT for this path, so the
|
||||
// directory does not resolve — the shape a dropped mount presents.
|
||||
const { photoId } = await seedExternalPhoto({ externalPath: 'vanished-share' });
|
||||
|
||||
await expect(faceProcessor.processPhotoFaces(photoId))
|
||||
.rejects.toBeInstanceOf(faceProcessor.TransientSourceError);
|
||||
|
||||
// Critically: still claimable. A 'failed' here is what stranded the photo.
|
||||
const photo = await db('photos').where({ id: photoId }).first();
|
||||
expect(photo.face_status).not.toBe('failed');
|
||||
});
|
||||
|
||||
it('defers when the event root survives an unmount but is empty', async () => {
|
||||
// The common NFS/SMB shape: unmounting leaves the mountpoint behind as an
|
||||
// ordinary empty directory, so fs.access succeeds on storage that is
|
||||
// entirely gone. The EVENT ROOT is the thing that goes empty — the photo's
|
||||
// own subdirectory vanishes with it.
|
||||
const emptyRoot = path.join(process.env.EXTERNAL_MEDIA_ROOT, 'unmounted');
|
||||
await fs.promises.mkdir(emptyRoot, { recursive: true });
|
||||
const { photoId } = await seedExternalPhoto({ externalPath: 'unmounted' });
|
||||
|
||||
await expect(faceProcessor.processPhotoFaces(photoId))
|
||||
.rejects.toBeInstanceOf(faceProcessor.TransientSourceError);
|
||||
|
||||
const photo = await db('photos').where({ id: photoId }).first();
|
||||
expect(photo.face_status).not.toBe('failed');
|
||||
});
|
||||
|
||||
it('fails when the directory is healthy but the file is gone', async () => {
|
||||
// Directory exists, file does not — a genuinely broken photo, which should
|
||||
// surface as a failure the admin can see rather than retry forever.
|
||||
const live = path.join(process.env.EXTERNAL_MEDIA_ROOT, 'live-share', 'individual');
|
||||
await fs.promises.mkdir(live, { recursive: true });
|
||||
// Non-empty: an empty directory is now read as an unmounted share, so the
|
||||
// "healthy storage, dead photo" case needs a sibling file present.
|
||||
await fs.promises.writeFile(path.join(live, 'sibling.jpg'), 'x');
|
||||
const { photoId } = await seedExternalPhoto({ externalPath: 'live-share' });
|
||||
|
||||
const result = await faceProcessor.processPhotoFaces(photoId);
|
||||
|
||||
expect(result.status).toBe('failed');
|
||||
const photo = await db('photos').where({ id: photoId }).first();
|
||||
expect(photo.face_status).toBe('failed');
|
||||
expect(photo.face_error).toMatch(/preview/i);
|
||||
});
|
||||
|
||||
it('fails a missing subdirectory rather than deferring the whole event', async () => {
|
||||
// individual/ deleted while collages/ is fine. Probing only the photo's own
|
||||
// directory reports ENOENT and would read as a mount-wide outage, deferring
|
||||
// the event and starving every healthy sibling folder. The root is
|
||||
// populated, so the mount is up and this is a broken path.
|
||||
const root = path.join(process.env.EXTERNAL_MEDIA_ROOT, 'partial');
|
||||
await fs.promises.mkdir(path.join(root, 'collages'), { recursive: true });
|
||||
await fs.promises.writeFile(path.join(root, 'collages', 'kept.jpg'), 'x');
|
||||
const { photoId } = await seedExternalPhoto({ externalPath: 'partial' });
|
||||
|
||||
const result = await faceProcessor.processPhotoFaces(photoId);
|
||||
expect(result.status).toBe('failed');
|
||||
});
|
||||
|
||||
it('defers a file that exists but cannot be read', async () => {
|
||||
// EACCES / EIO / ESTALE on the file itself, with the mount up: a transient
|
||||
// condition wearing a per-file disguise. Only ENOENT means genuinely gone.
|
||||
const root = path.join(process.env.EXTERNAL_MEDIA_ROOT, 'locked');
|
||||
const dir = path.join(root, 'individual');
|
||||
await fs.promises.mkdir(dir, { recursive: true });
|
||||
const file = path.join(dir, 'a.jpg');
|
||||
await fs.promises.writeFile(file, 'x');
|
||||
await fs.promises.chmod(file, 0o000);
|
||||
|
||||
const { photoId } = await seedExternalPhoto({ externalPath: 'locked' });
|
||||
try {
|
||||
await expect(faceProcessor.processPhotoFaces(photoId))
|
||||
.rejects.toBeInstanceOf(faceProcessor.TransientSourceError);
|
||||
} finally {
|
||||
await fs.promises.chmod(file, 0o644).catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
it('still fails managed photos without probing the mount', async () => {
|
||||
// The probe is scoped to external/reference rows: a managed photo with no
|
||||
// preview is broken, and there is no mount to blame.
|
||||
const [e] = await db('events').insert({
|
||||
slug: `tr-m-${Math.random().toString(36).slice(2, 8)}`,
|
||||
event_type: 'wedding',
|
||||
event_name: 'trm',
|
||||
event_date: '2026-01-01',
|
||||
host_email: 'h@example.com',
|
||||
admin_email: 'a@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: `tr-m-${Math.random()}`,
|
||||
expires_at: new Date().toISOString(),
|
||||
face_recognition_enabled: true,
|
||||
}).returning('id');
|
||||
const [p] = await db('photos').insert({
|
||||
event_id: typeof e === 'object' ? e.id : e,
|
||||
filename: 'm.jpg',
|
||||
path: 'trm/m.jpg',
|
||||
type: 'individual',
|
||||
width: 100,
|
||||
height: 100,
|
||||
processing_status: 'complete',
|
||||
face_status: 'processing',
|
||||
source_origin: 'managed',
|
||||
}).returning('id');
|
||||
|
||||
const result = await faceProcessor.processPhotoFaces(typeof p === 'object' ? p.id : p);
|
||||
expect(result.status).toBe('failed');
|
||||
});
|
||||
});
|
||||
@@ -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,375 +0,0 @@
|
||||
/**
|
||||
* Responsive preview tiers (#1095).
|
||||
*
|
||||
* A phone can display ~1170px at most, so the single 1920px preview ships
|
||||
* roughly twice the bytes it can use on every lightbox swipe — and the
|
||||
* lightbox prefetches neighbours, so a guest flicking through a wedding
|
||||
* gallery on cellular pays that repeatedly.
|
||||
*
|
||||
* The width is whitelisted rather than free-form: every distinct value is a
|
||||
* permanent cache entry on disk, so an open ?w= is an invitation to fill the
|
||||
* volume with renditions nobody asked for.
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
|
||||
process.env.NODE_ENV = 'test';
|
||||
const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-tiers-'));
|
||||
process.env.TEST_DATABASE_PATH = path.join(tmpRoot, 'db.sqlite');
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'tiers-test-secret';
|
||||
process.env.STORAGE_PATH = path.join(tmpRoot, 'storage');
|
||||
fs.mkdirSync(process.env.STORAGE_PATH, { recursive: true });
|
||||
|
||||
const sharp = require('sharp');
|
||||
const imageProcessor = require('../../src/services/imageProcessor');
|
||||
const { bootCrmDb } = require('./helpers/crmDb');
|
||||
|
||||
let db; let cleanup;
|
||||
|
||||
describe('preview tiers (#1095)', () => {
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => {
|
||||
if (cleanup) await cleanup();
|
||||
await fs.promises.rm(tmpRoot, { recursive: true, force: true }).catch(() => {});
|
||||
});
|
||||
|
||||
describe('normalizeTierWidth', () => {
|
||||
const { normalizeTierWidth, PREVIEW_WIDTHS, THUMBNAIL_WIDTHS } = imageProcessor;
|
||||
|
||||
it('accepts every advertised width', () => {
|
||||
for (const w of PREVIEW_WIDTHS) {
|
||||
expect(normalizeTierWidth(String(w), PREVIEW_WIDTHS)).toBe(w);
|
||||
}
|
||||
for (const w of THUMBNAIL_WIDTHS) {
|
||||
expect(normalizeTierWidth(String(w), THUMBNAIL_WIDTHS)).toBe(w);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects anything not on the list', () => {
|
||||
// The disk-filling cases: arbitrary sizes, and a caller walking a range.
|
||||
for (const bad of ['999', '1921', '0', '-100', '99999']) {
|
||||
expect(normalizeTierWidth(bad, PREVIEW_WIDTHS)).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects junk without throwing', () => {
|
||||
// Straight off a query string, so it is whatever the client sent.
|
||||
for (const bad of [undefined, null, '', 'abc', '12abc', {}, [], '1e3', 'NaN']) {
|
||||
expect(normalizeTierWidth(bad, PREVIEW_WIDTHS)).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not let a thumbnail width through the preview list', () => {
|
||||
// The two lists are separate on purpose; 600 is a thumb tier, not a
|
||||
// preview tier, and vice versa for 1280.
|
||||
expect(normalizeTierWidth('600', PREVIEW_WIDTHS)).toBeNull();
|
||||
expect(normalizeTierWidth('1280', THUMBNAIL_WIDTHS)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ensurePreviewImageAtWidth', () => {
|
||||
async function seedPhoto() {
|
||||
const [e] = await db('events').insert({
|
||||
slug: `tier-${Math.random().toString(36).slice(2, 8)}`,
|
||||
event_type: 'wedding',
|
||||
event_name: 'tier',
|
||||
event_date: '2026-01-01',
|
||||
host_email: 'h@example.com',
|
||||
admin_email: 'a@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: `tier-${Math.random()}`,
|
||||
expires_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
const eventId = typeof e === 'object' ? e.id : e;
|
||||
|
||||
// A real image on disk under STORAGE_PATH, since the managed branch
|
||||
// resolves through storage rather than a mount.
|
||||
const rel = `events/active/tier/${Math.random().toString(36).slice(2, 8)}.jpg`;
|
||||
const abs = path.join(process.env.STORAGE_PATH, rel);
|
||||
await fs.promises.mkdir(path.dirname(abs), { recursive: true });
|
||||
await sharp({ create: { width: 3000, height: 2000, channels: 3, background: { r: 10, g: 90, b: 160 } } })
|
||||
.jpeg().toFile(abs);
|
||||
|
||||
const [p] = await db('photos').insert({
|
||||
event_id: eventId,
|
||||
filename: path.basename(rel),
|
||||
path: rel.replace(/^events\/active\//, ''),
|
||||
type: 'individual',
|
||||
width: 3000,
|
||||
height: 2000,
|
||||
processing_status: 'complete',
|
||||
source_origin: 'managed',
|
||||
}).returning('id');
|
||||
return db('photos').where({ id: typeof p === 'object' ? p.id : p }).first();
|
||||
}
|
||||
|
||||
it('scopes keys by photo id so two galleries cannot collide', async () => {
|
||||
// The leak: managed auto-imports keep camera basenames, so two events can
|
||||
// each hold an IMG_0001.jpg. A tier is served straight from a cache hit
|
||||
// without re-reading the source, so a shared key hands one gallery's
|
||||
// photo to another.
|
||||
const a = await seedPhoto();
|
||||
const b = await seedPhoto();
|
||||
await db('photos').where({ id: a.id }).update({ path: 'wedding-a/IMG_0001.jpg' });
|
||||
await db('photos').where({ id: b.id }).update({ path: 'wedding-b/IMG_0001.jpg' });
|
||||
|
||||
const keyA = imageProcessor.previewTierKeys(await db('photos').where({ id: a.id }).first())[0];
|
||||
const keyB = imageProcessor.previewTierKeys(await db('photos').where({ id: b.id }).first())[0];
|
||||
|
||||
expect(keyA).not.toBe(keyB);
|
||||
expect(keyA).toContain(`p${a.id}_`);
|
||||
expect(keyB).toContain(`p${b.id}_`);
|
||||
});
|
||||
|
||||
it('derives every non-default tier key for cleanup', () => {
|
||||
// Tiers live outside preview_path, so delete/archive/regenerate have no
|
||||
// other way to find them. 1920 is excluded because that IS preview_path.
|
||||
const keys = imageProcessor.previewTierKeys({ id: 5, path: 'e/a.jpg', source_origin: 'managed' });
|
||||
expect(keys).toHaveLength(imageProcessor.PREVIEW_WIDTHS.length - 1);
|
||||
expect(keys.some((k) => k.includes('w1920'))).toBe(false);
|
||||
expect(keys.every((k) => k.includes('p5_'))).toBe(true);
|
||||
});
|
||||
|
||||
it('deletePreviewTiers removes generated tiers from storage', async () => {
|
||||
const photo = await seedPhoto();
|
||||
const key = await imageProcessor.ensurePreviewImageAtWidth(photo, 640);
|
||||
const abs = path.join(process.env.STORAGE_PATH, key);
|
||||
expect(fs.existsSync(abs)).toBe(true);
|
||||
|
||||
await imageProcessor.deletePreviewTiers(await db('photos').where({ id: photo.id }).first());
|
||||
expect(fs.existsSync(abs)).toBe(false);
|
||||
});
|
||||
|
||||
it('produces a distinct key per width and never touches preview_path', async () => {
|
||||
const photo = await seedPhoto();
|
||||
|
||||
const small = await imageProcessor.ensurePreviewImageAtWidth(photo, 640);
|
||||
expect(small).toContain('preview_w640_');
|
||||
|
||||
// The extra tiers are cache, not state. Writing them to the row would
|
||||
// mean the last size requested silently becomes "the" preview.
|
||||
const row = await db('photos').where({ id: photo.id }).first();
|
||||
expect(row.preview_path == null || !String(row.preview_path).includes('w640')).toBe(true);
|
||||
});
|
||||
|
||||
it('resolves the default width to the canonical preview, not a w1920 copy', async () => {
|
||||
// Otherwise every existing install grows a duplicate of every preview it
|
||||
// already has, for no benefit.
|
||||
const photo = await seedPhoto();
|
||||
const def = await imageProcessor.ensurePreviewImageAtWidth(photo, 1920);
|
||||
expect(def).not.toContain('preview_w1920_');
|
||||
});
|
||||
|
||||
it('reuses the cached tier instead of regenerating', async () => {
|
||||
const photo = await seedPhoto();
|
||||
const first = await imageProcessor.ensurePreviewImageAtWidth(photo, 1280);
|
||||
expect(first).toBeTruthy();
|
||||
|
||||
const abs = path.join(process.env.STORAGE_PATH, first);
|
||||
const before = (await fs.promises.stat(abs)).mtimeMs;
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
|
||||
const second = await imageProcessor.ensurePreviewImageAtWidth(photo, 1280);
|
||||
expect(second).toBe(first);
|
||||
expect((await fs.promises.stat(abs)).mtimeMs).toBe(before);
|
||||
});
|
||||
|
||||
it('actually resizes to the requested tier', async () => {
|
||||
const photo = await seedPhoto();
|
||||
const key = await imageProcessor.ensurePreviewImageAtWidth(photo, 640);
|
||||
const meta = await sharp(path.join(process.env.STORAGE_PATH, key)).metadata();
|
||||
// 3000x2000 constrained to a 640 long edge.
|
||||
expect(Math.max(meta.width, meta.height)).toBe(640);
|
||||
expect(meta.height).toBe(Math.round(640 * (2000 / 3000)));
|
||||
});
|
||||
});
|
||||
|
||||
describe('thumbnail tiers', () => {
|
||||
async function seedThumbPhoto(w = 3000, h = 2000) {
|
||||
const [e] = await db('events').insert({
|
||||
slug: `tt-${Math.random().toString(36).slice(2, 8)}`,
|
||||
event_type: 'wedding', event_name: 'tt', event_date: '2026-01-01',
|
||||
host_email: 'h@example.com', admin_email: 'a@example.com',
|
||||
password_hash: 'x', share_link: `tt-${Math.random()}`,
|
||||
expires_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
const eventId = typeof e === 'object' ? e.id : e;
|
||||
const rel = `events/active/tt/${Math.random().toString(36).slice(2, 8)}.jpg`;
|
||||
const abs = path.join(process.env.STORAGE_PATH, rel);
|
||||
await fs.promises.mkdir(path.dirname(abs), { recursive: true });
|
||||
await sharp({ create: { width: w, height: h, channels: 3, background: { r: 5, g: 5, b: 5 } } })
|
||||
.jpeg().toFile(abs);
|
||||
const [p2] = await db('photos').insert({
|
||||
event_id: eventId, filename: path.basename(rel),
|
||||
path: rel.replace(/^events\/active\//, ''), type: 'individual',
|
||||
width: w, height: h, processing_status: 'complete', source_origin: 'managed',
|
||||
}).returning('id');
|
||||
return db('photos').where({ id: typeof p2 === 'object' ? p2.id : p2 }).first();
|
||||
}
|
||||
|
||||
it('scopes thumbnail tier keys by photo id', async () => {
|
||||
// Same cross-gallery hazard the preview tiers had: a cache hit serves
|
||||
// without re-reading the source, so a shared basename leaks across events.
|
||||
const keys = imageProcessor.thumbnailTierKeys({ id: 42, path: 'a/IMG_0001.jpg', source_origin: 'managed' });
|
||||
expect(keys.every((k) => k.includes('p42_'))).toBe(true);
|
||||
// Every width, canonical included: which one is canonical depends on the
|
||||
// thumbnail_width setting, so on a 600-configured install w300 is the
|
||||
// tier file. Deleting a key that was never written is a no-op; missing
|
||||
// one strands it forever.
|
||||
expect(keys).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('tags the tier against the configured width, not the 300 default', async () => {
|
||||
// Regression: with thumbnail_width=600 a w=300 request wrote
|
||||
// `thumb_<name>` while the caller probed `thumb_w300_<name>`. The cache
|
||||
// never hit, so every request re-downloaded the original and ran Sharp,
|
||||
// and the file it left behind was in no cleanup list.
|
||||
await db('app_settings').where('setting_key', 'thumbnail_width')
|
||||
.update({ setting_value: 600 });
|
||||
try {
|
||||
const photo = await seedThumbPhoto();
|
||||
|
||||
const first = await imageProcessor.ensureThumbnailAtWidth(photo, 300);
|
||||
expect(first).toContain('thumb_w300_');
|
||||
|
||||
// The second call must be a cache hit on the key the first one wrote.
|
||||
const before = fs.statSync(path.join(process.env.STORAGE_PATH, first)).mtimeMs;
|
||||
const second = await imageProcessor.ensureThumbnailAtWidth(photo, 300);
|
||||
expect(second).toBe(first);
|
||||
expect(fs.statSync(path.join(process.env.STORAGE_PATH, second)).mtimeMs).toBe(before);
|
||||
|
||||
// ...and 600 is now the canonical, so it resolves to the plain thumbnail.
|
||||
const canonical = await imageProcessor.ensureThumbnailAtWidth(photo, 600);
|
||||
expect(canonical).not.toContain('thumb_w600_');
|
||||
|
||||
// Cleanup still reaches the w300 tier this install actually generated.
|
||||
expect(imageProcessor.thumbnailTierKeys(photo)).toContain(first);
|
||||
} finally {
|
||||
await db('app_settings').where('setting_key', 'thumbnail_width')
|
||||
.update({ setting_value: 300 });
|
||||
}
|
||||
});
|
||||
|
||||
it('generates a tier at the requested size', async () => {
|
||||
const photo = await seedThumbPhoto();
|
||||
const key = await imageProcessor.ensureThumbnailAtWidth(photo, 600);
|
||||
expect(key).toContain('thumb_w600_');
|
||||
const meta = await sharp(path.join(process.env.STORAGE_PATH, key)).metadata();
|
||||
expect(Math.max(meta.width, meta.height)).toBe(600);
|
||||
});
|
||||
|
||||
it('does not upscale past the source, which is why the tier is clamped', async () => {
|
||||
// The reason tileThumbnailWidth checks the short edge: ask a 400px
|
||||
// source for 900 and withoutEnlargement caps it, so the request buys a
|
||||
// Sharp run and a second cache entry for a file identical to the 300.
|
||||
const small = await seedThumbPhoto(500, 400);
|
||||
const key = await imageProcessor.ensureThumbnailAtWidth(small, 900);
|
||||
const meta = await sharp(path.join(process.env.STORAGE_PATH, key)).metadata();
|
||||
expect(Math.max(meta.width, meta.height)).toBeLessThan(900);
|
||||
});
|
||||
|
||||
it('resolves the canonical width to the normal thumbnail', async () => {
|
||||
const photo = await seedThumbPhoto();
|
||||
const key = await imageProcessor.ensureThumbnailAtWidth(photo, 300);
|
||||
expect(key).not.toContain('thumb_w300_');
|
||||
});
|
||||
|
||||
it('keeps the configured aspect ratio instead of forcing a square', async () => {
|
||||
// Thumbnails are square by default, but the settings API takes any
|
||||
// width/height in 50..1000. With fit:'cover' a 300x200 canonical and a
|
||||
// 600x600 tier are two different crops, so the photo would visibly
|
||||
// reframe as the tile size changed.
|
||||
await db('app_settings').where('setting_key', 'thumbnail_height')
|
||||
.update({ setting_value: 200 });
|
||||
try {
|
||||
const photo = await seedThumbPhoto();
|
||||
const key = await imageProcessor.ensureThumbnailAtWidth(photo, 600);
|
||||
const meta = await sharp(path.join(process.env.STORAGE_PATH, key)).metadata();
|
||||
expect(meta.width).toBe(600);
|
||||
expect(meta.height).toBe(400); // 600 * (200/300), not 600
|
||||
} finally {
|
||||
await db('app_settings').where('setting_key', 'thumbnail_height')
|
||||
.update({ setting_value: 300 });
|
||||
}
|
||||
});
|
||||
|
||||
it('never hands a video to Sharp', async () => {
|
||||
// A video's thumbnail is a poster frame from videoProcessor, not a
|
||||
// resize of the stored file. Without the short-circuit the tier path
|
||||
// would download the whole video (withLocalCopy, in full on S3) and
|
||||
// then fail to decode it — every request, since nothing caches a miss.
|
||||
const photo = await seedThumbPhoto();
|
||||
await db('photos').where({ id: photo.id })
|
||||
.update({ media_type: 'video', mime_type: 'video/mp4' });
|
||||
const video = await db('photos').where({ id: photo.id }).first();
|
||||
|
||||
const key = await imageProcessor.ensureThumbnailAtWidth(video, 900);
|
||||
expect(key).not.toContain('thumb_w900_');
|
||||
});
|
||||
|
||||
it('drops tiers when a rename moves the basename they are keyed on', async () => {
|
||||
// The key embeds the basename, so the DB update in renamePhotoFiles is
|
||||
// the point past which the old keys cannot be derived at all — a later
|
||||
// delete or archive computes the new ones and leaves these behind.
|
||||
const renameService = require('../../src/services/eventRenameService');
|
||||
const photo = await seedThumbPhoto();
|
||||
const event = await db('events').where({ id: photo.event_id }).first();
|
||||
|
||||
// Give it a filename the rename will actually rewrite.
|
||||
const dir = path.join(process.env.STORAGE_PATH, 'events/active', event.slug, 'individual');
|
||||
await fs.promises.mkdir(dir, { recursive: true });
|
||||
await sharp({ create: { width: 1200, height: 900, channels: 3, background: { r: 7, g: 7, b: 7 } } })
|
||||
.jpeg().toFile(path.join(dir, 'Old_Name_001.jpg'));
|
||||
await db('photos').where({ id: photo.id }).update({
|
||||
filename: 'Old_Name_001.jpg',
|
||||
path: `${event.slug}/individual/Old_Name_001.jpg`,
|
||||
});
|
||||
const renamable = await db('photos').where({ id: photo.id }).first();
|
||||
|
||||
const key = await imageProcessor.ensureThumbnailAtWidth(renamable, 600);
|
||||
const abs = path.join(process.env.STORAGE_PATH, key);
|
||||
expect(fs.existsSync(abs)).toBe(true);
|
||||
|
||||
await renameService.renamePhotoFiles(
|
||||
event.id, 'Old Name', 'New Name', event.slug, event.slug
|
||||
);
|
||||
|
||||
expect(await db('photos').where({ id: photo.id }).first())
|
||||
.toMatchObject({ filename: 'New_Name_001.jpg' });
|
||||
expect(fs.existsSync(abs)).toBe(false);
|
||||
});
|
||||
|
||||
it('leaves tiers alone when a rename does not move the basename', async () => {
|
||||
// Four storage deletes per photo is 20k calls against S3 for a
|
||||
// 5,000-photo event whose slug merely changed, so the sweep is gated on
|
||||
// the filename actually moving.
|
||||
const renameService = require('../../src/services/eventRenameService');
|
||||
const photo = await seedThumbPhoto();
|
||||
const event = await db('events').where({ id: photo.event_id }).first();
|
||||
|
||||
const key = await imageProcessor.ensureThumbnailAtWidth(photo, 600);
|
||||
const abs = path.join(process.env.STORAGE_PATH, key);
|
||||
|
||||
// The photo's filename carries no event-name prefix, so nothing moves.
|
||||
await renameService.renamePhotoFiles(
|
||||
event.id, 'Old Name', 'New Name', event.slug, event.slug
|
||||
);
|
||||
|
||||
expect(fs.existsSync(abs)).toBe(true);
|
||||
});
|
||||
|
||||
it('deleteThumbnailTiers removes them', async () => {
|
||||
const photo = await seedThumbPhoto();
|
||||
const key = await imageProcessor.ensureThumbnailAtWidth(photo, 600);
|
||||
const abs = path.join(process.env.STORAGE_PATH, key);
|
||||
expect(fs.existsSync(abs)).toBe(true);
|
||||
await imageProcessor.deleteThumbnailTiers(await db('photos').where({ id: photo.id }).first());
|
||||
expect(fs.existsSync(abs)).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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,123 +0,0 @@
|
||||
/**
|
||||
* Regression test for the maintenance-mode lockout in single-container mode.
|
||||
*
|
||||
* In the compose stack nginx serves the frontend, so a request for /admin/login
|
||||
* or /gallery/<slug> never reaches Express. The all-in-one image (#1042) has no
|
||||
* nginx: server.js serves the SPA itself, and maintenanceMiddleware is mounted
|
||||
* far ahead of that static block. Gating those paths therefore answered the
|
||||
* HTML document with 503 JSON, which broke two things at once —
|
||||
*
|
||||
* 1. an admin who enabled maintenance mode could never disable it, because
|
||||
* /admin/login and its /assets/ bundle would not load (the login *API* was
|
||||
* already exempt, but nothing could call it), and
|
||||
* 2. a guest saw raw JSON instead of the branded maintenance screen the
|
||||
* frontend already ships.
|
||||
*
|
||||
* The shell is inert HTML: it boots, calls /api/public/settings (exempt) and
|
||||
* renders MaintenanceMode itself, so letting it through costs nothing.
|
||||
*
|
||||
* The dividing line is taken from frontend/nginx.conf rather than invented:
|
||||
* paths nginx answers from the frontend container are exempt, paths it
|
||||
* proxy_passes to the backend stay gated. That makes the all-in-one image
|
||||
* behave exactly like compose in both directions. The gated half is where the
|
||||
* risk lives — a negative "everything that is not an API is a shell" rule
|
||||
* looks right and quietly un-gates /og/ (event names, cover images) and the
|
||||
* public CMS at the site root — so most of the cases below assert it.
|
||||
*/
|
||||
|
||||
const { maintenanceMiddleware } = require('../../src/middleware/maintenance');
|
||||
|
||||
jest.mock('../../src/database/db', () => {
|
||||
const settings = { setting_key: 'general_maintenance_mode', setting_value: 'true' };
|
||||
const db = jest.fn(() => ({
|
||||
where: jest.fn().mockReturnThis(),
|
||||
first: jest.fn().mockResolvedValue(settings),
|
||||
}));
|
||||
return { db };
|
||||
});
|
||||
jest.mock('../../src/utils/logger', () => ({
|
||||
error: jest.fn(), warn: jest.fn(), info: jest.fn(), debug: jest.fn(),
|
||||
}));
|
||||
|
||||
// Maintenance state is cached for a minute; each case starts from a clean read.
|
||||
const { clearMaintenanceCache } = require('../../src/middleware/maintenance');
|
||||
|
||||
async function run(path, { method = 'GET', authorization } = {}) {
|
||||
clearMaintenanceCache();
|
||||
const req = { path, method, headers: authorization ? { authorization } : {} };
|
||||
const res = {
|
||||
statusCode: null,
|
||||
body: null,
|
||||
status(code) { this.statusCode = code; return this; },
|
||||
json(payload) { this.body = payload; return this; },
|
||||
};
|
||||
const next = jest.fn();
|
||||
await maintenanceMiddleware(req, res, next);
|
||||
return { passed: next.mock.calls.length === 1, status: res.statusCode, body: res.body };
|
||||
}
|
||||
|
||||
describe('maintenanceMiddleware — SPA shell vs API split', () => {
|
||||
describe('passes the frontend shell through so the branded screen can render', () => {
|
||||
it.each([
|
||||
['/admin', 'admin shell entry'],
|
||||
['/admin/login', 'the page that calls the exempt login API'],
|
||||
['/assets/index-abc123.js', 'hashed bundle the shell loads'],
|
||||
['/gallery/some-event', 'guest gallery route'],
|
||||
['/customer/portal', 'customer portal route'],
|
||||
])('%s (%s)', async (path) => {
|
||||
const { passed } = await run(path);
|
||||
expect(passed).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('still gates everything that is not a shell', () => {
|
||||
it.each([
|
||||
['/api/gallery/some-event/verify', 'public gallery API'],
|
||||
['/api/photos/1', 'photo API'],
|
||||
['/photos/anything.jpg', 'backend-owned photo mount'],
|
||||
['/thumbnails/anything.jpg', 'backend-owned thumbnail mount'],
|
||||
['/fonts/anything.woff2', 'backend-owned font mount'],
|
||||
// nginx proxy_passes these to the backend, so compose gates them today
|
||||
// and the all-in-one image must not be the one deployment that does not.
|
||||
['/', 'site root — nginx `location = /` hands this to the public CMS'],
|
||||
['/og/gallery/some-event', 'OG renderer: leaks the event name'],
|
||||
['/og/gallery/some-event/cover', 'OG cover: leaks the hero thumbnail'],
|
||||
['/s/abc123', 'short-link renderer'],
|
||||
['/robots.txt', 'proxied one-to-one by nginx'],
|
||||
['/favicon.ico', 'proxied one-to-one by nginx'],
|
||||
])('%s (%s) returns 503', async (path) => {
|
||||
const { passed, status, body } = await run(path);
|
||||
expect(passed).toBe(false);
|
||||
expect(status).toBe(503);
|
||||
expect(body).toMatchObject({ maintenance: true });
|
||||
});
|
||||
|
||||
it('does not let a non-GET request masquerade as a shell load', async () => {
|
||||
const { passed, status } = await run('/api/gallery/some-event/verify', { method: 'POST' });
|
||||
expect(passed).toBe(false);
|
||||
expect(status).toBe(503);
|
||||
});
|
||||
});
|
||||
|
||||
describe('keeps the pre-existing admin exemptions', () => {
|
||||
it('admin login API stays reachable', async () => {
|
||||
expect((await run('/api/auth/admin/login', { method: 'POST' })).passed).toBe(true);
|
||||
});
|
||||
|
||||
it('/api/public/settings stays reachable so the shell can read the flag', async () => {
|
||||
expect((await run('/api/public/settings')).passed).toBe(true);
|
||||
});
|
||||
|
||||
it('an authenticated admin still reaches /api/admin', async () => {
|
||||
const { passed } = await run('/api/admin/events', { authorization: 'Bearer token' });
|
||||
expect(passed).toBe(true);
|
||||
});
|
||||
|
||||
it('an unauthenticated /api/admin request is not served by this middleware', async () => {
|
||||
// isAdminRoute suppresses the 503 so the auth layer can answer 401.
|
||||
const { passed, status } = await run('/api/admin/events');
|
||||
expect(passed).toBe(true);
|
||||
expect(status).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,166 +0,0 @@
|
||||
/**
|
||||
* Migration 177 (#1074) — face recognition schema.
|
||||
*
|
||||
* The acceptance criteria for #1074 name three properties explicitly, so
|
||||
* they get tests rather than a manual check:
|
||||
*
|
||||
* - idempotent on re-run,
|
||||
* - a working down(),
|
||||
* - and — the one that matters most — installing it must NOT enqueue
|
||||
* anything. A `face_status` column defaulting to 'pending' would put
|
||||
* every existing photo on every install into a queue the operator never
|
||||
* asked for, on installs with no sidecar at all.
|
||||
*/
|
||||
|
||||
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-mig177-')), 'db.sqlite',
|
||||
);
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'mig177-test-secret';
|
||||
|
||||
const { bootCrmDb } = require('../integration/helpers/crmDb');
|
||||
const migration = require('../../migrations/core/177_add_face_recognition');
|
||||
|
||||
describe('migration 177 — face recognition schema', () => {
|
||||
let db; let cleanup;
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => { if (cleanup) await cleanup(); });
|
||||
|
||||
it('creates both tables with the columns the pipeline writes', async () => {
|
||||
expect(await db.schema.hasTable('photo_faces')).toBe(true);
|
||||
expect(await db.schema.hasTable('event_people')).toBe(true);
|
||||
|
||||
for (const col of [
|
||||
'photo_id', 'event_id', 'bbox_x', 'bbox_y', 'bbox_w', 'bbox_h',
|
||||
'det_score', 'yaw', 'pitch', 'blur', 'embedding', 'model_version',
|
||||
'person_id', 'created_at',
|
||||
]) {
|
||||
expect(await db.schema.hasColumn('photo_faces', col)).toBe(true);
|
||||
}
|
||||
|
||||
for (const col of [
|
||||
'event_id', 'label', 'cover_face_id', 'centroid', 'face_count_total',
|
||||
'model_version', 'is_hidden', 'is_ignored',
|
||||
]) {
|
||||
expect(await db.schema.hasColumn('event_people', col)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('adds the photos and events columns', async () => {
|
||||
for (const col of ['face_status', 'face_count', 'face_started_at', 'face_error']) {
|
||||
expect(await db.schema.hasColumn('photos', col)).toBe(true);
|
||||
}
|
||||
for (const col of [
|
||||
'face_recognition_enabled', 'faces_visible_to_guests', 'faces_last_scan_at',
|
||||
]) {
|
||||
expect(await db.schema.hasColumn('events', col)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('enqueues nothing — face_status has no default', async () => {
|
||||
// The whole "zero behaviour change by default" guarantee rests on this.
|
||||
const [{ id: eventId }] = await db('events').insert({
|
||||
slug: 'mig177-event',
|
||||
event_type: 'wedding',
|
||||
event_name: 'Migration 177',
|
||||
event_date: '2026-01-01',
|
||||
host_email: 'h@example.com',
|
||||
admin_email: 'a@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: 'mig177-share',
|
||||
expires_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
|
||||
const eid = typeof eventId === 'object' ? eventId.id : eventId;
|
||||
await db('photos').insert({
|
||||
event_id: eid, filename: 'a.jpg', path: '/tmp/a.jpg', type: 'individual',
|
||||
});
|
||||
|
||||
const row = await db('photos').where({ event_id: eid }).first();
|
||||
expect(row.face_status).toBeNull();
|
||||
expect(await db('photo_faces').count({ c: '*' }).first()).toMatchObject({ c: 0 });
|
||||
});
|
||||
|
||||
it('seeds the tunable thresholds rather than hardcoding them', async () => {
|
||||
// Immich's clustering guide exists because no single threshold survives
|
||||
// contact with every library — these must be operator-reachable.
|
||||
const keys = [
|
||||
'face_match_threshold', 'face_min_cluster_size',
|
||||
'face_quality_min_score', 'face_quality_min_px',
|
||||
];
|
||||
const rows = await db('app_settings').whereIn('setting_key', keys);
|
||||
expect(rows).toHaveLength(keys.length);
|
||||
expect(rows.every((r) => r.setting_type === 'faces')).toBe(true);
|
||||
});
|
||||
|
||||
it('is idempotent on re-run', async () => {
|
||||
await expect(migration.up(db)).resolves.not.toThrow();
|
||||
// And did not duplicate the settings rows.
|
||||
const rows = await db('app_settings').where('setting_key', 'face_match_threshold');
|
||||
expect(rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('down() removes everything it added, and up() restores it', async () => {
|
||||
await migration.down(db);
|
||||
|
||||
expect(await db.schema.hasTable('photo_faces')).toBe(false);
|
||||
expect(await db.schema.hasTable('event_people')).toBe(false);
|
||||
expect(await db.schema.hasColumn('photos', 'face_status')).toBe(false);
|
||||
expect(await db.schema.hasColumn('events', 'face_recognition_enabled')).toBe(false);
|
||||
expect(await db('app_settings').where('setting_key', 'face_match_threshold')).toHaveLength(0);
|
||||
|
||||
await migration.up(db);
|
||||
expect(await db.schema.hasTable('photo_faces')).toBe(true);
|
||||
expect(await db.schema.hasColumn('photos', 'face_status')).toBe(true);
|
||||
});
|
||||
|
||||
it('cascades face rows when a photo is deleted', async () => {
|
||||
// #1074 acceptance criterion: deleting a photo removes its face rows.
|
||||
//
|
||||
// SQLite ignores foreign keys unless the pragma is on, and PicPeak does
|
||||
// NOT enable it globally (a large amount of existing data and fixtures
|
||||
// would start failing). So the cascade below proves only that the schema
|
||||
// declares it correctly — the code does not RELY on it. Deletion paths
|
||||
// purge face rows explicitly; see faceProcessor.purgeEvent /
|
||||
// purgePhotoFaces and the erasure tests in facePrivacy.test.js.
|
||||
await db.raw('PRAGMA foreign_keys = ON');
|
||||
|
||||
const [{ id: eventId }] = await db('events').insert({
|
||||
slug: 'mig177-cascade',
|
||||
event_type: 'wedding',
|
||||
event_name: 'Cascade',
|
||||
event_date: '2026-01-01',
|
||||
host_email: 'h@example.com',
|
||||
admin_email: 'a@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: 'mig177-cascade-share',
|
||||
expires_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
const eid = typeof eventId === 'object' ? eventId.id : eventId;
|
||||
|
||||
const [{ id: photoId }] = await db('photos')
|
||||
.insert({ event_id: eid, filename: 'c.jpg', path: '/tmp/c.jpg', type: 'individual' })
|
||||
.returning('id');
|
||||
const pid = typeof photoId === 'object' ? photoId.id : photoId;
|
||||
|
||||
await db('photo_faces').insert({
|
||||
photo_id: pid,
|
||||
event_id: eid,
|
||||
bbox_x: 1, bbox_y: 2, bbox_w: 3, bbox_h: 4,
|
||||
model_version: 'test',
|
||||
created_at: new Date().toISOString(),
|
||||
});
|
||||
expect(await db('photo_faces').where({ photo_id: pid })).toHaveLength(1);
|
||||
|
||||
await db('photos').where({ id: pid }).del();
|
||||
expect(await db('photo_faces').where({ photo_id: pid })).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -1,63 +0,0 @@
|
||||
/**
|
||||
* The person-faces query must table-qualify its WHERE (#1096).
|
||||
*
|
||||
* `photo_faces` and `photos` BOTH have an event_id, so the moment the join was
|
||||
* added a bare `where({ event_id })` became ambiguous. Postgres refuses it —
|
||||
*
|
||||
* column reference "event_id" is ambiguous
|
||||
*
|
||||
* — and the endpoint 500s, which took the Split dialog down with it on every
|
||||
* PostgreSQL install. SQLite resolves the ambiguity silently, which is why the
|
||||
* suite stayed green and this reached production.
|
||||
*
|
||||
* Two deliberate choices about HOW this is tested:
|
||||
*
|
||||
* 1. It imports the builder the route actually calls. An earlier version of
|
||||
* this file re-declared the query locally, which meant the route could
|
||||
* regress to the bare form while these assertions kept passing — a test
|
||||
* that documents a bug without guarding it.
|
||||
* 2. It asserts on the emitted SQL rather than executing it. A round-trip test
|
||||
* would run against the SQLite the suite uses and prove nothing about the
|
||||
* engine the bug affects.
|
||||
*/
|
||||
|
||||
process.env.NODE_ENV = 'test';
|
||||
|
||||
const knex = require('knex')({ client: 'pg' });
|
||||
const { buildPersonFacesQuery, PERSON_FACES_LIMIT } = require('../src/routes/adminEvents/faces');
|
||||
|
||||
const sql = () => buildPersonFacesQuery(knex, 857, 143).toString();
|
||||
|
||||
describe('person faces query', () => {
|
||||
it('is the query the route runs, not a copy of it', () => {
|
||||
expect(typeof buildPersonFacesQuery).toBe('function');
|
||||
expect(sql()).toContain('from "photo_faces"');
|
||||
});
|
||||
|
||||
it('qualifies event_id with its table', () => {
|
||||
// The bare form is what Postgres rejects.
|
||||
expect(sql()).toContain('"photo_faces"."event_id"');
|
||||
expect(sql()).not.toMatch(/where\s+"event_id"/i);
|
||||
});
|
||||
|
||||
it('qualifies person_id too, so the join cannot shadow it either', () => {
|
||||
expect(sql()).toContain('"photo_faces"."person_id"');
|
||||
expect(sql()).not.toMatch(/and\s+"person_id"\s*=/i);
|
||||
});
|
||||
|
||||
it('still joins photos for the original dimensions', () => {
|
||||
// The dimensions are what faceCropStyle scales the bbox against; without
|
||||
// the join the crop maths has nothing to work from.
|
||||
const s = sql();
|
||||
expect(s).toContain('inner join "photos"');
|
||||
expect(s).toContain('"photos"."width"');
|
||||
expect(s).toContain('"photos"."height"');
|
||||
});
|
||||
|
||||
it('caps the list at the limit the UI is told about', () => {
|
||||
// The viewer reports truncation using this same number; if they drift, it
|
||||
// silently claims a person has fewer appearances than they do.
|
||||
expect(PERSON_FACES_LIMIT).toBe(500);
|
||||
expect(sql()).toContain(`limit ${PERSON_FACES_LIMIT}`);
|
||||
});
|
||||
});
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -1,42 +0,0 @@
|
||||
/**
|
||||
* Source-inspection contract test for #1078.
|
||||
*
|
||||
* POST /api/admin/thumbnails/regenerate-previews hands its selected rows to
|
||||
* ensurePreviewImage, which branches on `source_origin` (and then reads
|
||||
* `external_relpath` / `filename`) to reach an external/reference photo on its
|
||||
* media mount. When the select list omitted those columns, every external row
|
||||
* looked managed, resolvePhotoStorageKey returned null, and the endpoint
|
||||
* reported success while silently generating nothing for reference galleries.
|
||||
*/
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
describe('regenerate-previews selects the columns ensurePreviewImage branches on (#1078)', () => {
|
||||
const src = fs.readFileSync(
|
||||
path.join(__dirname, '..', '..', 'src', 'routes', 'adminThumbnails.js'),
|
||||
'utf8',
|
||||
);
|
||||
|
||||
// The select feeding the regenerate-previews handler, from the route
|
||||
// declaration to the end of that statement.
|
||||
const selectStatement = (() => {
|
||||
const routeIdx = src.indexOf('/regenerate-previews');
|
||||
expect(routeIdx).toBeGreaterThan(-1);
|
||||
const selectIdx = src.indexOf('.select(', routeIdx);
|
||||
expect(selectIdx).toBeGreaterThan(-1);
|
||||
return src.slice(selectIdx, src.indexOf(';', selectIdx));
|
||||
})();
|
||||
|
||||
it.each(['source_origin', 'external_relpath', 'filename'])(
|
||||
'selects %s',
|
||||
(column) => {
|
||||
expect(selectStatement).toContain(`'${column}'`);
|
||||
}
|
||||
);
|
||||
|
||||
it('still selects the columns the managed path needs', () => {
|
||||
for (const column of ['id', 'event_id', 'path', 'media_type', 'mime_type', 'preview_path']) {
|
||||
expect(selectStatement).toContain(`'${column}'`);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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,100 +0,0 @@
|
||||
/**
|
||||
* CORS posture of the protected-image responses (#1116).
|
||||
*
|
||||
* secureImageMiddleware used to set its own Access-Control-Allow-Origin,
|
||||
* overwriting the one cors(corsOptions) had already computed for the request.
|
||||
* That was worse in both directions:
|
||||
*
|
||||
* unresolved -> '*', which with the credentials:true that cors() sets is an
|
||||
* invalid pair every browser rejects outright
|
||||
* resolved -> the frontend origin, even when the request legitimately came
|
||||
* from the allowlisted ADMIN_URL
|
||||
*
|
||||
* The header now belongs to cors() alone. These tests are mounted on a real
|
||||
* Express app with the same middleware order as server.js — a unit test against
|
||||
* a response double cannot see middleware composition, which is precisely how
|
||||
* the first version of this fix looked correct while still being wrong.
|
||||
*/
|
||||
|
||||
process.env.NODE_ENV = 'test';
|
||||
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const request = require('supertest');
|
||||
|
||||
jest.mock('../src/database/db', () => ({ db: jest.fn() }));
|
||||
|
||||
// A frontend origin IS resolvable here, deliberately. With the resolver empty
|
||||
// (the default in tests) merely GUARDING the assignment looks identical to
|
||||
// removing it — the admin-origin case below is what tells them apart, and it
|
||||
// is the common one in production.
|
||||
jest.mock('../src/utils/frontendUrl', () => ({
|
||||
getFrontendBaseUrlSync: () => 'https://gallery.example.com',
|
||||
}));
|
||||
|
||||
jest.useFakeTimers(); // the module schedules a cleanup setInterval at require time
|
||||
const secureImageMiddleware = require('../src/middleware/secureImageMiddleware');
|
||||
|
||||
const FRONTEND = 'https://gallery.example.com';
|
||||
const ADMIN = 'https://admin.example.com';
|
||||
|
||||
/** Mirrors server.js: cors() on /api, then the route sets its own headers. */
|
||||
function buildApp() {
|
||||
const app = express();
|
||||
app.use('/api', cors({
|
||||
origin: (origin, cb) => cb(null, !origin || [FRONTEND, ADMIN].includes(origin)),
|
||||
credentials: true,
|
||||
}));
|
||||
app.get('/api/secure-images/:id', (req, res) => {
|
||||
secureImageMiddleware.setSecurityHeaders(res);
|
||||
res.status(200).send('ok');
|
||||
});
|
||||
return app;
|
||||
}
|
||||
|
||||
afterAll(() => {
|
||||
jest.clearAllTimers();
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
describe('protected-image CORS headers', () => {
|
||||
it('never emits a wildcard origin', async () => {
|
||||
// '*' alongside the credentials:true that cors() sets is invalid, and the
|
||||
// browser drops the whole response.
|
||||
const res = await request(buildApp()).get('/api/secure-images/1').set('Origin', FRONTEND);
|
||||
expect(res.headers['access-control-allow-origin']).not.toBe('*');
|
||||
});
|
||||
|
||||
it('preserves the cors() answer for an allowlisted origin', async () => {
|
||||
const res = await request(buildApp()).get('/api/secure-images/1').set('Origin', FRONTEND);
|
||||
expect(res.headers['access-control-allow-origin']).toBe(FRONTEND);
|
||||
expect(res.headers['access-control-allow-credentials']).toBe('true');
|
||||
});
|
||||
|
||||
it('does not repoint an allowlisted admin origin at the frontend', async () => {
|
||||
// The regression the old code caused, and the case a guarded assignment
|
||||
// still gets wrong: the resolver returns the FRONTEND origin here, so any
|
||||
// code that writes it would stamp the wrong origin on an admin request
|
||||
// that cors() had already allowed, and the browser would reject it.
|
||||
const res = await request(buildApp()).get('/api/secure-images/1').set('Origin', ADMIN);
|
||||
expect(res.headers['access-control-allow-origin']).toBe(ADMIN);
|
||||
});
|
||||
|
||||
it('stays absent for a disallowed origin', async () => {
|
||||
const res = await request(buildApp()).get('/api/secure-images/1').set('Origin', 'https://evil.example.com');
|
||||
expect(res.headers).not.toHaveProperty('access-control-allow-origin');
|
||||
});
|
||||
|
||||
it('stays absent when there is no Origin at all', async () => {
|
||||
const res = await request(buildApp()).get('/api/secure-images/1');
|
||||
expect(res.headers).not.toHaveProperty('access-control-allow-origin');
|
||||
});
|
||||
|
||||
it('still sets the route-specific security headers', async () => {
|
||||
const res = await request(buildApp()).get('/api/secure-images/1').set('Origin', FRONTEND);
|
||||
expect(res.headers['x-content-type-options']).toBe('nosniff');
|
||||
expect(res.headers['x-frame-options']).toBe('DENY');
|
||||
expect(res.headers['cache-control']).toContain('no-store');
|
||||
expect(res.headers['access-control-allow-methods']).toBe('GET');
|
||||
});
|
||||
});
|
||||
@@ -1,159 +0,0 @@
|
||||
/**
|
||||
* Regression test: business documents must be written under STORAGE_PATH.
|
||||
*
|
||||
* quoteService.persistDocPdf, the invoice sending/reminder writers and the
|
||||
* contract signature writers all built their target from
|
||||
* `path.join(process.cwd(), 'storage', 'business-docs', ...)`. Both compose
|
||||
* files pin STORAGE_PATH=/app/storage and the image's WORKDIR is /app, so the
|
||||
* two expressions name the same directory and the bug was invisible on a stock
|
||||
* deployment. Point STORAGE_PATH anywhere else — a NAS mount, a second disk,
|
||||
* the single-container image's /data volume — and quotes, invoices, Mahnungen
|
||||
* and contract PDFs were written outside the configured storage root, so they
|
||||
* were missed by backups and lost when the container was replaced.
|
||||
*
|
||||
* Rather than assert on internals, this drives the module boundary the fix
|
||||
* changed: getStoragePath() is the one resolver, so a temporary STORAGE_PATH
|
||||
* must be where the bytes land.
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
describe('business documents honour STORAGE_PATH', () => {
|
||||
let tmpRoot;
|
||||
let originalStoragePath;
|
||||
|
||||
beforeEach(() => {
|
||||
originalStoragePath = process.env.STORAGE_PATH;
|
||||
tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-storage-'));
|
||||
process.env.STORAGE_PATH = tmpRoot;
|
||||
jest.resetModules();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (originalStoragePath === undefined) delete process.env.STORAGE_PATH;
|
||||
else process.env.STORAGE_PATH = originalStoragePath;
|
||||
fs.rmSync(tmpRoot, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('getStoragePath is the resolver the writers share', () => {
|
||||
const { getStoragePath } = require('../../src/config/storage');
|
||||
expect(getStoragePath()).toBe(tmpRoot);
|
||||
});
|
||||
|
||||
it('no business-document writer still targets process.cwd()/storage', () => {
|
||||
// Whitespace is collapsed before matching on purpose. The first version of
|
||||
// this test compared against the single-line literal and therefore missed
|
||||
// persistSignatureImage(), whose identical path.join was simply spread over
|
||||
// seven lines — it reported green while signature PNGs still wrote outside
|
||||
// STORAGE_PATH. Formatting must not decide whether a bug is visible.
|
||||
const writers = [
|
||||
'src/services/quoteService.js',
|
||||
'src/services/invoice/sending.js',
|
||||
'src/services/invoice/reminders.js',
|
||||
'src/services/contract/signatureAssets.js',
|
||||
'src/routes/adminDev.js',
|
||||
];
|
||||
const offenders = writers.filter((rel) => {
|
||||
const source = fs.readFileSync(path.join(__dirname, '../../', rel), 'utf8');
|
||||
return /process\.cwd\(\),'storage'/.test(source.replace(/\s+/g, ''));
|
||||
});
|
||||
expect(offenders).toEqual([]);
|
||||
});
|
||||
|
||||
it('generated contract PDFs pass the containment check that serves them', () => {
|
||||
// assertContractPdfPath guards the admin and public contract download
|
||||
// routes. It listed only <cwd>/storage/business-docs/contract, so once the
|
||||
// writers moved to STORAGE_PATH every freshly generated contract was
|
||||
// refused with PATH_OUTSIDE_STORAGE — a worse failure than the bug being
|
||||
// fixed. Both roots must be accepted.
|
||||
const { assertContractPdfPath } = require('../../src/utils/safePath');
|
||||
const { getStoragePath } = require('../../src/config/storage');
|
||||
|
||||
// assertPathInside realpaths both the file and each root, so the guard only
|
||||
// means anything against a filesystem that actually has them — write them.
|
||||
const write = (...segments) => {
|
||||
const p = path.join(getStoragePath(), 'business-docs', 'contract', ...segments);
|
||||
fs.mkdirSync(path.dirname(p), { recursive: true });
|
||||
fs.writeFileSync(p, 'bytes');
|
||||
return p;
|
||||
};
|
||||
|
||||
const generated = write('2026', 'C-2026-0001.pdf');
|
||||
expect(() => assertContractPdfPath(generated)).not.toThrow();
|
||||
|
||||
// Signature PNGs live under the same root and are served by the same guard.
|
||||
const signature = write('signatures', '7', 'customer-1.png');
|
||||
expect(() => assertContractPdfPath(signature)).not.toThrow();
|
||||
|
||||
// And the guard still refuses a real file outside every allowed root.
|
||||
const foreign = path.join(tmpRoot, 'outside.pdf');
|
||||
fs.writeFileSync(foreign, 'bytes');
|
||||
expect(() => assertContractPdfPath(foreign)).toThrow(/outside the storage roots/i);
|
||||
});
|
||||
|
||||
it('the guard takes its root from the shared resolver, not its own fallback', () => {
|
||||
// The regression this pins: the guard used to compute
|
||||
// `STORAGE_PATH || <cwd>/storage` itself. That agrees with getStoragePath()
|
||||
// only while STORAGE_PATH is set — unset, the shared resolver falls back
|
||||
// module-relative to <repo>/storage while the guard fell back to
|
||||
// <cwd>/storage, and the backend is normally started from backend/. Writers
|
||||
// and guard then disagreed and contract downloads 403'd.
|
||||
//
|
||||
// Mocking the resolver is what makes this provable AND safe. If the guard
|
||||
// consumes getStoragePath(), the mock moves its root; if it rolled its own
|
||||
// expression, the mock would have no effect and the assertion fails. It
|
||||
// also keeps every path inside the tmpdir — an earlier version of this test
|
||||
// deleted `<resolved root>/business-docs` in cleanup, which with
|
||||
// STORAGE_PATH unset resolves to a developer's real, gitignored
|
||||
// <repo>/storage and would have destroyed local documents on `npm test`.
|
||||
jest.resetModules();
|
||||
jest.doMock('../../src/config/storage', () => ({ getStoragePath: () => tmpRoot }));
|
||||
|
||||
const { assertContractPdfPath } = require('../../src/utils/safePath');
|
||||
|
||||
const root = path.join(tmpRoot, 'business-docs', 'contract', '2026');
|
||||
fs.mkdirSync(root, { recursive: true });
|
||||
const generated = path.join(root, 'C-2026-0002.pdf');
|
||||
fs.writeFileSync(generated, 'bytes');
|
||||
|
||||
expect(() => assertContractPdfPath(generated)).not.toThrow();
|
||||
|
||||
jest.dontMock('../../src/config/storage');
|
||||
});
|
||||
|
||||
it('writes land under STORAGE_PATH, not the working directory', () => {
|
||||
const { getStoragePath } = require('../../src/config/storage');
|
||||
|
||||
// Mirror what persistDocPdf does: derive the root, create it, write.
|
||||
const root = path.join(getStoragePath(), 'business-docs', 'quote', '2026');
|
||||
fs.mkdirSync(root, { recursive: true });
|
||||
const filePath = path.join(root, 'Q-2026-0001.pdf');
|
||||
fs.writeFileSync(filePath, 'pdf-bytes');
|
||||
|
||||
expect(fs.existsSync(filePath)).toBe(true);
|
||||
expect(filePath.startsWith(tmpRoot)).toBe(true);
|
||||
// And crucially NOT beside the process working directory.
|
||||
expect(filePath.startsWith(path.join(process.cwd(), 'storage'))).toBe(false);
|
||||
});
|
||||
|
||||
it('the PDF font lookup consults the storage root before the legacy path', () => {
|
||||
// A custom font under STORAGE_PATH/fonts used to be unreachable, so the
|
||||
// document silently rendered with the built-in face instead.
|
||||
const fontDir = path.join(tmpRoot, 'fonts');
|
||||
fs.mkdirSync(fontDir, { recursive: true });
|
||||
const fontPath = path.join(fontDir, 'Brand.ttf');
|
||||
fs.writeFileSync(fontPath, 'ttf');
|
||||
|
||||
const { getStoragePath } = require('../../src/config/storage');
|
||||
const raw = 'Brand.ttf';
|
||||
const candidates = [
|
||||
path.join(getStoragePath(), raw.replace(/^\/+/, '')),
|
||||
path.join(getStoragePath(), 'fonts', path.basename(raw)),
|
||||
path.join(process.cwd(), 'storage', 'fonts', path.basename(raw)),
|
||||
];
|
||||
const found = candidates.find((p) => fs.existsSync(p));
|
||||
expect(found).toBe(fontPath);
|
||||
});
|
||||
});
|
||||
@@ -1,218 +0,0 @@
|
||||
/**
|
||||
* Regression tests for #1078 — ensurePreviewImage must generate previews for
|
||||
* external/reference photos, not silently fall back to the full-size original.
|
||||
*
|
||||
* resolvePhotoStorageKey returns null for external photos by design, and that
|
||||
* null used to be handed straight to withLocalCopy, which throws. The lightbox
|
||||
* preview route caught the throw and redirected to the original, so a gallery
|
||||
* whose photos all live on an external mount paid full size on every open —
|
||||
* the exact cost the preview tier (#492) exists to avoid.
|
||||
*/
|
||||
const path = require('path');
|
||||
const fs = require('fs').promises;
|
||||
const os = require('os');
|
||||
const sharp = require('sharp');
|
||||
|
||||
// Must be set before externalMediaService is first required: it caches the
|
||||
// resolved root on first call, and the dir has to exist to win over the
|
||||
// container default.
|
||||
const EXTERNAL_ROOT = path.join(os.tmpdir(), `picpeak-ext-media-${process.pid}`);
|
||||
process.env.EXTERNAL_MEDIA_ROOT = EXTERNAL_ROOT;
|
||||
|
||||
jest.mock('../../src/database/db', () => {
|
||||
const state = { event: null, updates: [] };
|
||||
const api = (table) => {
|
||||
if (table === 'events') {
|
||||
return { where: () => ({ first: async () => state.event }) };
|
||||
}
|
||||
if (table === 'photos') {
|
||||
return {
|
||||
where: (criteria) => ({
|
||||
update: async (values) => {
|
||||
state.updates.push({ criteria, values });
|
||||
return 1;
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
throw new Error(`unexpected table in test: ${table}`);
|
||||
};
|
||||
api.__state = state;
|
||||
return { db: api };
|
||||
});
|
||||
|
||||
const LocalFsStorage = require('../../src/services/storage/LocalFsStorage');
|
||||
const storageModule = require('../../src/services/storage');
|
||||
const { db } = require('../../src/database/db');
|
||||
|
||||
const EVENT = {
|
||||
id: 7,
|
||||
slug: 'nas-wedding',
|
||||
source_mode: 'reference',
|
||||
external_path: 'weddings/2026-08-smith',
|
||||
};
|
||||
|
||||
async function writeSourceJpeg(absPath, { width = 2400, height = 1600 } = {}) {
|
||||
await fs.mkdir(path.dirname(absPath), { recursive: true });
|
||||
const buf = Buffer.alloc(width * height * 3);
|
||||
for (let i = 0; i < buf.length; i++) buf[i] = (i * 7) % 256;
|
||||
await sharp(buf, { raw: { width, height, channels: 3 } }).jpeg({ quality: 90 }).toFile(absPath);
|
||||
}
|
||||
|
||||
describe('ensurePreviewImage — external/reference sources (#1078)', () => {
|
||||
let storage;
|
||||
let storageRoot;
|
||||
let imageProcessor;
|
||||
|
||||
beforeAll(async () => {
|
||||
storageRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'picpeak-preview-store-'));
|
||||
storage = new LocalFsStorage({ root: storageRoot });
|
||||
await storage.init();
|
||||
storageModule.setStorageForTesting(storage);
|
||||
|
||||
// Require AFTER the storage injection so the module sees it.
|
||||
delete require.cache[require.resolve('../../src/services/imageProcessor')];
|
||||
imageProcessor = require('../../src/services/imageProcessor');
|
||||
|
||||
await fs.mkdir(path.join(EXTERNAL_ROOT, EVENT.external_path), { recursive: true });
|
||||
}, 30000);
|
||||
|
||||
afterAll(async () => {
|
||||
storageModule.resetStorage();
|
||||
await fs.rm(storageRoot, { recursive: true, force: true }).catch(() => {});
|
||||
await fs.rm(EXTERNAL_ROOT, { recursive: true, force: true }).catch(() => {});
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
db.__state.event = EVENT;
|
||||
db.__state.updates = [];
|
||||
});
|
||||
|
||||
it.each(['external', 'reference'])(
|
||||
'generates a downscaled preview for a %s photo off the media mount',
|
||||
async (sourceOrigin) => {
|
||||
const relpath = `${sourceOrigin}-shot.jpg`;
|
||||
await writeSourceJpeg(path.join(EXTERNAL_ROOT, EVENT.external_path, relpath));
|
||||
|
||||
const photo = {
|
||||
id: sourceOrigin === 'external' ? 101 : 102,
|
||||
event_id: EVENT.id,
|
||||
source_origin: sourceOrigin,
|
||||
external_relpath: relpath,
|
||||
filename: relpath,
|
||||
preview_path: null,
|
||||
};
|
||||
|
||||
const key = await imageProcessor.ensurePreviewImage(photo);
|
||||
|
||||
// Per-photo basename so two events referencing the same NAS filename
|
||||
// can't clobber each other's preview.
|
||||
expect(key).toBe(`previews/preview_ext${photo.id}_${relpath}`);
|
||||
expect(await storage.exists(key)).toBe(true);
|
||||
|
||||
const meta = await sharp(storage.resolveLocalPath(key)).metadata();
|
||||
expect(meta.format).toBe('jpeg');
|
||||
// 2400x1600 capped at the 1920 long edge, aspect preserved.
|
||||
expect(meta.width).toBe(1920);
|
||||
expect(meta.height).toBe(1280);
|
||||
|
||||
// The generated key is persisted so the next open short-circuits.
|
||||
expect(db.__state.updates).toEqual([
|
||||
{ criteria: { id: photo.id }, values: { preview_path: key } },
|
||||
]);
|
||||
}
|
||||
);
|
||||
|
||||
it('short-circuits on an existing valid preview instead of regenerating', async () => {
|
||||
const relpath = 'already-previewed.jpg';
|
||||
await writeSourceJpeg(path.join(EXTERNAL_ROOT, EVENT.external_path, relpath));
|
||||
const photo = {
|
||||
id: 103,
|
||||
event_id: EVENT.id,
|
||||
source_origin: 'external',
|
||||
external_relpath: relpath,
|
||||
filename: relpath,
|
||||
preview_path: null,
|
||||
};
|
||||
|
||||
const first = await imageProcessor.ensurePreviewImage(photo);
|
||||
db.__state.updates = [];
|
||||
|
||||
const second = await imageProcessor.ensurePreviewImage({ ...photo, preview_path: first });
|
||||
expect(second).toBe(first);
|
||||
expect(db.__state.updates).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns null (never throws) when the external source is missing', async () => {
|
||||
const photo = {
|
||||
id: 104,
|
||||
event_id: EVENT.id,
|
||||
source_origin: 'external',
|
||||
external_relpath: 'not-on-the-mount.jpg',
|
||||
filename: 'not-on-the-mount.jpg',
|
||||
preview_path: null,
|
||||
};
|
||||
|
||||
await expect(imageProcessor.ensurePreviewImage(photo)).resolves.toBeNull();
|
||||
expect(db.__state.updates).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns null (never throws) for a row with no source_origin in a reference event', async () => {
|
||||
// Mode falls back to event.source_mode = 'reference', so
|
||||
// resolvePhotoStorageKey yields null. That used to reach withLocalCopy and
|
||||
// throw out of ensurePreviewImage instead of honouring null-on-failure.
|
||||
const photo = {
|
||||
id: 105,
|
||||
event_id: EVENT.id,
|
||||
source_origin: null,
|
||||
external_relpath: null,
|
||||
filename: 'orphan.jpg',
|
||||
path: 'nas-wedding/individual/orphan.jpg',
|
||||
preview_path: null,
|
||||
};
|
||||
|
||||
await expect(imageProcessor.ensurePreviewImage(photo)).resolves.toBeNull();
|
||||
expect(db.__state.updates).toEqual([]);
|
||||
});
|
||||
|
||||
it('branches on source_origin, so a row selected without it looks managed', async () => {
|
||||
// Pins why the /regenerate-previews caller must select source_origin:
|
||||
// an external row missing that column takes the managed path, where
|
||||
// resolvePhotoStorageKey yields null and generation is skipped.
|
||||
const relpath = 'column-starved.jpg';
|
||||
await writeSourceJpeg(path.join(EXTERNAL_ROOT, EVENT.external_path, relpath));
|
||||
const starved = {
|
||||
id: 106,
|
||||
event_id: EVENT.id,
|
||||
external_relpath: relpath,
|
||||
preview_path: null,
|
||||
};
|
||||
|
||||
await expect(imageProcessor.ensurePreviewImage(starved)).resolves.toBeNull();
|
||||
await expect(
|
||||
imageProcessor.ensurePreviewImage({ ...starved, source_origin: 'external', filename: relpath })
|
||||
).resolves.toBe(`previews/preview_ext106_${relpath}`);
|
||||
});
|
||||
|
||||
it('still routes managed photos through the storage backend', async () => {
|
||||
const sourceKey = 'events/active/managed-event/individual/managed.jpg';
|
||||
const localSource = path.join(os.tmpdir(), `picpeak-managed-${process.pid}.jpg`);
|
||||
await writeSourceJpeg(localSource, { width: 800, height: 600 });
|
||||
await storage.put(sourceKey, await fs.readFile(localSource), { contentType: 'image/jpeg' });
|
||||
await fs.rm(localSource, { force: true });
|
||||
|
||||
db.__state.event = { id: 8, slug: 'managed-event', source_mode: 'managed' };
|
||||
const photo = {
|
||||
id: 201,
|
||||
event_id: 8,
|
||||
source_origin: 'managed',
|
||||
path: 'managed-event/individual/managed.jpg',
|
||||
filename: 'managed.jpg',
|
||||
preview_path: null,
|
||||
};
|
||||
|
||||
const key = await imageProcessor.ensurePreviewImage(photo);
|
||||
expect(key).toBe('previews/preview_managed.jpg');
|
||||
expect(await storage.exists(key)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
@@ -146,18 +146,11 @@ Generated on: ${new Date().toISOString()}
|
||||
console.log('Default email templates created');
|
||||
}
|
||||
|
||||
// Seed an email config ONLY when the environment actually supplies a host
|
||||
// (#705). This used to fall back to `mailhog`, the dev compose service, so
|
||||
// every fresh install came up with a LIVE config pointing at a host that
|
||||
// does not exist outside the dev stack — the setup wizard then showed empty
|
||||
// SMTP fields (reading as "nothing configured") while mail silently failed.
|
||||
// With no row at all, emailProcessor logs "No email configuration found"
|
||||
// and the wizard's blank fields are the truth. The dev stack keeps mailhog
|
||||
// by setting SMTP_HOST explicitly in docker-compose.yml.
|
||||
// Create default email config if none exists
|
||||
const emailConfig = await knex('email_configs').first();
|
||||
if (!emailConfig && process.env.SMTP_HOST) {
|
||||
if (!emailConfig) {
|
||||
await knex('email_configs').insert({
|
||||
smtp_host: process.env.SMTP_HOST,
|
||||
smtp_host: process.env.SMTP_HOST || 'mailhog',
|
||||
smtp_port: process.env.SMTP_PORT || 1025,
|
||||
smtp_secure: process.env.SMTP_SECURE === 'true',
|
||||
smtp_user: process.env.SMTP_USER || '',
|
||||
|
||||
@@ -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');
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user