Compare commits
113 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c5dc790e28 | |||
| 323dcae917 | |||
| 9ac23e5fe1 | |||
| 40eb03f0d8 | |||
| f89d374236 | |||
| c6ec93eef9 | |||
| 2f05fcc39d | |||
| 3d6c9848dc | |||
| f8a95d29d2 | |||
| ad326da35c | |||
| a6a3c9f9f8 | |||
| 997a85cdbc | |||
| cb5b319f10 | |||
| e8dad4b40d | |||
| 60cdd07085 | |||
| 613133c29c | |||
| 8337a716b1 | |||
| 0310c46fdd | |||
| 8060fedf6a | |||
| f891b16503 | |||
| 216c282542 | |||
| f7fd89387b | |||
| 2f4b8a64c0 | |||
| c8eb334637 | |||
| 14d5fa6ca5 | |||
| 84f370f4c2 | |||
| 8c260c4eeb | |||
| ec69ad84f2 | |||
| d7ba781c0f | |||
| ee9d2f70d3 | |||
| d0ccadbc99 | |||
| b743ea0398 | |||
| 808d305549 | |||
| e732e13f24 | |||
| c9b64d9c1a | |||
| be2ec0a4a1 | |||
| f4b685a5ab | |||
| 8e0005e170 | |||
| 43c6d22bdd | |||
| 2b5b23b96f | |||
| 0245e445ca | |||
| 433fb9a989 | |||
| e03d13efde | |||
| b97b130cad | |||
| 2a0361a83b | |||
| 29f1d23a0a | |||
| 51a505e379 | |||
| 1e38d84808 | |||
| 1b32d4691e | |||
| e7ca8bdb7f | |||
| 6cd546e86a | |||
| 7f22a9ee3d | |||
| f12606b4e0 | |||
| cbde7636aa | |||
| b5ac24ea46 | |||
| a77c2c2c57 | |||
| 7ebc232620 | |||
| 199dab82ae | |||
| 340d91bdd5 | |||
| 38fd41aad3 | |||
| 31bc01cb4b | |||
| 9cd6b08441 | |||
| 7dace044dc | |||
| 348894efef | |||
| efccecb3d8 | |||
| eadf282755 | |||
| eb03b61268 | |||
| 07f2c90055 | |||
| e91c7deaa4 | |||
| 7f7d38a57f | |||
| ac1838fbd7 | |||
| ed5fc5ad5c | |||
| f0cdcddb92 | |||
| 0751a08aa6 | |||
| d64eef8abf | |||
| 109aba8598 | |||
| b9283386a5 | |||
| 5da1c3a12f | |||
| 93301002ba | |||
| f8ba669716 | |||
| 00fff24a1c | |||
| 7eb6357b4a | |||
| aab9e1a937 | |||
| ffd4a7eee6 | |||
| 1476884dd0 | |||
| e3d597b89a | |||
| ea9caa9c5d | |||
| d51112e761 | |||
| a4b4485d32 | |||
| 8d0a946478 | |||
| 4698402b54 | |||
| ed0fa3241b | |||
| 54676424f2 | |||
| b41cb1586d | |||
| 1f3bc3c343 | |||
| 39db7bf6cb | |||
| aeade94a35 | |||
| b768a53c5b | |||
| 1f19fbb1b2 | |||
| 03ded870bf | |||
| df5aeaba41 | |||
| 279e0472c7 | |||
| 2ee4146d9a | |||
| 5dea0c9695 | |||
| d3d7df46f2 | |||
| 784d059c3d | |||
| dbe4b588eb | |||
| 274ef0cd73 | |||
| 65ac6eddac | |||
| be710eb1de | |||
| 58a86af868 | |||
| 1250306d11 | |||
| 80503c52b9 |
@@ -10,6 +10,14 @@ 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)
|
||||
@@ -106,6 +114,11 @@ VITE_API_URL=/api
|
||||
# DB_PORT=5432
|
||||
# REDIS_PORT=6379
|
||||
|
||||
# File watcher (watch-folder auto-import, local storage only)
|
||||
# Max photos processed in parallel — raise on hosts with memory headroom,
|
||||
# lower to 1 on very small hosts. Default: 2
|
||||
# FILE_WATCHER_CONCURRENCY=2
|
||||
|
||||
# Release Channel
|
||||
# Options: 'stable' (default), 'beta', or specific version like 'v2.3.0'
|
||||
# 'stable' uses the :stable tag (same as :latest on main)
|
||||
|
||||
@@ -95,6 +95,15 @@ jobs:
|
||||
repo_lc="${GITHUB_REPOSITORY,,}"
|
||||
echo "BACKEND_IMAGE_NAME=${repo_lc}/backend" >> "$GITHUB_ENV"
|
||||
echo "FRONTEND_IMAGE_NAME=${repo_lc}/frontend" >> "$GITHUB_ENV"
|
||||
# Mirror manifests to Docker Hub (picpeak/{backend,frontend}) only on the
|
||||
# canonical org repo, where the DOCKERHUB_* secrets live. Forks (and any
|
||||
# other owner) fall back to GHCR-only — the Docker Hub image line and login
|
||||
# are gated on this flag so their builds keep working unchanged.
|
||||
if [[ "$GITHUB_REPOSITORY" == "PicPeak/picpeak" ]]; then
|
||||
echo "DOCKERHUB_ENABLED=true" >> "$GITHUB_ENV"
|
||||
else
|
||||
echo "DOCKERHUB_ENABLED=false" >> "$GITHUB_ENV"
|
||||
fi
|
||||
|
||||
- name: Prepare platform pair
|
||||
run: |
|
||||
@@ -233,6 +242,15 @@ jobs:
|
||||
repo_lc="${GITHUB_REPOSITORY,,}"
|
||||
echo "BACKEND_IMAGE_NAME=${repo_lc}/backend" >> "$GITHUB_ENV"
|
||||
echo "FRONTEND_IMAGE_NAME=${repo_lc}/frontend" >> "$GITHUB_ENV"
|
||||
# Mirror manifests to Docker Hub (picpeak/{backend,frontend}) only on the
|
||||
# canonical org repo, where the DOCKERHUB_* secrets live. Forks (and any
|
||||
# other owner) fall back to GHCR-only — the Docker Hub image line and login
|
||||
# are gated on this flag so their builds keep working unchanged.
|
||||
if [[ "$GITHUB_REPOSITORY" == "PicPeak/picpeak" ]]; then
|
||||
echo "DOCKERHUB_ENABLED=true" >> "$GITHUB_ENV"
|
||||
else
|
||||
echo "DOCKERHUB_ENABLED=false" >> "$GITHUB_ENV"
|
||||
fi
|
||||
|
||||
- name: Download digest artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
@@ -266,11 +284,24 @@ jobs:
|
||||
echo "is_prerelease=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
if: env.DOCKERHUB_ENABLED == 'true'
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: docker.io
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata for Backend
|
||||
id: meta-backend
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.BACKEND_IMAGE_NAME }}
|
||||
# GHCR always; Docker Hub (picpeak/backend) added on the canonical repo so
|
||||
# the same tag scheme is mirrored to both registries. metadata-action drops
|
||||
# the blank second line on forks → GHCR-only there.
|
||||
images: |
|
||||
${{ env.REGISTRY }}/${{ env.BACKEND_IMAGE_NAME }}
|
||||
${{ env.DOCKERHUB_ENABLED == 'true' && 'docker.io/picpeak/backend' || '' }}
|
||||
labels: |
|
||||
org.opencontainers.image.title=PicPeak Backend
|
||||
org.opencontainers.image.description=PicPeak photo sharing platform backend service
|
||||
@@ -282,6 +313,10 @@ jobs:
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}},enable=${{ steps.context.outputs.is_prerelease == 'false' }}
|
||||
type=semver,pattern={{major}},enable=${{ steps.context.outputs.is_prerelease == 'false' }}
|
||||
# #668/#783: publish the git-tag name verbatim (v3.45.0 / v3.84.0-beta.0)
|
||||
# so users can pin the same string as the GitHub release. metadata-action's
|
||||
# `pattern=v{{version}}` silently dropped it on prereleases, so use type=ref.
|
||||
type=ref,event=tag
|
||||
type=sha,format=short
|
||||
# `:latest` + `:stable` follow the stable channel (the `stable` branch +
|
||||
# stable release tags). The default branch is now `main` (active dev),
|
||||
@@ -298,10 +333,15 @@ jobs:
|
||||
docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
|
||||
$(printf "${{ env.REGISTRY }}/${{ env.BACKEND_IMAGE_NAME }}@sha256:%s " *)
|
||||
|
||||
- name: Inspect manifest
|
||||
- name: Inspect manifest (GHCR)
|
||||
run: |
|
||||
docker buildx imagetools inspect ${{ env.REGISTRY }}/${{ env.BACKEND_IMAGE_NAME }}:${{ steps.meta-backend.outputs.version }}
|
||||
|
||||
- name: Inspect manifest (Docker Hub)
|
||||
if: env.DOCKERHUB_ENABLED == 'true'
|
||||
run: |
|
||||
docker buildx imagetools inspect docker.io/picpeak/backend:${{ steps.meta-backend.outputs.version }}
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Frontend: per-arch build, then merge into a multi-arch manifest
|
||||
# -----------------------------------------------------------------------------
|
||||
@@ -331,6 +371,15 @@ jobs:
|
||||
repo_lc="${GITHUB_REPOSITORY,,}"
|
||||
echo "BACKEND_IMAGE_NAME=${repo_lc}/backend" >> "$GITHUB_ENV"
|
||||
echo "FRONTEND_IMAGE_NAME=${repo_lc}/frontend" >> "$GITHUB_ENV"
|
||||
# Mirror manifests to Docker Hub (picpeak/{backend,frontend}) only on the
|
||||
# canonical org repo, where the DOCKERHUB_* secrets live. Forks (and any
|
||||
# other owner) fall back to GHCR-only — the Docker Hub image line and login
|
||||
# are gated on this flag so their builds keep working unchanged.
|
||||
if [[ "$GITHUB_REPOSITORY" == "PicPeak/picpeak" ]]; then
|
||||
echo "DOCKERHUB_ENABLED=true" >> "$GITHUB_ENV"
|
||||
else
|
||||
echo "DOCKERHUB_ENABLED=false" >> "$GITHUB_ENV"
|
||||
fi
|
||||
|
||||
- name: Prepare platform pair
|
||||
run: |
|
||||
@@ -450,6 +499,15 @@ jobs:
|
||||
repo_lc="${GITHUB_REPOSITORY,,}"
|
||||
echo "BACKEND_IMAGE_NAME=${repo_lc}/backend" >> "$GITHUB_ENV"
|
||||
echo "FRONTEND_IMAGE_NAME=${repo_lc}/frontend" >> "$GITHUB_ENV"
|
||||
# Mirror manifests to Docker Hub (picpeak/{backend,frontend}) only on the
|
||||
# canonical org repo, where the DOCKERHUB_* secrets live. Forks (and any
|
||||
# other owner) fall back to GHCR-only — the Docker Hub image line and login
|
||||
# are gated on this flag so their builds keep working unchanged.
|
||||
if [[ "$GITHUB_REPOSITORY" == "PicPeak/picpeak" ]]; then
|
||||
echo "DOCKERHUB_ENABLED=true" >> "$GITHUB_ENV"
|
||||
else
|
||||
echo "DOCKERHUB_ENABLED=false" >> "$GITHUB_ENV"
|
||||
fi
|
||||
|
||||
- name: Download digest artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
@@ -483,11 +541,24 @@ jobs:
|
||||
echo "is_prerelease=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
if: env.DOCKERHUB_ENABLED == 'true'
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: docker.io
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata for Frontend
|
||||
id: meta-frontend
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.FRONTEND_IMAGE_NAME }}
|
||||
# GHCR always; Docker Hub (picpeak/frontend) added on the canonical repo so
|
||||
# the same tag scheme is mirrored to both registries. metadata-action drops
|
||||
# the blank second line on forks → GHCR-only there.
|
||||
images: |
|
||||
${{ env.REGISTRY }}/${{ env.FRONTEND_IMAGE_NAME }}
|
||||
${{ env.DOCKERHUB_ENABLED == 'true' && 'docker.io/picpeak/frontend' || '' }}
|
||||
labels: |
|
||||
org.opencontainers.image.title=PicPeak Frontend
|
||||
org.opencontainers.image.description=PicPeak photo sharing platform frontend application
|
||||
@@ -499,6 +570,10 @@ jobs:
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}},enable=${{ steps.context.outputs.is_prerelease == 'false' }}
|
||||
type=semver,pattern={{major}},enable=${{ steps.context.outputs.is_prerelease == 'false' }}
|
||||
# #668/#783: publish the git-tag name verbatim (v3.45.0 / v3.84.0-beta.0)
|
||||
# so users can pin the same string as the GitHub release. metadata-action's
|
||||
# `pattern=v{{version}}` silently dropped it on prereleases, so use type=ref.
|
||||
type=ref,event=tag
|
||||
type=sha,format=short
|
||||
# `:latest` + `:stable` follow the stable channel (the `stable` branch +
|
||||
# stable release tags). The default branch is now `main` (active dev),
|
||||
@@ -515,10 +590,15 @@ jobs:
|
||||
docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
|
||||
$(printf "${{ env.REGISTRY }}/${{ env.FRONTEND_IMAGE_NAME }}@sha256:%s " *)
|
||||
|
||||
- name: Inspect manifest
|
||||
- name: Inspect manifest (GHCR)
|
||||
run: |
|
||||
docker buildx imagetools inspect ${{ env.REGISTRY }}/${{ env.FRONTEND_IMAGE_NAME }}:${{ steps.meta-frontend.outputs.version }}
|
||||
|
||||
- name: Inspect manifest (Docker Hub)
|
||||
if: env.DOCKERHUB_ENABLED == 'true'
|
||||
run: |
|
||||
docker buildx imagetools inspect docker.io/picpeak/frontend:${{ steps.meta-frontend.outputs.version }}
|
||||
|
||||
summary:
|
||||
needs: [build-backend, merge-backend, build-frontend, merge-frontend]
|
||||
if: always()
|
||||
@@ -532,6 +612,15 @@ jobs:
|
||||
repo_lc="${GITHUB_REPOSITORY,,}"
|
||||
echo "BACKEND_IMAGE_NAME=${repo_lc}/backend" >> "$GITHUB_ENV"
|
||||
echo "FRONTEND_IMAGE_NAME=${repo_lc}/frontend" >> "$GITHUB_ENV"
|
||||
# Mirror manifests to Docker Hub (picpeak/{backend,frontend}) only on the
|
||||
# canonical org repo, where the DOCKERHUB_* secrets live. Forks (and any
|
||||
# other owner) fall back to GHCR-only — the Docker Hub image line and login
|
||||
# are gated on this flag so their builds keep working unchanged.
|
||||
if [[ "$GITHUB_REPOSITORY" == "PicPeak/picpeak" ]]; then
|
||||
echo "DOCKERHUB_ENABLED=true" >> "$GITHUB_ENV"
|
||||
else
|
||||
echo "DOCKERHUB_ENABLED=false" >> "$GITHUB_ENV"
|
||||
fi
|
||||
|
||||
- name: Build Summary
|
||||
run: |
|
||||
@@ -570,6 +659,10 @@ jobs:
|
||||
echo "### 📦 Images" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Backend: \`${{ env.REGISTRY }}/${{ env.BACKEND_IMAGE_NAME }}\`" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Frontend: \`${{ env.REGISTRY }}/${{ env.FRONTEND_IMAGE_NAME }}\`" >> $GITHUB_STEP_SUMMARY
|
||||
if [[ "$DOCKERHUB_ENABLED" == "true" ]]; then
|
||||
echo "- Backend (Docker Hub): \`docker.io/picpeak/backend\`" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Frontend (Docker Hub): \`docker.io/picpeak/frontend\`" >> $GITHUB_STEP_SUMMARY
|
||||
fi
|
||||
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "### 🏗️ Architectures" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
+3
-2
@@ -130,5 +130,6 @@ docker-compose.dev.yml
|
||||
# New layout development files
|
||||
new-layouts/
|
||||
|
||||
# Generated CRM/accounting documents (runtime) — never commit
|
||||
backend/storage/business-docs/
|
||||
# Backend runtime storage (generated media, previews, thumbnails,
|
||||
# CRM/accounting documents) — never commit
|
||||
backend/storage/
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "3.83.0-beta.0"
|
||||
".": "3.94.2-beta.0"
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
{".":"3.45.3"}
|
||||
{".":"3.44.0"}
|
||||
|
||||
+1244
-816
File diff suppressed because it is too large
Load Diff
+18
-4
@@ -52,13 +52,19 @@ 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. **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).
|
||||
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.
|
||||
|
||||
6. **Merge.** Standard merge commit, not squash — the PR's history (the individual feature commits) carries forward into `stable`'s log.
|
||||
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).
|
||||
|
||||
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.
|
||||
7. **Merge.** Standard merge commit, not squash — the PR's history (the individual feature commits) carries forward into `stable`'s log.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
## Hotfix path (backport to current stable)
|
||||
|
||||
@@ -83,6 +89,14 @@ 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,9 +1,7 @@
|
||||
node_modules
|
||||
npm-debug.log
|
||||
.env
|
||||
storage/events/active/*
|
||||
storage/events/archived/*
|
||||
storage/thumbnails/*
|
||||
storage
|
||||
data/*.db
|
||||
logs/*
|
||||
coverage
|
||||
|
||||
@@ -106,6 +106,12 @@ 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
|
||||
|
||||
+4
-1
@@ -67,8 +67,11 @@ RUN npm install -g npm@11
|
||||
# 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 docs/accounting-inbound-invoices.md).
|
||||
# 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.
|
||||
RUN apk add --no-cache dumb-init postgresql-client ffmpeg su-exec \
|
||||
fontconfig ttf-dejavu ttf-liberation poppler-utils && \
|
||||
fontconfig ttf-dejavu ttf-liberation poppler-utils exiftool && \
|
||||
fc-cache -f
|
||||
|
||||
# Create non-root user
|
||||
|
||||
@@ -8,7 +8,10 @@ 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.
|
||||
RUN apk add --no-cache dumb-init ffmpeg
|
||||
# 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
|
||||
|
||||
# Copy package files
|
||||
COPY package*.json ./
|
||||
|
||||
@@ -40,7 +40,7 @@ jest.mock('../../src/middleware/permissions', () => ({
|
||||
requirePermission: () => (_req, _res, next) => next(),
|
||||
}));
|
||||
|
||||
jest.setTimeout(30000);
|
||||
jest.setTimeout(120000);
|
||||
|
||||
describe('GET /api/admin/system-health/backup-coverage', () => {
|
||||
let db;
|
||||
|
||||
@@ -29,7 +29,7 @@ jest.mock('../../src/middleware/permissions', () => ({
|
||||
requirePermission: () => (_req, _res, next) => next(),
|
||||
}));
|
||||
|
||||
jest.setTimeout(30000);
|
||||
jest.setTimeout(120000);
|
||||
|
||||
describe('GET /api/admin/system-health/backup-integrity', () => {
|
||||
let cleanup;
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* 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(),
|
||||
}));
|
||||
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -23,7 +23,7 @@ const path = require('path');
|
||||
|
||||
const { bootCrmDb } = require('./helpers/crmDb');
|
||||
|
||||
jest.setTimeout(30000);
|
||||
jest.setTimeout(120000);
|
||||
|
||||
describe('backupService — configurable walker (backup_paths)', () => {
|
||||
let db;
|
||||
|
||||
@@ -34,7 +34,7 @@ jest.mock('../../src/services/databaseBackup', () => ({
|
||||
DatabaseBackupService: class {},
|
||||
}));
|
||||
|
||||
jest.setTimeout(30000);
|
||||
jest.setTimeout(120000);
|
||||
|
||||
describe('backupService — inline DB dump + fail-loud guard', () => {
|
||||
let db;
|
||||
|
||||
@@ -23,7 +23,7 @@ const path = require('path');
|
||||
|
||||
const { bootCrmDb } = require('./helpers/crmDb');
|
||||
|
||||
jest.setTimeout(30000);
|
||||
jest.setTimeout(120000);
|
||||
|
||||
describe('backupService — per-Stage-B-path statistics', () => {
|
||||
let db;
|
||||
|
||||
@@ -14,7 +14,7 @@ const path = require('path');
|
||||
|
||||
const { bootCrmDb } = require('./helpers/crmDb');
|
||||
|
||||
jest.setTimeout(30000);
|
||||
jest.setTimeout(120000);
|
||||
|
||||
describe('backupService — config + file collection + manifest (smoke)', () => {
|
||||
let db;
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
const crypto = require('crypto');
|
||||
const { bootCrmDb, seedMinimal } = require('./helpers/crmDb');
|
||||
|
||||
jest.setTimeout(30000);
|
||||
jest.setTimeout(120000);
|
||||
|
||||
describe('booking cutover — draft invoices on hold', () => {
|
||||
let db; let cleanup; let adminId; let customerId; let quoteService;
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
/**
|
||||
* 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);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,413 @@
|
||||
/**
|
||||
* 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);
|
||||
});
|
||||
});
|
||||
@@ -14,7 +14,7 @@ const { bootCrmDb, seedMinimal } = require('./helpers/crmDb');
|
||||
// Service-level CRM calls cold-require heavy modules (pdfService,
|
||||
// nodemailer, etc.) on first use; the global 5 s per-test budget is
|
||||
// too tight for that. Bump it for this file only.
|
||||
jest.setTimeout(30000);
|
||||
jest.setTimeout(120000);
|
||||
|
||||
describe('discount line items (negative unit_price_minor)', () => {
|
||||
let db;
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* 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);
|
||||
});
|
||||
});
|
||||
@@ -6,7 +6,7 @@
|
||||
const { bootCrmDb, seedMinimal } = require('./helpers/crmDb');
|
||||
|
||||
// bootCrmDb runs the full core-migration set in beforeAll.
|
||||
jest.setTimeout(30000);
|
||||
jest.setTimeout(120000);
|
||||
|
||||
describe('event type slug rename cascade', () => {
|
||||
let db;
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* 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' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* 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);
|
||||
});
|
||||
});
|
||||
@@ -17,7 +17,7 @@ const request = require('supertest');
|
||||
|
||||
const { bootCrmDb } = require('./helpers/crmDb');
|
||||
|
||||
jest.setTimeout(60000);
|
||||
jest.setTimeout(120000);
|
||||
|
||||
let db; let cleanup; let service; let app;
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
*/
|
||||
const { bootCrmDb } = require('./helpers/crmDb');
|
||||
|
||||
jest.setTimeout(60000);
|
||||
jest.setTimeout(120000);
|
||||
|
||||
let db; let cleanup; let service; let adminId;
|
||||
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
/**
|
||||
* 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.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`,
|
||||
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 };
|
||||
@@ -13,7 +13,7 @@ const { bootCrmDb, seedMinimal } = require('./helpers/crmDb');
|
||||
|
||||
// Service-level CRM calls cold-require heavy modules (pdfService, nodemailer)
|
||||
// on first use; bump the budget for this file.
|
||||
jest.setTimeout(60000);
|
||||
jest.setTimeout(120000);
|
||||
|
||||
describe('incoming-invoice categorise / re-bill chain', () => {
|
||||
let db;
|
||||
|
||||
@@ -32,7 +32,7 @@ jest.mock('../../src/services/restoreService', () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
jest.setTimeout(30000);
|
||||
jest.setTimeout(120000);
|
||||
|
||||
describe('installFromBackupBoot', () => {
|
||||
let db;
|
||||
|
||||
@@ -13,7 +13,7 @@ const { bootCrmDb, seedMinimal } = require('./helpers/crmDb');
|
||||
// bootCrmDb runs the full core-migration set in beforeAll; under full-suite
|
||||
// parallel load on a small CI runner that can exceed the 5s default. Match the
|
||||
// other migration-heavy CRM suites (discountLineItems, incomingInvoiceRebill).
|
||||
jest.setTimeout(30000);
|
||||
jest.setTimeout(120000);
|
||||
|
||||
let db;
|
||||
let cleanup;
|
||||
|
||||
@@ -0,0 +1,416 @@
|
||||
/**
|
||||
* 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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,302 @@
|
||||
/**
|
||||
* 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,
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,190 @@
|
||||
/**
|
||||
* 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 });
|
||||
});
|
||||
});
|
||||
@@ -13,7 +13,7 @@ const { execFileSync } = require('child_process');
|
||||
|
||||
const { bootCrmDb } = require('./helpers/crmDb');
|
||||
|
||||
jest.setTimeout(60000);
|
||||
jest.setTimeout(120000);
|
||||
|
||||
let db;
|
||||
let cleanup;
|
||||
|
||||
@@ -0,0 +1,402 @@
|
||||
/**
|
||||
* 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', async () => {
|
||||
const res = await request(app)
|
||||
.get(`/api/gallery/${SLUG}/photos?preview=${encodeURIComponent(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 });
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -10,7 +10,7 @@ const { bootCrmDb } = require('./helpers/crmDb');
|
||||
// bootCrmDb runs the full core-migration set in beforeAll; under full-suite
|
||||
// parallel load on a small CI runner that can exceed the 5s default. Match the
|
||||
// other migration-heavy CRM suites (discountLineItems, incomingInvoiceRebill).
|
||||
jest.setTimeout(30000);
|
||||
jest.setTimeout(120000);
|
||||
|
||||
let db;
|
||||
let cleanup;
|
||||
|
||||
@@ -9,7 +9,7 @@ const {
|
||||
// bootCrmDb runs the full core-migration set in beforeAll; under full-suite
|
||||
// parallel load on a small CI runner that can exceed the 5s default. Match the
|
||||
// other migration-heavy CRM suites (discountLineItems, incomingInvoiceRebill).
|
||||
jest.setTimeout(30000);
|
||||
jest.setTimeout(120000);
|
||||
|
||||
let db;
|
||||
let cleanup;
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* 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');
|
||||
}, 30000);
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -180,6 +180,27 @@ describe('admin events CRUD endpoints (smoke)', () => {
|
||||
});
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
// #822 — hero_logo_visible/position are nullable (null = "inherit the global
|
||||
// branding toggle"), but the validator used .optional() without
|
||||
// { nullable: true }, so an explicit null was rejected with 400.
|
||||
it('accepts hero_logo_visible: null and stores NULL (inherit)', async () => {
|
||||
const id = await insertEvent(db, adminId, { hero_logo_visible: 1 });
|
||||
const res = await auth(request(app).put(`/api/admin/events/${id}`)).send({
|
||||
hero_logo_visible: null,
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
const row = await db('events').where({ id }).first();
|
||||
expect(row.hero_logo_visible).toBeNull();
|
||||
});
|
||||
|
||||
it('still rejects a non-boolean hero_logo_visible', async () => {
|
||||
const id = await insertEvent(db, adminId);
|
||||
const res = await auth(request(app).put(`/api/admin/events/${id}`)).send({
|
||||
hero_logo_visible: 'maybe',
|
||||
});
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /:id', () => {
|
||||
|
||||
@@ -39,7 +39,7 @@ const {
|
||||
bootCrmDb, mintAdminToken, buildRouteApp,
|
||||
} = require('../integration/helpers/crmDb');
|
||||
|
||||
jest.setTimeout(60000);
|
||||
jest.setTimeout(120000);
|
||||
|
||||
let db;
|
||||
let cleanup;
|
||||
|
||||
@@ -32,9 +32,17 @@ 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(([k, v]) => {
|
||||
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\./, '');
|
||||
if (k === 'is_active') return Boolean(row.is_active) === Boolean(v);
|
||||
return row[k] === v;
|
||||
});
|
||||
@@ -50,7 +58,12 @@ jest.mock('../../src/database/db', () => {
|
||||
if (!row) return undefined;
|
||||
if (!this._cols) return row;
|
||||
const out = {};
|
||||
for (const c of this._cols) out[c] = row[c];
|
||||
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];
|
||||
}
|
||||
return out;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -99,7 +99,12 @@ describe('public Live Slideshow routes', () => {
|
||||
await setFlag(db, 'slideshow', true);
|
||||
});
|
||||
|
||||
const stateUrl = (token = TOKEN) => `/api/gallery/${SLUG}/show/${token}/state`;
|
||||
// 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`;
|
||||
|
||||
describe('resolveSlideshow guards', () => {
|
||||
it('200 + per-event display settings on a live link', async () => {
|
||||
@@ -228,6 +233,58 @@ 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).
|
||||
|
||||
@@ -22,7 +22,7 @@ const crypto = require('crypto');
|
||||
|
||||
const { bootCrmDb, seedMinimal } = require('../integration/helpers/crmDb');
|
||||
|
||||
jest.setTimeout(30000);
|
||||
jest.setTimeout(120000);
|
||||
|
||||
describe('backupIntegrityService.verifyDocumentArtefacts', () => {
|
||||
let db;
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* 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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* 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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* 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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* 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,3 +234,66 @@ 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,15 +71,24 @@ 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/'),
|
||||
}));
|
||||
|
||||
@@ -205,6 +214,44 @@ 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 });
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* 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();
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* 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
|
||||
});
|
||||
@@ -0,0 +1,202 @@
|
||||
/**
|
||||
* 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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Regression tests for the password-complexity setting read path.
|
||||
*
|
||||
* Bug 1 (key mismatch): the settings UI saves the admin's choice as
|
||||
* `security_password_complexity` (useSettingsState.ts prefixes every
|
||||
* security field with `security_`), but getPasswordComplexitySettings()
|
||||
* queried `security_password_complexity_level` — a key nothing writes —
|
||||
* so the configured level was silently ignored.
|
||||
*
|
||||
* Bug 2 (driver shape, codex review of #843): on SQLite the TEXT column
|
||||
* returns the JSON-stringified value ('"very_strong"'), but on Postgres
|
||||
* (production default) `setting_value` is a json column and comes back
|
||||
* already decoded ('very_strong'). A bare JSON.parse throws on the
|
||||
* decoded shape and the outer catch fell back to 'moderate' — the
|
||||
* setting stayed unenforced on Postgres even with the right key.
|
||||
*/
|
||||
|
||||
const mockQueriedKeys = [];
|
||||
let mockStoredValue;
|
||||
|
||||
jest.mock('../../src/database/db', () => ({
|
||||
db: () => ({
|
||||
where(_col, key) {
|
||||
mockQueriedKeys.push(key);
|
||||
return this;
|
||||
},
|
||||
first() {
|
||||
return Promise.resolve(
|
||||
mockQueriedKeys[mockQueriedKeys.length - 1] === 'security_password_complexity'
|
||||
? { setting_key: 'security_password_complexity', setting_value: mockStoredValue }
|
||||
: undefined
|
||||
);
|
||||
},
|
||||
}),
|
||||
withRetry: (fn) => fn(),
|
||||
}));
|
||||
|
||||
const { getPasswordComplexitySettings } = require('../../src/utils/passwordValidation');
|
||||
|
||||
describe('getPasswordComplexitySettings', () => {
|
||||
beforeEach(() => { mockQueriedKeys.length = 0; });
|
||||
|
||||
it('reads the key the settings UI actually writes (SQLite shape: JSON-stringified)', async () => {
|
||||
mockStoredValue = JSON.stringify('very_strong'); // '"very_strong"'
|
||||
const level = await getPasswordComplexitySettings();
|
||||
expect(mockQueriedKeys).toContain('security_password_complexity');
|
||||
expect(level).toBe('very_strong');
|
||||
});
|
||||
|
||||
it('accepts the Postgres json-column shape (already decoded, no quotes)', async () => {
|
||||
mockStoredValue = 'very_strong'; // pg driver auto-parses the json column
|
||||
const level = await getPasswordComplexitySettings();
|
||||
expect(level).toBe('very_strong');
|
||||
});
|
||||
|
||||
it('falls back to moderate on an empty value', async () => {
|
||||
mockStoredValue = '';
|
||||
const level = await getPasswordComplexitySettings();
|
||||
expect(level).toBe('moderate');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* 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);
|
||||
});
|
||||
Binary file not shown.
Binary file not shown.
+93
@@ -0,0 +1,93 @@
|
||||
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,5 +1,10 @@
|
||||
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.
|
||||
testTimeout: 120000,
|
||||
coverageDirectory: 'coverage',
|
||||
collectCoverageFrom: [
|
||||
'src/**/*.js',
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* 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));
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* 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')
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* 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');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* 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();
|
||||
};
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* 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));
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* #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');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* 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');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* 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);
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
Generated
+64
-4
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "picpeak-backend",
|
||||
"version": "3.80.0-beta.0",
|
||||
"version": "3.92.1-beta.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "picpeak-backend",
|
||||
"version": "3.80.0-beta.0",
|
||||
"version": "3.92.1-beta.0",
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-s3": "^3.850.0",
|
||||
"@aws-sdk/lib-storage": "^3.850.0",
|
||||
@@ -40,7 +40,9 @@
|
||||
"node-cron": "^3.0.2",
|
||||
"node-stream-zip": "^1.15.0",
|
||||
"nodemailer": "^9.0.1",
|
||||
"openid-client": "^5.7.1",
|
||||
"otplib": "^12.0.1",
|
||||
"p-limit": "^3.1.0",
|
||||
"pdf-lib": "^1.17.1",
|
||||
"pdfkit": "^0.17.2",
|
||||
"pg": "^8.16.3",
|
||||
@@ -7905,6 +7907,15 @@
|
||||
"@sideway/pinpoint": "^2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/jose": {
|
||||
"version": "4.15.9",
|
||||
"resolved": "https://registry.npmjs.org/jose/-/jose-4.15.9.tgz",
|
||||
"integrity": "sha512-1vUQX+IdDMVPj4k8kOxgUqlcK518yluMuGZwqlr44FS1ppZB/5GWh4rZG89erpOBOJjU/OBsnCVFfapsRz6nEA==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/panva"
|
||||
}
|
||||
},
|
||||
"node_modules/jpeg-exif": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/jpeg-exif/-/jpeg-exif-1.1.4.tgz",
|
||||
@@ -9330,6 +9341,15 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/object-hash": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/object-hash/-/object-hash-2.2.0.tgz",
|
||||
"integrity": "sha512-gScRMn0bS5fH+IuwyIFgnh9zBdo4DV+6GhygmWM9HyNJSgS0hScp1f5vjtm7oIIOiT9trXrShAkLFSc2IqKNgw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/object-inspect": {
|
||||
"version": "1.13.4",
|
||||
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
|
||||
@@ -9342,6 +9362,15 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/oidc-token-hash": {
|
||||
"version": "5.2.0",
|
||||
"resolved": "https://registry.npmjs.org/oidc-token-hash/-/oidc-token-hash-5.2.0.tgz",
|
||||
"integrity": "sha512-6gj2m8cJZ+iSW8bm0FXdGF0YhIQbKrfP4yWTNzxc31U6MOjfEmB1rHvlYvxI1B7t7BCi1F2vYTT6YhtQRG4hxw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^10.13.0 || >=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/on-exit-leak-free": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz",
|
||||
@@ -9404,6 +9433,39 @@
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/openid-client": {
|
||||
"version": "5.7.1",
|
||||
"resolved": "https://registry.npmjs.org/openid-client/-/openid-client-5.7.1.tgz",
|
||||
"integrity": "sha512-jDBPgSVfTnkIh71Hg9pRvtJc6wTwqjRkN88+gCFtYWrlP4Yx2Dsrow8uPi3qLr/aeymPF3o2+dS+wOpglK04ew==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"jose": "^4.15.9",
|
||||
"lru-cache": "^6.0.0",
|
||||
"object-hash": "^2.2.0",
|
||||
"oidc-token-hash": "^5.0.3"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/panva"
|
||||
}
|
||||
},
|
||||
"node_modules/openid-client/node_modules/lru-cache": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
|
||||
"integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"yallist": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/openid-client/node_modules/yallist": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
|
||||
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/optionator": {
|
||||
"version": "0.9.4",
|
||||
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
|
||||
@@ -9437,7 +9499,6 @@
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",
|
||||
"integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"yocto-queue": "^0.1.0"
|
||||
@@ -12450,7 +12511,6 @@
|
||||
"version": "0.1.0",
|
||||
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
|
||||
"integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "picpeak-backend",
|
||||
"version": "3.45.3",
|
||||
"version": "3.94.2-beta.0",
|
||||
"description": "Backend for PicPeak event photo sharing platform",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
@@ -11,6 +11,7 @@
|
||||
"generate:watermarks": "node scripts/generate-watermarks.js",
|
||||
"test": "jest",
|
||||
"test:s3": "SKIP_S3_TESTS=false jest __tests__/integration/backup-s3",
|
||||
"test:pg": "jest __tests__/integration/picpeakRestorePg",
|
||||
"lint": "eslint src/"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -46,7 +47,9 @@
|
||||
"node-cron": "^3.0.2",
|
||||
"node-stream-zip": "^1.15.0",
|
||||
"nodemailer": "^9.0.1",
|
||||
"openid-client": "^5.7.1",
|
||||
"otplib": "^12.0.1",
|
||||
"p-limit": "^3.1.0",
|
||||
"pdf-lib": "^1.17.1",
|
||||
"pdfkit": "^0.17.2",
|
||||
"pg": "^8.16.3",
|
||||
|
||||
@@ -20,6 +20,7 @@ const path = require('path');
|
||||
const { initializeDatabase, db } = require('./src/database/db');
|
||||
const { startFileWatcher } = require('./src/services/fileWatcher');
|
||||
const { startExpirationChecker } = require('./src/services/expirationChecker');
|
||||
const { startRevealScheduler } = require('./src/services/revealScheduler');
|
||||
const { startInvoiceScheduler } = require('./src/services/invoiceSchedulerService');
|
||||
const { initializeTransporter, startEmailQueueProcessor } = require('./src/services/emailProcessor');
|
||||
const { startBackupService } = require('./src/services/backupService');
|
||||
@@ -903,6 +904,8 @@ async function startServer() {
|
||||
|
||||
// Start expiration checker
|
||||
startExpirationChecker();
|
||||
// Reveal-mode scheduler (#838): minutely stamp for scheduled reveals.
|
||||
startRevealScheduler();
|
||||
// CRM invoice scheduler: hourly tick to flush scheduled-send invoices
|
||||
// + run the overdue reminder ladder. No-op when the `bills` feature
|
||||
// flag is OFF (the service short-circuits on empty result sets).
|
||||
|
||||
@@ -33,6 +33,13 @@ jest.mock('../utils/tokenRevocation', () => ({
|
||||
isTokenRevoked: jest.fn(),
|
||||
}));
|
||||
|
||||
// The global session cutoff (added for .picpeak restore invalidation) queries
|
||||
// app_settings; stub it to "no cutoff" so it doesn't consume this suite's
|
||||
// one-shot db() mock. Its own behaviour is covered by utils/sessionCutoff.test.js.
|
||||
jest.mock('../utils/sessionCutoff', () => ({
|
||||
isTokenBeforeCutoff: jest.fn().mockResolvedValue(false),
|
||||
}));
|
||||
|
||||
jest.mock('../utils/tokenUtils', () => ({
|
||||
getCustomerTokenFromRequest: jest.fn(),
|
||||
}));
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Emoji reactions (#839): the fixed, curated reaction set. Guests pick ONE
|
||||
* of these per photo (changeable). Kept as a shared constant so the
|
||||
* validator, the service and the export layer can never drift apart.
|
||||
*
|
||||
* Mirrored in frontend/src/services/feedback.service.ts (REACTION_EMOJIS) —
|
||||
* update both together.
|
||||
*/
|
||||
const REACTION_EMOJIS = ['❤️', '😂', '😍', '👏', '🎉'];
|
||||
|
||||
module.exports = { REACTION_EMOJIS };
|
||||
@@ -72,7 +72,7 @@ async function apiTokenAuth(req, res, next) {
|
||||
}
|
||||
|
||||
// Touch last_used_at — async, don't block the request.
|
||||
db('api_tokens').where({ id: row.id }).update({ last_used_at: new Date() })
|
||||
db('api_tokens').where({ id: row.id }).update({ last_used_at: new Date().toISOString() })
|
||||
.catch((err) => logger.debug('api_tokens last_used update failed', { err: err.message }));
|
||||
|
||||
req.admin = admin;
|
||||
|
||||
@@ -2,6 +2,7 @@ const jwt = require('jsonwebtoken');
|
||||
const { db } = require('../database/db');
|
||||
const { formatBoolean } = require('../utils/dbCompat');
|
||||
const { isTokenRevoked } = require('../utils/tokenRevocation');
|
||||
const { isTokenBeforeCutoff } = require('../utils/sessionCutoff');
|
||||
const logger = require('../utils/logger');
|
||||
const { getAdminTokenFromRequest, getGalleryTokenFromRequest } = require('../utils/tokenUtils');
|
||||
|
||||
@@ -38,6 +39,13 @@ async function adminAuth(req, res, next) {
|
||||
});
|
||||
return res.status(401).json({ error: 'Token has been revoked', code: 'TOKEN_REVOKED' });
|
||||
}
|
||||
|
||||
// Reject any session issued before the global cutoff (set by a .picpeak
|
||||
// restore, which can reassign admin ids). Forces every pre-restore admin
|
||||
// session to re-authenticate against the restored data.
|
||||
if (await isTokenBeforeCutoff(decoded)) {
|
||||
return res.status(401).json({ error: 'Session invalidated', code: 'SESSION_INVALIDATED' });
|
||||
}
|
||||
|
||||
// Verify token type
|
||||
if (decoded.type !== 'admin') {
|
||||
@@ -157,7 +165,12 @@ async function galleryAuth(req, res, next) {
|
||||
if (await isTokenRevoked(decoded)) {
|
||||
return res.status(401).json({ error: 'Session has been invalidated', code: 'TOKEN_REVOKED' });
|
||||
}
|
||||
|
||||
|
||||
// Reject sessions issued before the global restore cutoff.
|
||||
if (await isTokenBeforeCutoff(decoded)) {
|
||||
return res.status(401).json({ error: 'Session invalidated', code: 'SESSION_INVALIDATED' });
|
||||
}
|
||||
|
||||
// Verify token type
|
||||
if (decoded.type !== 'gallery') {
|
||||
return res.status(403).json({ error: 'Invalid access token' });
|
||||
@@ -221,6 +234,11 @@ async function photoAuth(req, res, next) {
|
||||
return res.status(401).json({ error: 'Token has been revoked', code: 'TOKEN_REVOKED' });
|
||||
}
|
||||
|
||||
// Reject sessions issued before the global restore cutoff.
|
||||
if (await isTokenBeforeCutoff(decoded)) {
|
||||
return res.status(401).json({ error: 'Session invalidated', code: 'SESSION_INVALIDATED' });
|
||||
}
|
||||
|
||||
// Allow both admin and gallery tokens
|
||||
if (decoded.type === 'admin') {
|
||||
const admin = await db('admin_users')
|
||||
|
||||
@@ -13,6 +13,7 @@ const jwt = require('jsonwebtoken');
|
||||
const { db } = require('../database/db');
|
||||
const { formatBoolean } = require('../utils/dbCompat');
|
||||
const { isTokenRevoked } = require('../utils/tokenRevocation');
|
||||
const { isTokenBeforeCutoff } = require('../utils/sessionCutoff');
|
||||
const logger = require('../utils/logger');
|
||||
const { getCustomerTokenFromRequest } = require('../utils/tokenUtils');
|
||||
|
||||
@@ -61,6 +62,11 @@ async function customerAuth(req, res, next) {
|
||||
return res.status(401).json({ error: 'Token has been revoked', code: 'TOKEN_REVOKED' });
|
||||
}
|
||||
|
||||
// Reject sessions issued before the global restore cutoff.
|
||||
if (await isTokenBeforeCutoff(decoded)) {
|
||||
return res.status(401).json({ error: 'Session invalidated', code: 'SESSION_INVALIDATED' });
|
||||
}
|
||||
|
||||
if (decoded.type !== 'customer') {
|
||||
logger.warn('[customerAuth] wrong token type', {
|
||||
url: req.originalUrl,
|
||||
|
||||
@@ -34,20 +34,26 @@ async function getRateLimitSettings() {
|
||||
.where('setting_key', 'feedback_rate_limits')
|
||||
.first();
|
||||
|
||||
if (settings && settings.setting_value) {
|
||||
// setting_value is already a JSON object in PostgreSQL
|
||||
return typeof settings.setting_value === 'string'
|
||||
? JSON.parse(settings.setting_value)
|
||||
: settings.setting_value;
|
||||
}
|
||||
|
||||
// Default settings
|
||||
return {
|
||||
// Defaults FIRST, stored values override: persisted rows predate newer
|
||||
// action types (`reaction`, #839) — returning the stored object alone
|
||||
// would silently drop their intended defaults to the generic 100/h.
|
||||
const defaults = {
|
||||
rating: { max: 100, window: 3600 }, // 100 ratings per hour
|
||||
comment: { max: 20, window: 3600 }, // 20 comments per hour
|
||||
like: { max: 200, window: 3600 }, // 200 likes per hour
|
||||
favorite: { max: 100, window: 3600 } // 100 favorites per hour
|
||||
favorite: { max: 100, window: 3600 }, // 100 favorites per hour
|
||||
reaction: { max: 200, window: 3600 } // reactions churn like likes (#839)
|
||||
};
|
||||
|
||||
if (settings && settings.setting_value) {
|
||||
// setting_value is already a JSON object in PostgreSQL
|
||||
const stored = typeof settings.setting_value === 'string'
|
||||
? JSON.parse(settings.setting_value)
|
||||
: settings.setting_value;
|
||||
return { ...defaults, ...stored };
|
||||
}
|
||||
|
||||
return defaults;
|
||||
} catch (error) {
|
||||
logger.error('Error getting rate limit settings:', error);
|
||||
// Return defaults on error
|
||||
@@ -55,7 +61,8 @@ async function getRateLimitSettings() {
|
||||
rating: { max: 100, window: 3600 },
|
||||
comment: { max: 20, window: 3600 },
|
||||
like: { max: 200, window: 3600 },
|
||||
favorite: { max: 100, window: 3600 }
|
||||
favorite: { max: 100, window: 3600 },
|
||||
reaction: { max: 200, window: 3600 }
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,6 +164,11 @@ async function verifyGalleryAccess(req, res, next) {
|
||||
logger.debug('[verifyGalleryAccess] Event located', { eventId: event.id, slug: event.slug });
|
||||
req.event = event;
|
||||
req.accessLevel = decoded.accessLevel || 'guest';
|
||||
// Customer-portal provenance (#746/#849): portal-minted tokens carry
|
||||
// via:'customer' but NO accessLevel (they default to guest), while
|
||||
// PIN-client logins carry accessLevel:'client' without `via`. Activity
|
||||
// attribution/dedup needs the distinction, so surface it explicitly.
|
||||
req.viaCustomer = decoded.via === 'customer';
|
||||
req.sessionID = decoded.sessionId || `gallery_${event.id}_${Date.now()}`;
|
||||
|
||||
// Create client info for logging (similar to secureImageMiddleware but simpler)
|
||||
|
||||
@@ -73,6 +73,15 @@ async function maintenanceMiddleware(req, res, next) {
|
||||
// entries here matched nothing, which is exactly why the lockout happened).
|
||||
const skipPaths = [
|
||||
'/api/auth/admin/login',
|
||||
// The second factor is part of the same login — without this, any
|
||||
// MFA-enrolled admin gets a 503 on the verify step and cannot sign in
|
||||
// at all while maintenance mode is on.
|
||||
'/api/auth/admin/login/mfa',
|
||||
// SSO variants of the admin login (#798) — same reasoning: an SSO-only
|
||||
// (JIT-provisioned) admin has no password, so blocking these would make
|
||||
// maintenance mode admin-proof for them.
|
||||
'/api/auth/admin/sso/login',
|
||||
'/api/auth/admin/sso/callback',
|
||||
'/api/auth/session',
|
||||
'/api/public/settings',
|
||||
'/health'
|
||||
|
||||
@@ -11,6 +11,7 @@ const { db, logActivity } = require('../database/db');
|
||||
const { adminAuth } = require('./../middleware/auth');
|
||||
const { requirePermission } = require('./../middleware/permissions');
|
||||
const { generateApiToken, VALID_SCOPES } = require('./../middleware/apiTokenAuth');
|
||||
const { toIso } = require('../utils/dateNormalize');
|
||||
const logger = require('../utils/logger');
|
||||
|
||||
const router = express.Router();
|
||||
@@ -33,7 +34,15 @@ router.get('/', adminAuth, requirePermission('settings.view'), async (req, res)
|
||||
'admin_users.username as owner_username'
|
||||
)
|
||||
.orderBy('api_tokens.created_at', 'desc');
|
||||
res.json(tokens);
|
||||
// toIso: last_used_at / revoked_at were written as raw Dates before
|
||||
// this fix — SQLite installs hold epoch numbers in existing rows.
|
||||
res.json(tokens.map((t) => ({
|
||||
...t,
|
||||
created_at: toIso(t.created_at),
|
||||
expires_at: toIso(t.expires_at),
|
||||
last_used_at: toIso(t.last_used_at),
|
||||
revoked_at: toIso(t.revoked_at),
|
||||
})));
|
||||
} catch (error) {
|
||||
logger.error('Failed to list API tokens', { error: error.message });
|
||||
res.status(500).json({ error: 'Failed to list tokens' });
|
||||
@@ -103,7 +112,7 @@ router.delete('/:id', adminAuth, requirePermission('settings.edit'), async (req,
|
||||
if (!row) return res.status(404).json({ error: 'Token not found' });
|
||||
if (row.revoked_at) return res.status(400).json({ error: 'Token already revoked' });
|
||||
|
||||
await db('api_tokens').where({ id }).update({ revoked_at: new Date() });
|
||||
await db('api_tokens').where({ id }).update({ revoked_at: new Date().toISOString() });
|
||||
await logActivity('api_token_revoked', { name: row.name }, null, {
|
||||
type: 'admin', id: req.admin.id, name: req.admin.username
|
||||
});
|
||||
|
||||
@@ -293,7 +293,7 @@ router.post('/:id/restore', adminAuth, requirePermission('archives.restore'), re
|
||||
type: path.extname(filename).substring(1).toLowerCase(),
|
||||
size_bytes: stats.size,
|
||||
category_id: categoryId,
|
||||
uploaded_at: new Date()
|
||||
uploaded_at: new Date().toISOString()
|
||||
});
|
||||
}
|
||||
} catch (statError) {
|
||||
|
||||
@@ -31,7 +31,13 @@ router.get('/config', adminAuth, requirePermission('backup.view'), async (req, r
|
||||
config[setting.setting_key] = setting.setting_value;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// Never return the stored credentials — mask like the email/WhatsApp
|
||||
// config endpoints do. The PUT below skips the mask sentinel, so the
|
||||
// form round-trips without clobbering the real values.
|
||||
if (config.backup_s3_secret_key) config.backup_s3_secret_key = '••••••••';
|
||||
if (config.backup_rsync_ssh_key) config.backup_rsync_ssh_key = '••••••••';
|
||||
|
||||
res.json(config);
|
||||
} catch (error) {
|
||||
errorResponse(res, error, 500, 'Failed to get backup configuration');
|
||||
@@ -67,6 +73,11 @@ router.put('/config', adminAuth, requirePermission('backup.create'), async (req,
|
||||
|
||||
// Update settings
|
||||
for (const [key, value] of Object.entries(updates)) {
|
||||
// An unchanged secret round-trips as the GET mask sentinel — keep the
|
||||
// stored value instead of overwriting it with bullets.
|
||||
if (value === '••••••••') {
|
||||
continue;
|
||||
}
|
||||
if (key.startsWith('backup_')) {
|
||||
await db('app_settings')
|
||||
.insert({
|
||||
@@ -186,18 +197,15 @@ router.post('/picpeak/import', adminAuth, requirePermission('backup.restore'), p
|
||||
// letting a crafted .picpeak take over every admin account (GHSA-qxfx-4493-4v8f).
|
||||
const result = await importFromPicpeak({ picpeakPath, currentAdminId: req.admin && req.admin.id });
|
||||
|
||||
// The restore rewrote admin_users, so ids may have shifted. The operator's
|
||||
// current JWT is bound only to the pre-restore admin id (adminAuth trusts
|
||||
// `decoded.id` — IP is logged, not enforced, and the backup controls
|
||||
// password_changed_at), which could now resolve to a DIFFERENT restored
|
||||
// account and silently grant its permissions. Force a fresh login instead
|
||||
// of trusting the old session: revoke the token and clear the cookie.
|
||||
// Clearing the cookie is the guarantee — it drops the operator's browser
|
||||
// session unconditionally. Revocation is the extra layer that also kills a
|
||||
// Bearer-header copy of the JWT; revokeToken() swallows DB errors and
|
||||
// returns false, so check the result and log loudly if the denylist write
|
||||
// didn't land (the operator should still re-login, which the cookie clear
|
||||
// forces).
|
||||
// The restore rewrote admin_users, so ids may have shifted. importFromPicpeak
|
||||
// already stamped a GLOBAL session cutoff (see setSessionsValidAfter), so
|
||||
// every JWT issued before the restore — admin, customer, gallery — now fails
|
||||
// auth. Here we additionally give the importing admin an immediate, clean
|
||||
// logout: revoke this token and clear the cookie so their browser drops the
|
||||
// session at once rather than on the next 401. Cookie clear is the
|
||||
// unconditional guarantee; revokeToken() swallows DB errors and returns
|
||||
// false, so check the result and log loudly if the denylist write didn't
|
||||
// land (the operator still re-logs-in, which the cookie clear forces).
|
||||
let tokenRevoked = false;
|
||||
try {
|
||||
if (req.token) {
|
||||
|
||||
@@ -4,6 +4,8 @@ const { db, logActivity } = require('../database/db');
|
||||
const { formatBoolean } = require('../utils/dbCompat');
|
||||
const { adminAuth } = require('../middleware/auth');
|
||||
const { requirePermission } = require('../middleware/permissions');
|
||||
const { requireEventOwnership } = require('../middleware/ownership');
|
||||
const { getEventCategoriesOrdered } = require('../utils/categoryOrder');
|
||||
const logger = require('../utils/logger');
|
||||
const router = express.Router();
|
||||
|
||||
@@ -12,8 +14,9 @@ router.get('/global', adminAuth, requirePermission('settings.view'), async (req,
|
||||
try {
|
||||
const categories = await db('photo_categories')
|
||||
.where('is_global', formatBoolean(true))
|
||||
.orderBy('display_order', 'asc')
|
||||
.orderBy('name', 'asc');
|
||||
|
||||
|
||||
res.json(categories);
|
||||
} catch (error) {
|
||||
logger.error('Error fetching categories:', error);
|
||||
@@ -21,19 +24,12 @@ router.get('/global', adminAuth, requirePermission('settings.view'), async (req,
|
||||
}
|
||||
});
|
||||
|
||||
// Get categories for a specific event (global + event-specific)
|
||||
router.get('/event/:eventId', adminAuth, requirePermission('settings.view'), async (req, res) => {
|
||||
// Get categories for a specific event (global + event-specific), resolved to
|
||||
// the event's effective order: per-event override, else global default, else
|
||||
// name (#782). Each row carries `override_position` (null when not customised).
|
||||
router.get('/event/:eventId', adminAuth, requirePermission('settings.view'), requireEventOwnership, async (req, res) => {
|
||||
try {
|
||||
const { eventId } = req.params;
|
||||
|
||||
const categories = await db('photo_categories')
|
||||
.where(function() {
|
||||
this.where('is_global', formatBoolean(true))
|
||||
.orWhere('event_id', eventId);
|
||||
})
|
||||
.orderBy('is_global', 'desc')
|
||||
.orderBy('name', 'asc');
|
||||
|
||||
const categories = await getEventCategoriesOrdered(req.params.eventId);
|
||||
res.json(categories);
|
||||
} catch (error) {
|
||||
logger.error('Error fetching event categories:', error);
|
||||
@@ -81,12 +77,27 @@ router.post('/', adminAuth, requirePermission('settings.edit'), [
|
||||
return res.status(400).json({ error: 'Category with this slug already exists' });
|
||||
}
|
||||
|
||||
// Append to the end of its scope so a new category doesn't jump to the
|
||||
// top of an admin-defined order (#782).
|
||||
const maxRow = await db('photo_categories')
|
||||
.where(function() {
|
||||
if (is_global) {
|
||||
this.where('is_global', formatBoolean(true));
|
||||
} else {
|
||||
this.where('event_id', event_id);
|
||||
}
|
||||
})
|
||||
.max('display_order as maxOrder')
|
||||
.first();
|
||||
const nextOrder = (maxRow?.maxOrder || 0) + 1;
|
||||
|
||||
// Create category
|
||||
const insertResult = await db('photo_categories').insert({
|
||||
name,
|
||||
slug: categorySlug,
|
||||
is_global,
|
||||
event_id: is_global ? null : event_id
|
||||
event_id: is_global ? null : event_id,
|
||||
display_order: nextOrder
|
||||
}).returning('id');
|
||||
|
||||
const categoryId = insertResult[0]?.id || insertResult[0];
|
||||
@@ -254,4 +265,133 @@ router.delete('/:id', adminAuth, requirePermission('settings.edit'), async (req,
|
||||
}
|
||||
});
|
||||
|
||||
// Set a per-event category order override (#782). The client sends the full
|
||||
// ordered id list for THIS event — globals + event-specific, interleaved — and
|
||||
// we replace the event's override rows in one transaction. This overrides the
|
||||
// global default order for this gallery only.
|
||||
router.post('/reorder', adminAuth, requirePermission('settings.edit'), [
|
||||
body('event_id').isInt().withMessage('event_id must be an integer'),
|
||||
body('orderedIds').isArray({ min: 1 }).withMessage('orderedIds must be a non-empty array'),
|
||||
body('orderedIds.*').isInt().withMessage('Each id must be an integer')
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({ errors: errors.array() });
|
||||
}
|
||||
|
||||
const eventId = parseInt(req.body.event_id, 10);
|
||||
const orderedIds = req.body.orderedIds.map((id) => parseInt(id, 10));
|
||||
|
||||
// Event ownership (event_id comes from the body, so requireEventOwnership —
|
||||
// which reads req.params — can't be used here). Mirror it: super_admins
|
||||
// bypass; other admins may only reorder events they own (ownerless
|
||||
// legacy/system events allowed).
|
||||
if (req.admin.roleName !== 'super_admin') {
|
||||
const event = await db('events').where('id', eventId).first();
|
||||
if (!event) {
|
||||
return res.status(404).json({ error: 'Event not found' });
|
||||
}
|
||||
if (event.created_by && event.created_by !== req.admin.id) {
|
||||
return res.status(403).json({ error: 'Access denied' });
|
||||
}
|
||||
}
|
||||
|
||||
// Every id must be a category available to this event: a shared global OR
|
||||
// one of the event's own categories. Anything else is out of scope.
|
||||
const available = await db('photo_categories')
|
||||
.where(function() {
|
||||
this.where('is_global', formatBoolean(true)).orWhere('event_id', eventId);
|
||||
})
|
||||
.pluck('id');
|
||||
const availableSet = new Set(available);
|
||||
const invalid = orderedIds.filter((id) => !availableSet.has(id));
|
||||
if (invalid.length > 0) {
|
||||
return res.status(400).json({ error: 'One or more categories are not available for this event' });
|
||||
}
|
||||
|
||||
await db.transaction(async (trx) => {
|
||||
await trx('event_category_order').where('event_id', eventId).del();
|
||||
await trx('event_category_order').insert(
|
||||
orderedIds.map((id, i) => ({ event_id: eventId, category_id: id, position: i + 1 }))
|
||||
);
|
||||
});
|
||||
|
||||
// Log activity after commit (avoids a SQLite in-transaction global write).
|
||||
await logActivity('event_category_order_set',
|
||||
{ eventId, count: orderedIds.length },
|
||||
eventId,
|
||||
{ type: 'admin', id: req.admin.id, name: req.admin.username }
|
||||
);
|
||||
|
||||
res.json(await getEventCategoriesOrdered(eventId));
|
||||
} catch (error) {
|
||||
logger.error('Error reordering categories:', error);
|
||||
res.status(500).json({ error: 'Failed to reorder categories' });
|
||||
}
|
||||
});
|
||||
|
||||
// Clear an event's override — revert this gallery to the global default order.
|
||||
router.delete('/reorder/:eventId', adminAuth, requirePermission('settings.edit'), requireEventOwnership, async (req, res) => {
|
||||
try {
|
||||
const eventId = parseInt(req.params.eventId, 10);
|
||||
await db('event_category_order').where('event_id', eventId).del();
|
||||
|
||||
await logActivity('event_category_order_reset',
|
||||
{ eventId },
|
||||
eventId,
|
||||
{ type: 'admin', id: req.admin.id, name: req.admin.username }
|
||||
);
|
||||
|
||||
res.json(await getEventCategoriesOrdered(eventId));
|
||||
} catch (error) {
|
||||
logger.error('Error resetting category order:', error);
|
||||
res.status(500).json({ error: 'Failed to reset category order' });
|
||||
}
|
||||
});
|
||||
|
||||
// Set the GLOBAL default order for shared (global) categories (#782). Applies
|
||||
// to every gallery that hasn't set its own override. Rewrites display_order.
|
||||
router.post('/reorder-global', adminAuth, requirePermission('settings.edit'), [
|
||||
body('orderedIds').isArray({ min: 1 }).withMessage('orderedIds must be a non-empty array'),
|
||||
body('orderedIds.*').isInt().withMessage('Each id must be an integer')
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({ errors: errors.array() });
|
||||
}
|
||||
|
||||
const orderedIds = req.body.orderedIds.map((id) => parseInt(id, 10));
|
||||
|
||||
const globals = await db('photo_categories').where('is_global', formatBoolean(true)).pluck('id');
|
||||
const globalsSet = new Set(globals);
|
||||
const invalid = orderedIds.filter((id) => !globalsSet.has(id));
|
||||
if (invalid.length > 0) {
|
||||
return res.status(400).json({ error: 'One or more categories are not global' });
|
||||
}
|
||||
|
||||
await db.transaction(async (trx) => {
|
||||
for (let i = 0; i < orderedIds.length; i += 1) {
|
||||
await trx('photo_categories').where('id', orderedIds[i]).update({ display_order: i + 1 });
|
||||
}
|
||||
});
|
||||
|
||||
await logActivity('global_category_order_set',
|
||||
{ count: orderedIds.length },
|
||||
null,
|
||||
{ type: 'admin', id: req.admin.id, name: req.admin.username }
|
||||
);
|
||||
|
||||
const categories = await db('photo_categories')
|
||||
.where('is_global', formatBoolean(true))
|
||||
.orderBy('display_order', 'asc')
|
||||
.orderBy('name', 'asc');
|
||||
res.json(categories);
|
||||
} catch (error) {
|
||||
logger.error('Error reordering global categories:', error);
|
||||
res.status(500).json({ error: 'Failed to reorder global categories' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -419,7 +419,7 @@ router.post('/accounts', adminAuth, messagingGate, requirePermission('email.edit
|
||||
account_key: b.account_key,
|
||||
imap_pass: (b.imap_pass && b.imap_pass !== '********') ? b.imap_pass : '',
|
||||
smtp_pass: (b.smtp_pass && b.smtp_pass !== '********') ? b.smtp_pass : '',
|
||||
created_at: new Date(),
|
||||
created_at: new Date().toISOString(),
|
||||
...patch,
|
||||
});
|
||||
}
|
||||
@@ -808,8 +808,8 @@ router.post('/send', adminAuth, messagingGate, requirePermission('email.send'),
|
||||
status: 'sent',
|
||||
origin: 'manual',
|
||||
rendered_html: html,
|
||||
created_at: new Date(),
|
||||
sent_at: new Date(),
|
||||
created_at: new Date().toISOString(),
|
||||
sent_at: new Date().toISOString(),
|
||||
});
|
||||
res.json({ ok: true });
|
||||
} catch (error) {
|
||||
@@ -985,7 +985,7 @@ router.put('/templates/:key', [
|
||||
template_id: template.id,
|
||||
language,
|
||||
...row,
|
||||
created_at: new Date(),
|
||||
created_at: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1099,7 +1099,7 @@ router.post('/templates', [
|
||||
subject: content.subject || '',
|
||||
body_html: content.body_html || '',
|
||||
body_text: content.body_text || '',
|
||||
created_at: new Date(),
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -178,7 +178,7 @@ router.put('/:id', adminAuth, requirePermission('settings.edit'), [
|
||||
if (error.code === 'NOT_FOUND') {
|
||||
return res.status(404).json({ error: error.message });
|
||||
}
|
||||
if (error.code === 'DUPLICATE_SLUG_PREFIX') {
|
||||
if (error.code === 'DUPLICATE_SLUG_PREFIX' || error.code === 'LAST_ACTIVE') {
|
||||
return res.status(400).json({ error: error.message });
|
||||
}
|
||||
|
||||
@@ -216,7 +216,7 @@ router.delete('/:id', adminAuth, requirePermission('settings.edit'), [
|
||||
if (error.code === 'NOT_FOUND') {
|
||||
return res.status(404).json({ error: error.message });
|
||||
}
|
||||
if (error.code === 'SYSTEM_TYPE' || error.code === 'IN_USE') {
|
||||
if (error.code === 'SYSTEM_TYPE' || error.code === 'IN_USE' || error.code === 'LAST_TYPE') {
|
||||
return res.status(400).json({ error: error.message });
|
||||
}
|
||||
|
||||
|
||||
@@ -94,7 +94,7 @@ module.exports = (router) => {
|
||||
body('allow_presigned_download').optional().isBoolean(),
|
||||
body('css_template_id').optional({ nullable: true, checkFalsy: true }).isInt(),
|
||||
// Hero logo settings
|
||||
body('hero_logo_visible').optional().isBoolean(),
|
||||
body('hero_logo_visible').optional({ nullable: true }).isBoolean(),
|
||||
body('hero_logo_size').optional({ nullable: true }).isIn(['small', 'medium', 'large', 'xlarge']),
|
||||
body('hero_logo_position').optional().isIn(['top', 'center', 'bottom']),
|
||||
// Header style settings (decoupled from layout)
|
||||
@@ -165,6 +165,7 @@ module.exports = (router) => {
|
||||
allow_likes = true,
|
||||
allow_comments = true,
|
||||
allow_favorites = true,
|
||||
allow_reactions = true,
|
||||
require_name_email = false,
|
||||
moderate_comments = true,
|
||||
show_feedback_to_guests = true,
|
||||
@@ -342,8 +343,10 @@ module.exports = (router) => {
|
||||
// hero_logo_visible: store NULL ("inherit") unless the admin explicitly
|
||||
// set it, so the global branding_logo_display_hero toggle keeps
|
||||
// controlling this gallery afterwards (#756). Only an explicit per-event
|
||||
// choice overrides the global.
|
||||
const effectiveHeroLogoVisible = req.body.hero_logo_visible !== undefined
|
||||
// choice overrides the global. `!= null` treats an explicit null the same
|
||||
// as omitted (both → inherit); otherwise formatBoolean(null) would coerce
|
||||
// to 0/false on SQLite instead of NULL (the PUT handler already does this).
|
||||
const effectiveHeroLogoVisible = req.body.hero_logo_visible != null
|
||||
? formatBoolean(hero_logo_visible)
|
||||
: null;
|
||||
// NULL = inherit the global branding_logo_size (#756), resolved at read
|
||||
@@ -488,6 +491,7 @@ module.exports = (router) => {
|
||||
allow_likes: formatBoolean(allow_likes),
|
||||
allow_comments: formatBoolean(allow_comments),
|
||||
allow_favorites: formatBoolean(allow_favorites),
|
||||
allow_reactions: formatBoolean(allow_reactions),
|
||||
require_name_email: formatBoolean(require_name_email),
|
||||
moderate_comments: formatBoolean(moderate_comments),
|
||||
show_feedback_to_guests: formatBoolean(show_feedback_to_guests),
|
||||
@@ -1109,6 +1113,7 @@ module.exports = (router) => {
|
||||
allow_likes: sourceFeedback.allow_likes,
|
||||
allow_comments: sourceFeedback.allow_comments,
|
||||
allow_favorites: sourceFeedback.allow_favorites,
|
||||
allow_reactions: sourceFeedback.allow_reactions,
|
||||
require_name_email: sourceFeedback.require_name_email,
|
||||
moderate_comments: sourceFeedback.moderate_comments,
|
||||
show_feedback_to_guests: sourceFeedback.show_feedback_to_guests,
|
||||
@@ -1172,6 +1177,9 @@ module.exports = (router) => {
|
||||
body('welcome_message').optional({ nullable: true, checkFalsy: true }).trim(),
|
||||
body('color_theme').optional({ nullable: true }),
|
||||
body('allow_user_uploads').optional().isBoolean(),
|
||||
// Reveal mode (#838): hide the gallery from guests until reveal.
|
||||
body('reveal_mode').optional().isBoolean(),
|
||||
body('reveal_at').optional({ nullable: true, checkFalsy: true }).isISO8601(),
|
||||
// Migration 143 — per-event reminder overrides. All three are
|
||||
// optional; nullable values are accepted so admins can clear an
|
||||
// override (e.g. drop a custom offset back to the global default).
|
||||
@@ -1224,7 +1232,7 @@ module.exports = (router) => {
|
||||
}),
|
||||
body('css_template_id').optional({ nullable: true, checkFalsy: true }).isInt(),
|
||||
// Hero logo settings
|
||||
body('hero_logo_visible').optional().isBoolean(),
|
||||
body('hero_logo_visible').optional({ nullable: true }).isBoolean(),
|
||||
body('hero_logo_size').optional({ nullable: true }).isIn(['small', 'medium', 'large', 'xlarge']),
|
||||
body('hero_logo_position').optional().isIn(['top', 'center', 'bottom']),
|
||||
// Header style settings (decoupled from layout)
|
||||
@@ -1484,6 +1492,39 @@ module.exports = (router) => {
|
||||
}
|
||||
}
|
||||
|
||||
// Reveal mode (#838). Turning the toggle ON from off clears
|
||||
// revealed_at, so a gallery can be re-hidden after a reveal;
|
||||
// reveal_at accepts null/'' to drop a schedule.
|
||||
if (Object.prototype.hasOwnProperty.call(updates, 'reveal_mode')) {
|
||||
const nextRevealMode = parseBooleanInput(updates.reveal_mode, false);
|
||||
updates.reveal_mode = formatBoolean(nextRevealMode);
|
||||
const wasOn = event.reveal_mode === true || event.reveal_mode === 1 || event.reveal_mode === '1';
|
||||
if (nextRevealMode && !wasOn) {
|
||||
updates.revealed_at = null;
|
||||
// A stale PAST schedule from a previous cycle would instantly
|
||||
// re-open the gate on re-arm. Only bites partial API updates —
|
||||
// isGalleryHidden() with the stamp cleared tells us whether the
|
||||
// stored schedule still hides anything.
|
||||
const { isGalleryHidden } = require('../../utils/revealMode');
|
||||
if (!Object.prototype.hasOwnProperty.call(updates, 'reveal_at')
|
||||
&& event.reveal_at
|
||||
&& !isGalleryHidden({ reveal_mode: true, revealed_at: null, reveal_at: event.reveal_at })) {
|
||||
updates.reveal_at = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(updates, 'reveal_at')) {
|
||||
// ISO string, not a Date object — the SQLite driver stringifies raw
|
||||
// Dates uselessly; ISO round-trips on both engines.
|
||||
updates.reveal_at = updates.reveal_at ? new Date(updates.reveal_at).toISOString() : null;
|
||||
// Scheduling a FUTURE reveal on an already-revealed gallery re-arms
|
||||
// hiding — that's the only way this state can be reached, since
|
||||
// "Reveal now" and the scheduler both clear/consume the schedule.
|
||||
if (updates.reveal_at && new Date(updates.reveal_at) > new Date() && event.revealed_at) {
|
||||
updates.revealed_at = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle client access fields (#172)
|
||||
if (Object.prototype.hasOwnProperty.call(updates, 'client_access_enabled')) {
|
||||
updates.client_access_enabled = formatBoolean(updates.client_access_enabled);
|
||||
@@ -1538,6 +1579,58 @@ module.exports = (router) => {
|
||||
});
|
||||
|
||||
// Delete event
|
||||
// Reveal now (#838): stamp revealed_at so the gallery opens for guests
|
||||
// immediately. Idempotent — revealing an already-revealed event no-ops.
|
||||
router.post('/:id/reveal', adminAuth, requirePermission('events.edit'), requireEventOwnership, async (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const event = await db('events').where('id', id).first();
|
||||
if (!event) {
|
||||
return res.status(404).json({ error: 'Event not found' });
|
||||
}
|
||||
const isOn = event.reveal_mode === true || event.reveal_mode === 1 || event.reveal_mode === '1';
|
||||
if (!isOn) {
|
||||
return res.status(400).json({ error: 'Reveal mode is not enabled for this event' });
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
// Also clear a pending schedule — "reveal now" makes it obsolete, and
|
||||
// a stale future reveal_at would re-arm hiding on the next form save.
|
||||
const stamped = await db('events')
|
||||
.where('id', id)
|
||||
.whereNull('revealed_at')
|
||||
.update({ revealed_at: now, reveal_at: null });
|
||||
|
||||
if (stamped === 1) {
|
||||
await logActivity('gallery_revealed', { scheduled: false }, id, {
|
||||
type: 'admin', id: req.admin.id, name: req.admin.username,
|
||||
});
|
||||
try {
|
||||
await require('../../services/workflows').emitWorkflowEvent('gallery.revealed', {
|
||||
entityType: 'event',
|
||||
entityId: parseInt(id, 10),
|
||||
dedupSuffix: String(new Date(now).getTime()),
|
||||
payload: {
|
||||
eventId: parseInt(id, 10),
|
||||
slug: event.slug,
|
||||
eventName: event.event_name,
|
||||
revealedAt: now,
|
||||
scheduled: false,
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
logger.warn('Failed to emit gallery.revealed workflow event', { eventId: id, error: e.message });
|
||||
}
|
||||
}
|
||||
|
||||
const fresh = await db('events').where('id', id).first();
|
||||
res.json({ message: 'Gallery revealed', revealed_at: fresh.revealed_at });
|
||||
} catch (error) {
|
||||
logger.error('Failed to reveal gallery:', error);
|
||||
res.status(500).json({ error: 'Failed to reveal gallery' });
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/:id', adminAuth, requirePermission('events.delete'), requireEventOwnership, async (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
@@ -307,6 +307,9 @@ async function deleteEventCascade(eventId, adminContext) {
|
||||
const SLIDESHOW_TRANSITIONS = ['crossfade', 'cut', 'slide', 'kenburns', 'dipwhite', 'dipblack'];
|
||||
// Allowed per-slide color filters.
|
||||
const SLIDESHOW_COLORFILTERS = ['none', 'bw', 'sepia', 'warm', 'cool', 'vignette'];
|
||||
// Allowed slideshow play orders (#202). 'chronological' = upload order,
|
||||
// 'random' = client-side shuffle.
|
||||
const SLIDESHOW_ORDERS = ['chronological', 'random'];
|
||||
module.exports = {
|
||||
validateHeroImageAnchor,
|
||||
getStoragePath,
|
||||
@@ -321,6 +324,7 @@ module.exports = {
|
||||
mapEventForApi,
|
||||
hasCustomerContactColumns,
|
||||
deleteEventCascade,
|
||||
SLIDESHOW_ORDERS,
|
||||
SLIDESHOW_TRANSITIONS,
|
||||
SLIDESHOW_COLORFILTERS,
|
||||
};
|
||||
|
||||
@@ -13,5 +13,6 @@ require('./slideshow')(router);
|
||||
require('./resets')(router);
|
||||
require('./archiveBulk')(router);
|
||||
require('./logo')(router);
|
||||
require('./qr')(router);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
// Gallery QR codes (#836): QR image (PNG/SVG) for the event's share link and
|
||||
// print-ready PDF templates (table card A6, poster A4) built with pdfkit.
|
||||
// Registered after ./logo in ./index.js — all routes are '/:id/...' literals,
|
||||
// so registration order relative to the other sub-modules is not sensitive.
|
||||
|
||||
const path = require('path');
|
||||
const QRCode = require('qrcode');
|
||||
const PDFDocument = require('pdfkit');
|
||||
const { db } = require('../../database/db');
|
||||
const { adminAuth } = require('../../middleware/auth');
|
||||
const { requirePermission } = require('../../middleware/permissions');
|
||||
const { requireEventOwnership } = require('../../middleware/ownership');
|
||||
const { buildShareLinkVariants, getEventShareToken } = require('../../services/shareLinkService');
|
||||
const { getFrontendBaseUrl } = require('../../utils/frontendUrl');
|
||||
const logger = require('../../utils/logger');
|
||||
const { errorResponse } = require('../../utils/routeHelpers');
|
||||
|
||||
// Caption under the QR on the print templates, in the admin's UI language
|
||||
// (passed as ?lang= by the frontend). Mirrors the 8 gallery locales.
|
||||
const PRINT_CAPTIONS = {
|
||||
en: 'Scan to view & share your photos',
|
||||
de: 'Scannen, um Fotos anzusehen & zu teilen',
|
||||
es: 'Escanea para ver y compartir tus fotos',
|
||||
fr: 'Scannez pour voir et partager vos photos',
|
||||
nl: 'Scan om foto’s te bekijken & te delen',
|
||||
pt: 'Escaneie para ver e compartilhar suas fotos',
|
||||
ru: 'Отсканируйте, чтобы посмотреть и поделиться фото',
|
||||
sl: 'Skenirajte za ogled in deljenje fotografij',
|
||||
};
|
||||
|
||||
// A6 = 298 x 420 pt, A4 = 595 x 842 pt (pdfkit default unit).
|
||||
const TEMPLATES = {
|
||||
'table-card': { size: [298, 420], qrSize: 180, titleSize: 16, captionSize: 10, urlSize: 7 },
|
||||
poster: { size: 'A4', qrSize: 360, titleSize: 28, captionSize: 16, urlSize: 10 },
|
||||
};
|
||||
|
||||
// Bundled COMPLETE IBM Plex Sans (1019 glyphs: Latin + Cyrillic + Greek,
|
||||
// verified via fontkit cmap) — pdfkit's built-in Helvetica is WinAnsi-only
|
||||
// and silently drops e.g. Cyrillic event names, and the pre-existing
|
||||
// assets/fonts/IBM-Plex-Sans/ files are 270-glyph Latin subsets with the
|
||||
// same gap (codex review of #847). OFL license alongside the files.
|
||||
const FONT_BOLD = path.join(__dirname, '../../../assets/fonts/IBM-Plex-Sans-Full/700.ttf');
|
||||
const FONT_REGULAR = path.join(__dirname, '../../../assets/fonts/IBM-Plex-Sans-Full/400.ttf');
|
||||
|
||||
// A same-origin admin GET carries no Origin header, so the frontend passes
|
||||
// window.location.origin explicitly. Only accept a plain http(s) origin.
|
||||
const ORIGIN_RE = /^https?:\/\/[^\s/]+$/i;
|
||||
// Configured FRONTEND_URL defaults to localhost on unconfigured installs —
|
||||
// a QR pointing there is unusable on any other device (codex review of #847).
|
||||
const LOCAL_BASE_RE = /^https?:\/\/(localhost|127\.|0\.0\.0\.0|\[::1\])/i;
|
||||
|
||||
async function loadShareUrl(eventId, requestOrigin) {
|
||||
const event = await db('events').where({ id: eventId }).first();
|
||||
if (!event) return { event: null, shareUrl: null };
|
||||
|
||||
// Single source of truth is the STORED share_link — exactly what the
|
||||
// ShareLinkCard displays and the admin copies. Rebuilding from the
|
||||
// current slug/token/short-URL setting can diverge for legacy absolute
|
||||
// links or events created under a different short-URL setting, and a
|
||||
// printed QR encoding a different URL than the card is a permanent
|
||||
// mistake (codex review of #847, confirmation round). Only when no
|
||||
// share_link is stored do we fall back to rebuilding it.
|
||||
let link = event.share_link;
|
||||
if (!link) {
|
||||
const shareToken = getEventShareToken(event);
|
||||
if (!shareToken) return { event, shareUrl: null };
|
||||
({ shareLinkToStore: link } = await buildShareLinkVariants({ slug: event.slug, shareToken }));
|
||||
}
|
||||
|
||||
const origin = typeof requestOrigin === 'string' && ORIGIN_RE.test(requestOrigin)
|
||||
? requestOrigin.replace(/\/$/, '')
|
||||
: null;
|
||||
|
||||
// Absolute + reachable → use as-is; loopback-absolute → re-anchor its
|
||||
// path; relative → absolutize. Mirrors the frontend's buildShareLinkUrl.
|
||||
if (/^https?:\/\//i.test(link) && !LOCAL_BASE_RE.test(link)) {
|
||||
return { event, shareUrl: link };
|
||||
}
|
||||
let sharePath = link;
|
||||
if (/^https?:\/\//i.test(link)) {
|
||||
try { const u = new URL(link); sharePath = `${u.pathname}${u.search}`; } catch { /* keep as-is */ }
|
||||
}
|
||||
// Bare stored values (quote-/contract-converted events persist the raw
|
||||
// token) resolve as /gallery/<token> — mirroring the frontend's
|
||||
// buildShareLinkUrl exactly (codex review of #847, final round).
|
||||
if (!sharePath.startsWith('/')) sharePath = `/gallery/${sharePath}`;
|
||||
if (origin) return { event, shareUrl: `${origin}${sharePath}` };
|
||||
const frontendBase = await getFrontendBaseUrl();
|
||||
return { event, shareUrl: frontendBase ? `${frontendBase}${sharePath}` : sharePath };
|
||||
}
|
||||
|
||||
module.exports = (router) => {
|
||||
// QR image for the gallery share link.
|
||||
router.get('/:id/qr', adminAuth, requirePermission('events.view'), requireEventOwnership, async (req, res) => {
|
||||
try {
|
||||
const { event, shareUrl } = await loadShareUrl(req.params.id, req.query.origin);
|
||||
if (!event) return errorResponse(res, 'Event not found', 404);
|
||||
if (!shareUrl) return errorResponse(res, 'Event has no share link', 409);
|
||||
|
||||
const format = req.query.format === 'svg' ? 'svg' : 'png';
|
||||
const download = req.query.download === '1';
|
||||
const disposition = `${download ? 'attachment' : 'inline'}; filename="qr-${event.slug}.${format}"`;
|
||||
|
||||
if (format === 'svg') {
|
||||
const svg = await QRCode.toString(shareUrl, { type: 'svg', margin: 4 });
|
||||
res.set('Content-Type', 'image/svg+xml');
|
||||
res.set('Content-Disposition', disposition);
|
||||
return res.send(svg);
|
||||
}
|
||||
|
||||
const width = Math.min(Math.max(parseInt(req.query.size, 10) || 600, 128), 2048);
|
||||
const png = await QRCode.toBuffer(shareUrl, { type: 'png', width, margin: 4 });
|
||||
res.set('Content-Type', 'image/png');
|
||||
res.set('Content-Disposition', disposition);
|
||||
return res.send(png);
|
||||
} catch (error) {
|
||||
logger.error('Failed to generate gallery QR code:', error);
|
||||
return errorResponse(res, error, 500, 'Failed to generate QR code');
|
||||
}
|
||||
});
|
||||
|
||||
// Print-ready PDF (table card / poster) with QR + event name + caption.
|
||||
router.get('/:id/qr-print', adminAuth, requirePermission('events.view'), requireEventOwnership, async (req, res) => {
|
||||
try {
|
||||
const { event, shareUrl } = await loadShareUrl(req.params.id, req.query.origin);
|
||||
if (!event) return errorResponse(res, 'Event not found', 404);
|
||||
if (!shareUrl) return errorResponse(res, 'Event has no share link', 409);
|
||||
|
||||
const templateKey = TEMPLATES[req.query.template] ? req.query.template : 'table-card';
|
||||
const tpl = TEMPLATES[templateKey];
|
||||
const caption = PRINT_CAPTIONS[req.query.lang] || PRINT_CAPTIONS.en;
|
||||
|
||||
const qrPng = await QRCode.toBuffer(shareUrl, { type: 'png', width: tpl.qrSize * 3, margin: 4 });
|
||||
|
||||
const doc = new PDFDocument({
|
||||
size: tpl.size,
|
||||
margins: { top: 0, bottom: 0, left: 0, right: 0 },
|
||||
info: { Title: `PicPeak QR — ${event.event_name}` },
|
||||
});
|
||||
res.set('Content-Type', 'application/pdf');
|
||||
res.set('Content-Disposition', `attachment; filename="qr-${templateKey}-${event.slug}.pdf"`);
|
||||
doc.pipe(res);
|
||||
|
||||
const pageWidth = doc.page.width;
|
||||
const pageHeight = doc.page.height;
|
||||
const contentTop = pageHeight * 0.12;
|
||||
|
||||
// Fixed vertical layout: the title gets a bounded two-line region with
|
||||
// ellipsis so an arbitrarily long event name can't push the QR/caption
|
||||
// over the footer or off the page (codex review of #847). All positions
|
||||
// below derive from constants, never from doc.y.
|
||||
const titleBlockHeight = tpl.titleSize * 2.6;
|
||||
doc.font(FONT_BOLD).fontSize(tpl.titleSize).fillColor('#1a1a1a')
|
||||
.text(event.event_name, pageWidth * 0.1, contentTop, {
|
||||
width: pageWidth * 0.8,
|
||||
align: 'center',
|
||||
height: titleBlockHeight,
|
||||
ellipsis: true,
|
||||
});
|
||||
|
||||
const qrX = (pageWidth - tpl.qrSize) / 2;
|
||||
const qrY = contentTop + titleBlockHeight + tpl.titleSize * 0.5;
|
||||
doc.image(qrPng, qrX, qrY, { width: tpl.qrSize, height: tpl.qrSize });
|
||||
|
||||
doc.font(FONT_REGULAR).fontSize(tpl.captionSize).fillColor('#333333')
|
||||
.text(caption, pageWidth * 0.1, qrY + tpl.qrSize + tpl.captionSize, { width: pageWidth * 0.8, align: 'center' });
|
||||
|
||||
doc.font(FONT_REGULAR).fontSize(tpl.urlSize).fillColor('#888888')
|
||||
.text(shareUrl, pageWidth * 0.05, pageHeight - pageHeight * 0.07, {
|
||||
width: pageWidth * 0.9,
|
||||
align: 'center',
|
||||
height: pageHeight * 0.06,
|
||||
ellipsis: true,
|
||||
});
|
||||
|
||||
doc.end();
|
||||
} catch (error) {
|
||||
logger.error('Failed to generate QR print PDF:', error);
|
||||
if (!res.headersSent) return errorResponse(res, error, 500, 'Failed to generate QR print PDF');
|
||||
return res.end();
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -13,7 +13,7 @@ const { parseBooleanInput } = require('../../utils/parsers');
|
||||
const { requireEventOwnership } = require('../../middleware/ownership');
|
||||
const { requireFeatureFlag } = require('../../middleware/requireFeatureFlag');
|
||||
const { getFrontendBaseUrl } = require('../../utils/frontendUrl');
|
||||
const { SLIDESHOW_TRANSITIONS, SLIDESHOW_COLORFILTERS } = require('./helpers');
|
||||
const { SLIDESHOW_TRANSITIONS, SLIDESHOW_COLORFILTERS, SLIDESHOW_ORDERS } = require('./helpers');
|
||||
|
||||
// The watermark LOOK (source/position/opacity/style/size) is global-only
|
||||
// (app_settings, Settings → Slideshow); events only carry the show_watermark
|
||||
@@ -105,7 +105,10 @@ module.exports = (router) => {
|
||||
body('show_transition').optional().isIn(SLIDESHOW_TRANSITIONS),
|
||||
body('show_transition_ms').optional().isInt({ min: 100, max: 5000 }),
|
||||
body('show_watermark').optional({ nullable: true }),
|
||||
body('show_colorfilter').optional().isIn(SLIDESHOW_COLORFILTERS)
|
||||
body('show_qr').optional({ nullable: true }),
|
||||
body('show_colorfilter').optional().isIn(SLIDESHOW_COLORFILTERS),
|
||||
body('show_order').optional().isIn(SLIDESHOW_ORDERS),
|
||||
body('show_category_id').optional({ nullable: true }).isInt({ min: 1 })
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
@@ -129,7 +132,30 @@ module.exports = (router) => {
|
||||
? null
|
||||
: formatBoolean(parseBooleanInput(req.body.show_watermark, false));
|
||||
}
|
||||
// QR overlay (#837) — same tri-state semantics as show_watermark.
|
||||
if (req.body.show_qr !== undefined) {
|
||||
updates.show_qr = req.body.show_qr === null
|
||||
? null
|
||||
: formatBoolean(parseBooleanInput(req.body.show_qr, false));
|
||||
}
|
||||
if (req.body.show_colorfilter !== undefined) updates.show_colorfilter = req.body.show_colorfilter;
|
||||
if (req.body.show_order !== undefined) updates.show_order = req.body.show_order;
|
||||
// Category filter (#202). null clears it (all photos). A non-null id must
|
||||
// belong to this event or be a global category — otherwise ignore it so a
|
||||
// stale/foreign id can't leak another event's category selection.
|
||||
if (req.body.show_category_id !== undefined) {
|
||||
if (req.body.show_category_id === null) {
|
||||
updates.show_category_id = null;
|
||||
} else {
|
||||
const catId = parseInt(req.body.show_category_id, 10);
|
||||
const cat = await db('photo_categories')
|
||||
.where({ id: catId })
|
||||
.where(function () { this.where('event_id', event.id).orWhere('is_global', formatBoolean(true)); })
|
||||
.first();
|
||||
if (!cat) return res.status(400).json({ error: 'Category does not belong to this event' });
|
||||
updates.show_category_id = catId;
|
||||
}
|
||||
}
|
||||
|
||||
// Knex throws on an empty update; only write if something changed.
|
||||
if (Object.keys(updates).length > 0) {
|
||||
@@ -141,7 +167,10 @@ module.exports = (router) => {
|
||||
show_transition: updates.show_transition ?? event.show_transition ?? 'crossfade',
|
||||
show_transition_ms: updates.show_transition_ms ?? event.show_transition_ms ?? 800,
|
||||
show_watermark: updates.show_watermark ?? event.show_watermark ?? null,
|
||||
show_colorfilter: updates.show_colorfilter ?? event.show_colorfilter ?? 'none'
|
||||
show_qr: 'show_qr' in updates ? updates.show_qr : (event.show_qr ?? null),
|
||||
show_colorfilter: updates.show_colorfilter ?? event.show_colorfilter ?? 'none',
|
||||
show_order: updates.show_order ?? event.show_order ?? 'chronological',
|
||||
show_category_id: 'show_category_id' in updates ? updates.show_category_id : (event.show_category_id ?? null)
|
||||
});
|
||||
} catch (error) {
|
||||
errorResponse(res, error, 500, 'Failed to update slideshow settings');
|
||||
|
||||
@@ -233,17 +233,22 @@ router.get('/events/:eventId/feedback-analytics',
|
||||
.count('* as count')
|
||||
.first();
|
||||
|
||||
// Number() everywhere: Postgres COUNT() comes back as a string, and
|
||||
// string + string in the total_feedback sum concatenates ("00006").
|
||||
const counts = {
|
||||
total_ratings: Number(summaryData.stats?.total_ratings) || 0,
|
||||
total_likes: Number(summaryData.stats?.total_likes) || 0,
|
||||
total_comments: Number(summaryData.stats?.total_comments) || 0,
|
||||
total_favorites: Number(summaryData.stats?.total_favorites) || 0,
|
||||
total_reactions: Number(summaryData.stats?.total_reactions) || 0,
|
||||
};
|
||||
const summary = {
|
||||
average_rating: parseFloat(avgRatingResult?.average_rating || 0),
|
||||
total_ratings: summaryData.stats?.total_ratings || 0,
|
||||
total_likes: summaryData.stats?.total_likes || 0,
|
||||
total_comments: summaryData.stats?.total_comments || 0,
|
||||
total_favorites: summaryData.stats?.total_favorites || 0,
|
||||
pending_moderation: pendingModeration?.count || 0,
|
||||
total_feedback: (summaryData.stats?.total_ratings || 0) +
|
||||
(summaryData.stats?.total_likes || 0) +
|
||||
(summaryData.stats?.total_comments || 0) +
|
||||
(summaryData.stats?.total_favorites || 0)
|
||||
...counts,
|
||||
pending_moderation: Number(pendingModeration?.count) || 0,
|
||||
total_feedback: counts.total_ratings + counts.total_likes +
|
||||
counts.total_comments + counts.total_favorites +
|
||||
counts.total_reactions
|
||||
};
|
||||
|
||||
// Get top-rated photos
|
||||
|
||||
@@ -78,6 +78,7 @@ router.get(
|
||||
db.raw('COUNT(CASE WHEN photo_feedback.feedback_type = \'favorite\' THEN 1 END) AS favorites'),
|
||||
db.raw('COUNT(CASE WHEN photo_feedback.feedback_type = \'comment\' THEN 1 END) AS comments'),
|
||||
db.raw('COUNT(CASE WHEN photo_feedback.feedback_type = \'rating\' THEN 1 END) AS ratings'),
|
||||
db.raw('COUNT(CASE WHEN photo_feedback.feedback_type = \'reaction\' THEN 1 END) AS reactions'),
|
||||
db.raw('COUNT(DISTINCT photo_feedback.photo_id) AS distinct_photos')
|
||||
)
|
||||
.orderBy('gallery_guests.created_at', 'desc');
|
||||
@@ -89,6 +90,7 @@ router.get(
|
||||
favorites: parseInt(r.favorites, 10) || 0,
|
||||
comments: parseInt(r.comments, 10) || 0,
|
||||
ratings: parseInt(r.ratings, 10) || 0,
|
||||
reactions: parseInt(r.reactions, 10) || 0,
|
||||
distinct_photos: parseInt(r.distinct_photos, 10) || 0,
|
||||
},
|
||||
}));
|
||||
@@ -401,6 +403,7 @@ router.get(
|
||||
'photo_feedback.feedback_type',
|
||||
'photo_feedback.rating',
|
||||
'photo_feedback.comment_text',
|
||||
'photo_feedback.reaction',
|
||||
'photo_feedback.created_at',
|
||||
'photos.id as photo_id',
|
||||
'photos.filename',
|
||||
@@ -423,6 +426,7 @@ router.get(
|
||||
favorited: [],
|
||||
rated: [],
|
||||
commented: [],
|
||||
reacted: [],
|
||||
};
|
||||
for (const row of feedback) {
|
||||
if (row.feedback_type === 'like') {
|
||||
@@ -437,6 +441,8 @@ router.get(
|
||||
comment: row.comment_text,
|
||||
created_at: row.created_at,
|
||||
});
|
||||
} else if (row.feedback_type === 'reaction') {
|
||||
selections.reacted.push({ photo: photoFor(row), reaction: row.reaction });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -448,6 +454,7 @@ router.get(
|
||||
favorites: selections.favorited.length,
|
||||
comments: selections.commented.length,
|
||||
ratings: selections.rated.length,
|
||||
reactions: selections.reacted.length,
|
||||
},
|
||||
},
|
||||
selections,
|
||||
|
||||
@@ -25,12 +25,33 @@ const { resetSecurityConfigCache } = require('../utils/authSecurity');
|
||||
const { errorResponse } = require('../utils/routeHelpers');
|
||||
const logger = require('../utils/logger');
|
||||
const router = express.Router();
|
||||
const { clearMaxFilesPerUploadCache, MAX_ALLOWED_FILES_PER_UPLOAD } = require('../services/uploadSettings');
|
||||
const { clearMaxFilesPerUploadCache, MAX_ALLOWED_FILES_PER_UPLOAD, clearMaxFileSizeCache, MAX_ALLOWED_FILE_SIZE_MB } = require('../services/uploadSettings');
|
||||
const watermarkService = require('../services/watermarkService');
|
||||
const watermarkGeneratorService = require('../services/watermarkGeneratorService');
|
||||
|
||||
const getStoragePath = () => process.env.STORAGE_PATH || path.join(__dirname, '../../../storage');
|
||||
|
||||
// Reserved first-run bootstrap keys — never writable through the generic
|
||||
// settings upserts in this file: setup_wizard_completed is a one-way marker
|
||||
// (#800; writing false would reopen system-event-type deletion) and
|
||||
// setup_token is the first-run bootstrap secret. Every handler that loops
|
||||
// arbitrary request keys into app_settings must strip these first.
|
||||
// oidc_client_secret is reserved too: it is AES-encrypted at rest and only
|
||||
// writable through PUT /sso below — a generic upsert would store plaintext
|
||||
// and break decryption (#798).
|
||||
const RESERVED_SETTING_KEYS = ['setup_wizard_completed', 'setup_token'];
|
||||
// EVERY oidc_* key is reserved (#798 phase 2): the client secret would be
|
||||
// clobbered with plaintext, and the policy/mapping keys carry invariants
|
||||
// (role targets exist, break-glass account present) that only the dedicated
|
||||
// PUT /sso validates — a generic upsert would bypass all of them.
|
||||
const isReservedSettingKey = (key) => RESERVED_SETTING_KEYS.includes(key) || key.startsWith('oidc_');
|
||||
const stripReservedSettingKeys = (settings) => {
|
||||
for (const key of Object.keys(settings)) {
|
||||
if (isReservedSettingKey(key)) delete settings[key];
|
||||
}
|
||||
return settings;
|
||||
};
|
||||
|
||||
// Configure multer for logo uploads
|
||||
const storage = multer.diskStorage({
|
||||
destination: async (req, file, cb) => {
|
||||
@@ -143,10 +164,26 @@ router.get('/', adminAuth, requirePermission('settings.view'), async (req, res)
|
||||
}
|
||||
});
|
||||
|
||||
// Reserved bootstrap/credential keys are NEVER readable through the
|
||||
// generic settings reads — oidc_client_secret (#798) is stored encrypted
|
||||
// with setting_type 'string' and would otherwise leak its ciphertext to
|
||||
// any settings.view holder; setup_token is the first-run bootstrap secret.
|
||||
stripReservedSettingKeys(settingsObject);
|
||||
|
||||
// Mask sensitive secrets before sending to client
|
||||
if (settingsObject.security_recaptcha_secret_key) {
|
||||
settingsObject.security_recaptcha_secret_key = '••••••••';
|
||||
}
|
||||
// Backup credentials — the S3 secret key and the rsync SSH PRIVATE KEY
|
||||
// were returned in plaintext to any settings.view holder. Same masking
|
||||
// pattern as the recaptcha/umami/rybbit keys; the dedicated
|
||||
// /admin/backup/config endpoints handle the edit round-trip.
|
||||
if (settingsObject.backup_s3_secret_key) {
|
||||
settingsObject.backup_s3_secret_key = '••••••••';
|
||||
}
|
||||
if (settingsObject.backup_rsync_ssh_key) {
|
||||
settingsObject.backup_rsync_ssh_key = '••••••••';
|
||||
}
|
||||
// Umami v2 API key (#661 Bug C) — read-write secret that authenticates
|
||||
// outbound calls to the operator's Umami instance for the device
|
||||
// breakdown. Masked on GET, same pattern as the recaptcha secret.
|
||||
@@ -349,6 +386,21 @@ router.put('/slideshow', adminAuth, requirePermission('settings.edit'), async (r
|
||||
const n = Math.min(40, Math.max(3, Math.round(Number(req.body.slideshow_watermark_size) || 12)));
|
||||
push('slideshow_watermark_size', n);
|
||||
}
|
||||
// QR overlay (#837) — same option shape as the watermark.
|
||||
if (has('slideshow_qr_enabled')) push('slideshow_qr_enabled', !!req.body.slideshow_qr_enabled);
|
||||
if (has('slideshow_qr_position')) {
|
||||
const allowed = ['top-left', 'top-right', 'bottom-left', 'bottom-right'];
|
||||
const v = allowed.includes(req.body.slideshow_qr_position) ? req.body.slideshow_qr_position : 'bottom-left';
|
||||
push('slideshow_qr_position', v);
|
||||
}
|
||||
if (has('slideshow_qr_opacity')) {
|
||||
const n = Math.min(100, Math.max(0, Math.round(Number(req.body.slideshow_qr_opacity) || 0)));
|
||||
push('slideshow_qr_opacity', n);
|
||||
}
|
||||
if (has('slideshow_qr_size')) {
|
||||
const n = Math.min(40, Math.max(5, Math.round(Number(req.body.slideshow_qr_size) || 14)));
|
||||
push('slideshow_qr_size', n);
|
||||
}
|
||||
|
||||
for (const u of updates) {
|
||||
await upsertAppSetting(u.setting_key, u.setting_value, u.setting_type);
|
||||
@@ -363,6 +415,170 @@ router.put('/slideshow', adminAuth, requirePermission('settings.edit'), async (r
|
||||
});
|
||||
|
||||
// Get settings by type
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
// OIDC SSO settings (#798). Dedicated endpoints — NOT the generic upsert —
|
||||
// because the client secret must be encrypted at rest and never echoed back.
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
|
||||
// Read the SSO config. The secret is redacted to a set/unset flag; the
|
||||
// computed redirect URI is included for copy-paste into the IdP client.
|
||||
router.get('/sso', adminAuth, requirePermission('settings.view'), async (req, res) => {
|
||||
try {
|
||||
const oidcService = require('../services/oidcService');
|
||||
const cfg = await oidcService.getOidcConfig();
|
||||
// No public base URL configured → surface an empty redirect_uri rather
|
||||
// than failing the whole settings read; the login route refuses to start
|
||||
// the flow in that state anyway (OIDC_BAD_CONFIG).
|
||||
const redirectUri = await oidcService.getRedirectUri().catch(() => '');
|
||||
res.json({
|
||||
oidc_enabled: cfg.enabled,
|
||||
oidc_issuer_url: cfg.issuerUrl || '',
|
||||
oidc_client_id: cfg.clientId || '',
|
||||
oidc_client_secret_set: Boolean(cfg.clientSecret),
|
||||
oidc_autoprovision: cfg.autoprovision,
|
||||
oidc_default_role: cfg.defaultRole,
|
||||
oidc_button_label: cfg.buttonLabel || '',
|
||||
oidc_scopes: cfg.scopes,
|
||||
oidc_role_mapping_enabled: cfg.roleMappingEnabled,
|
||||
oidc_roles_claim: cfg.rolesClaim,
|
||||
oidc_role_mappings: cfg.roleMappings,
|
||||
oidc_require_mapped_role: cfg.requireMappedRole,
|
||||
oidc_disable_local_login: cfg.disableLocalLogin,
|
||||
redirect_uri: redirectUri,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to read SSO settings', { error: error.message });
|
||||
res.status(500).json({ error: 'Failed to read SSO settings' });
|
||||
}
|
||||
});
|
||||
|
||||
router.put('/sso', adminAuth, requirePermission('settings.edit'), [
|
||||
body('oidc_enabled').optional().isBoolean(),
|
||||
body('oidc_issuer_url').optional({ checkFalsy: true }).isURL({ protocols: ['http', 'https'], require_tld: false }),
|
||||
body('oidc_client_id').optional().isString().trim(),
|
||||
body('oidc_client_secret').optional().isString(),
|
||||
body('oidc_autoprovision').optional().isBoolean(),
|
||||
body('oidc_default_role').optional().isString().trim(),
|
||||
body('oidc_button_label').optional().isString().trim().isLength({ max: 60 }),
|
||||
body('oidc_scopes').optional().isString().trim(),
|
||||
body('oidc_role_mapping_enabled').optional().isBoolean(),
|
||||
body('oidc_roles_claim').optional().isString().trim().isLength({ max: 200 }),
|
||||
body('oidc_role_mappings').optional().isObject(),
|
||||
body('oidc_require_mapped_role').optional().isBoolean(),
|
||||
body('oidc_disable_local_login').optional().isBoolean(),
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({ errors: errors.array() });
|
||||
}
|
||||
const oidcService = require('../services/oidcService');
|
||||
|
||||
// Validate the MERGED resulting state, not just the request: enabling
|
||||
// requires a complete config, and a partial PUT must not be able to
|
||||
// blank the issuer/client while a stored enabled=true keeps a login
|
||||
// button alive that can only fail.
|
||||
const current = await oidcService.getOidcConfig();
|
||||
const effectiveEnabled = req.body.oidc_enabled ?? current.enabled;
|
||||
if (effectiveEnabled === true) {
|
||||
const issuer = req.body.oidc_issuer_url ?? current.issuerUrl;
|
||||
const clientId = req.body.oidc_client_id ?? current.clientId;
|
||||
const secretPresent = (typeof req.body.oidc_client_secret === 'string' && req.body.oidc_client_secret.length > 0)
|
||||
|| Boolean(current.clientSecret);
|
||||
if (!issuer || !clientId || !secretPresent) {
|
||||
return res.status(400).json({ error: 'Issuer URL, client ID and client secret must be configured while SSO is enabled — disable SSO first to clear them' });
|
||||
}
|
||||
// The redirect URI must be derivable too, or the login button leads
|
||||
// straight to an error (needs API_URL / FRONTEND_URL / general_site_url).
|
||||
try {
|
||||
await oidcService.getRedirectUri();
|
||||
} catch (err) {
|
||||
return res.status(400).json({ error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
// Default role must exist — a typo here would brick JIT provisioning.
|
||||
if (req.body.oidc_default_role !== undefined) {
|
||||
const role = await db('roles').where('name', req.body.oidc_default_role).first();
|
||||
if (!role) {
|
||||
return res.status(400).json({ error: `Unknown role: ${req.body.oidc_default_role}` });
|
||||
}
|
||||
}
|
||||
|
||||
// Every role-mapping target must exist too (#798 phase 2) — a typo'd
|
||||
// role name would silently map users to nothing.
|
||||
if (req.body.oidc_role_mappings !== undefined) {
|
||||
const targets = [...new Set(Object.values(req.body.oidc_role_mappings).map((r) => String(r).trim()).filter(Boolean))];
|
||||
if (targets.length > 0) {
|
||||
const known = (await db('roles').whereIn('name', targets)).map((r) => r.name);
|
||||
const unknown = targets.filter((t) => !known.includes(t));
|
||||
if (unknown.length > 0) {
|
||||
return res.status(400).json({ error: `Unknown role(s) in mapping: ${unknown.join(', ')}` });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Turning OFF local login requires SSO to be (staying) enabled. Only the
|
||||
// explicit request is checked — a stored true must never block disabling
|
||||
// SSO itself (runtime enforcement ignores the flag while SSO is off or
|
||||
// unconfigured, and OIDC_BREAK_GLASS=true always re-opens local login).
|
||||
if (req.body.oidc_disable_local_login === true && effectiveEnabled !== true) {
|
||||
return res.status(400).json({ error: 'Local login can only be disabled while SSO is enabled' });
|
||||
}
|
||||
|
||||
// …and an active LOCAL-password super_admin must exist as the break-glass
|
||||
// account: OIDC_BREAK_GLASS only re-opens the password route, but
|
||||
// OIDC-owned accounts are refused there and carry unusable random hashes.
|
||||
// settings.edit is super_admin-only, so a lesser local account couldn't
|
||||
// fix the SSO config either — without this check an all-OIDC instance
|
||||
// would be unrecoverable during an IdP outage. Checked on the MERGED
|
||||
// state, not just the request: re-enabling SSO while a stored true flag
|
||||
// re-arms SSO-only mode just as much as setting the flag itself.
|
||||
const effectiveDisableLocal = req.body.oidc_disable_local_login ?? current.disableLocalLogin;
|
||||
if (effectiveDisableLocal === true && effectiveEnabled === true) {
|
||||
if (!(await oidcService.hasActiveLocalSuperAdmin())) {
|
||||
return res.status(400).json({ error: 'Disabling local login requires at least one active Super Admin with a local password (the break-glass account)' });
|
||||
}
|
||||
}
|
||||
|
||||
await oidcService.saveOidcSettings(req.body);
|
||||
|
||||
await logActivity('sso_settings_updated',
|
||||
{ changes: Object.keys(req.body).filter((k) => k !== 'oidc_client_secret') },
|
||||
null,
|
||||
{ type: 'admin', id: req.admin.id, name: req.admin.username }
|
||||
);
|
||||
|
||||
res.json({ message: 'SSO settings saved' });
|
||||
} catch (error) {
|
||||
logger.error('Failed to save SSO settings', { error: error.message });
|
||||
res.status(500).json({ error: 'Failed to save SSO settings' });
|
||||
}
|
||||
});
|
||||
|
||||
// Server-side discovery probe: confirms the issuer is reachable and speaks
|
||||
// OIDC before the admin flips the enable toggle. Uses the SAVED config.
|
||||
router.post('/sso/test', adminAuth, requirePermission('settings.edit'), async (req, res) => {
|
||||
try {
|
||||
const oidcService = require('../services/oidcService');
|
||||
const cfg = await oidcService.getOidcConfig();
|
||||
if (!oidcService.isConfigured(cfg)) {
|
||||
return res.status(400).json({ ok: false, error: 'Issuer URL, client ID and client secret must be saved first' });
|
||||
}
|
||||
oidcService.invalidateDiscoveryCache();
|
||||
const { issuerMetadata } = await oidcService.getClient(cfg);
|
||||
res.json({
|
||||
ok: true,
|
||||
issuer: issuerMetadata.issuer,
|
||||
authorization_endpoint: issuerMetadata.authorization_endpoint,
|
||||
token_endpoint: issuerMetadata.token_endpoint,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.warn('SSO discovery test failed', { error: error.message });
|
||||
res.status(400).json({ ok: false, error: `Discovery failed: ${error.message}` });
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/:type', adminAuth, requirePermission('settings.view'), async (req, res) => {
|
||||
try {
|
||||
const { type } = req.params;
|
||||
@@ -393,10 +609,26 @@ router.get('/:type', adminAuth, requirePermission('settings.view'), async (req,
|
||||
}
|
||||
});
|
||||
|
||||
// Reserved bootstrap/credential keys are NEVER readable through the
|
||||
// generic settings reads — oidc_client_secret (#798) is stored encrypted
|
||||
// with setting_type 'string' and would otherwise leak its ciphertext to
|
||||
// any settings.view holder; setup_token is the first-run bootstrap secret.
|
||||
stripReservedSettingKeys(settingsObject);
|
||||
|
||||
// Mask sensitive secrets before sending to client
|
||||
if (settingsObject.security_recaptcha_secret_key) {
|
||||
settingsObject.security_recaptcha_secret_key = '••••••••';
|
||||
}
|
||||
// Backup credentials — the S3 secret key and the rsync SSH PRIVATE KEY
|
||||
// were returned in plaintext to any settings.view holder. Same masking
|
||||
// pattern as the recaptcha/umami/rybbit keys; the dedicated
|
||||
// /admin/backup/config endpoints handle the edit round-trip.
|
||||
if (settingsObject.backup_s3_secret_key) {
|
||||
settingsObject.backup_s3_secret_key = '••••••••';
|
||||
}
|
||||
if (settingsObject.backup_rsync_ssh_key) {
|
||||
settingsObject.backup_rsync_ssh_key = '••••••••';
|
||||
}
|
||||
// Umami v2 API key (#661 Bug C) — read-write secret that authenticates
|
||||
// outbound calls to the operator's Umami instance for the device
|
||||
// breakdown. Masked on GET, same pattern as the recaptcha secret.
|
||||
@@ -906,7 +1138,7 @@ router.put('/theme', adminAuth, requirePermission('settings.edit'), async (req,
|
||||
// Update general settings
|
||||
router.put('/general', adminAuth, requirePermission('settings.edit'), async (req, res) => {
|
||||
try {
|
||||
const settings = { ...req.body };
|
||||
const settings = stripReservedSettingKeys({ ...req.body });
|
||||
let uploadLimitTouched = false;
|
||||
|
||||
const publicSiteKeysTouched = Object.keys(settings).some((key) => key.startsWith('general_public_site_'));
|
||||
@@ -925,6 +1157,24 @@ router.put('/general', adminAuth, requirePermission('settings.edit'), async (req
|
||||
settings.general_max_files_per_upload = normalizedValue;
|
||||
}
|
||||
|
||||
// Per-file size limit (MB). Validate/clamp on save, mirroring the count
|
||||
// above, so an out-of-range value can't be persisted — otherwise the public
|
||||
// endpoint would advertise the raw value while getMaxFileSizeMb() normalizes
|
||||
// it, and the guest UI would reject files the backend actually accepts.
|
||||
if (Object.prototype.hasOwnProperty.call(settings, 'general_max_file_size_mb')) {
|
||||
uploadLimitTouched = true;
|
||||
const rawValue = Number(settings.general_max_file_size_mb);
|
||||
const normalizedValue = Number.isFinite(rawValue) ? Math.floor(rawValue) : NaN;
|
||||
|
||||
if (!Number.isInteger(normalizedValue) || normalizedValue < 1 || normalizedValue > MAX_ALLOWED_FILE_SIZE_MB) {
|
||||
return res.status(400).json({
|
||||
error: `general_max_file_size_mb must be an integer between 1 and ${MAX_ALLOWED_FILE_SIZE_MB}`
|
||||
});
|
||||
}
|
||||
|
||||
settings.general_max_file_size_mb = normalizedValue;
|
||||
}
|
||||
|
||||
if (publicSiteKeysTouched) {
|
||||
if (Object.prototype.hasOwnProperty.call(settings, 'general_public_site_custom_css')) {
|
||||
settings.general_public_site_custom_css = sanitizeCss(settings.general_public_site_custom_css || '');
|
||||
@@ -981,6 +1231,7 @@ router.put('/general', adminAuth, requirePermission('settings.edit'), async (req
|
||||
}
|
||||
if (uploadLimitTouched) {
|
||||
clearMaxFilesPerUploadCache();
|
||||
clearMaxFileSizeCache();
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(settings, 'general_short_gallery_urls')) {
|
||||
clearShareLinkSettingsCache();
|
||||
@@ -1017,7 +1268,7 @@ router.put('/general', adminAuth, requirePermission('settings.edit'), async (req
|
||||
// Update security settings
|
||||
router.put('/security', adminAuth, requirePermission('settings.edit'), async (req, res) => {
|
||||
try {
|
||||
const settings = req.body;
|
||||
const settings = stripReservedSettingKeys({ ...req.body });
|
||||
|
||||
// Update or insert each setting
|
||||
for (const [key, value] of Object.entries(settings)) {
|
||||
@@ -1055,7 +1306,7 @@ router.put('/security', adminAuth, requirePermission('settings.edit'), async (re
|
||||
// Update analytics settings
|
||||
router.put('/analytics', adminAuth, requirePermission('settings.edit'), async (req, res) => {
|
||||
try {
|
||||
const settings = req.body;
|
||||
const settings = stripReservedSettingKeys({ ...req.body });
|
||||
|
||||
// Validate the provider switch (#663 Phase 1). Reject unknown values
|
||||
// so the dashboard route's factory doesn't have to defensively guard.
|
||||
@@ -1110,7 +1361,7 @@ router.put('/analytics', adminAuth, requirePermission('settings.edit'), async (r
|
||||
// Update SEO settings
|
||||
router.put('/seo', adminAuth, requirePermission('settings.edit'), async (req, res) => {
|
||||
try {
|
||||
const settings = req.body;
|
||||
const settings = stripReservedSettingKeys({ ...req.body });
|
||||
|
||||
// Validate seo_blocked_ai_agents is an array of strings
|
||||
if (settings.seo_blocked_ai_agents !== undefined) {
|
||||
|
||||
@@ -10,39 +10,9 @@ const { requirePermission, requireSuperAdmin, getUserPermissions } = require('..
|
||||
const { handleAsync, validateRequest, successResponse } = require('../utils/routeHelpers');
|
||||
const userManagementService = require('../services/userManagementService');
|
||||
const { IDENTITY_PRESERVING_NORMALIZE_EMAIL } = require('../utils/emailNormalization');
|
||||
const { toIso } = require('../utils/dateNormalize');
|
||||
const router = express.Router();
|
||||
|
||||
/**
|
||||
* Coerce any of the shapes a TIMESTAMP column produces across our
|
||||
* supported drivers into a single ISO 8601 string the frontend (and
|
||||
* any external API consumer) can safely pass to date-fns / new Date.
|
||||
*
|
||||
* Postgres → Date object (becomes ISO via JSON.stringify anyway, but
|
||||
* pinning the format defends against driver-side surprises).
|
||||
* SQLite → integer milliseconds since epoch (the surface that crashed
|
||||
* the admin Users page in #485 — `parseISO(123456789)` blows up
|
||||
* with "e.split is not a function"). Native installs default to
|
||||
* SQLite, so this path matters every release.
|
||||
* Already a string → assume it's a parseable ISO/RFC3339 (Postgres
|
||||
* driver may stringify under JSON serialization mid-pipeline).
|
||||
*
|
||||
* Returns null/undefined unchanged so an unset last_login surfaces as
|
||||
* "Never" in the UI rather than 1970-01-01T00:00:00Z.
|
||||
*/
|
||||
function toIso(value) {
|
||||
if (value === null || value === undefined || value === '') return value;
|
||||
if (value instanceof Date) return value.toISOString();
|
||||
if (typeof value === 'number') return new Date(value).toISOString();
|
||||
if (typeof value === 'string') {
|
||||
// Numeric-as-string ("1778752458666") happens when the SQLite
|
||||
// driver stringifies large integers — re-coerce so the frontend
|
||||
// doesn't try to parseISO('1778752458666').
|
||||
if (/^\d{10,}$/.test(value)) return new Date(Number(value)).toISOString();
|
||||
return value;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform user object from snake_case (DB) to camelCase (API)
|
||||
*/
|
||||
|
||||
+214
-20
@@ -28,6 +28,7 @@ const {
|
||||
} = require('../utils/tokenUtils');
|
||||
const { getEventShareToken, resolveShareIdentifier } = require('../services/shareLinkService');
|
||||
const { getClientIp } = require('../utils/requestIp');
|
||||
const { sanitizePasswordInput } = require('../utils/passwordInput');
|
||||
const {
|
||||
validatePasswordInContext,
|
||||
getBcryptRounds,
|
||||
@@ -42,9 +43,20 @@ const router = express.Router();
|
||||
* both produce an identical session. `lockoutKey` is the identifier the user
|
||||
* typed (username or email) so success/failure tracking stays in one bucket.
|
||||
*/
|
||||
async function completeAdminLogin(req, res, admin, ipAddress, userAgent, lockoutKey) {
|
||||
async function establishAdminSession(res, admin, ipAddress, userAgent, lockoutKey) {
|
||||
await trackSuccessfulLogin(lockoutKey, ipAddress, userAgent);
|
||||
|
||||
// A normal login means the first-run wizard is over — the wizard never hits
|
||||
// this route (setup sets its cookie directly). Close the system-event-type
|
||||
// deletion window durably even when the wizard was abandoned mid-way (#800).
|
||||
// Best-effort: a failure here must never block a login.
|
||||
try {
|
||||
const setupService = require('../services/setupService');
|
||||
if (!(await setupService.isSetupWizardCompleted())) {
|
||||
await setupService.markSetupWizardCompleted();
|
||||
}
|
||||
} catch (_) { /* best-effort */ }
|
||||
|
||||
await db('admin_users').where('id', admin.id).update({
|
||||
last_login: new Date(),
|
||||
last_login_ip: ipAddress
|
||||
@@ -64,18 +76,21 @@ async function completeAdminLogin(req, res, admin, ipAddress, userAgent, lockout
|
||||
|
||||
setAdminAuthCookie(res, token);
|
||||
|
||||
return res.json({
|
||||
user: {
|
||||
id: admin.id,
|
||||
username: admin.username,
|
||||
email: admin.email,
|
||||
mustChangePassword: admin.must_change_password || false,
|
||||
role: admin.role_name ? {
|
||||
name: admin.role_name,
|
||||
displayName: admin.role_display_name
|
||||
} : null
|
||||
}
|
||||
});
|
||||
return {
|
||||
id: admin.id,
|
||||
username: admin.username,
|
||||
email: admin.email,
|
||||
mustChangePassword: admin.must_change_password || false,
|
||||
role: admin.role_name ? {
|
||||
name: admin.role_name,
|
||||
displayName: admin.role_display_name
|
||||
} : null
|
||||
};
|
||||
}
|
||||
|
||||
async function completeAdminLogin(req, res, admin, ipAddress, userAgent, lockoutKey) {
|
||||
const user = await establishAdminSession(res, admin, ipAddress, userAgent, lockoutKey);
|
||||
return res.json({ user });
|
||||
}
|
||||
|
||||
// Admin login with enhanced security
|
||||
@@ -92,7 +107,15 @@ router.post('/admin/login', [
|
||||
const { username, password, recaptchaToken } = req.body;
|
||||
const ipAddress = getClientIp(req);
|
||||
const userAgent = req.headers['user-agent'] || '';
|
||||
|
||||
|
||||
// SSO login policy (#798 phase 2): refuse the password path before any
|
||||
// credential/lockout work while oidc_disable_local_login is effective.
|
||||
// OIDC_BREAK_GLASS=true (checked inside) always re-opens local login.
|
||||
if (await require('../services/oidcService').isLocalLoginDisabled()) {
|
||||
logger.warn('Local admin login refused — disabled by SSO policy', { username, ipAddress });
|
||||
return res.status(403).json({ error: 'Local login is disabled — sign in through SSO', code: 'LOCAL_LOGIN_DISABLED' });
|
||||
}
|
||||
|
||||
// Check account lockout first
|
||||
const lockoutStatus = await checkAccountLockout(username);
|
||||
if (lockoutStatus.isLocked) {
|
||||
@@ -129,8 +152,11 @@ router.post('/admin/login', [
|
||||
)
|
||||
.first();
|
||||
|
||||
// Use generic error to prevent user enumeration
|
||||
if (!admin || !await bcrypt.compare(password, admin.password_hash)) {
|
||||
// Use generic error to prevent user enumeration. OIDC-owned accounts
|
||||
// (#798) never authenticate locally — their random hash is unusable by
|
||||
// design, and the explicit check keeps that true even if a hash ever
|
||||
// gets set through some other path.
|
||||
if (!admin || admin.auth_provider === 'oidc' || !await bcrypt.compare(password, admin.password_hash)) {
|
||||
await trackFailedAttempt(username, ipAddress, userAgent);
|
||||
return res.status(401).json({ error: getGenericAuthError() });
|
||||
}
|
||||
@@ -181,6 +207,14 @@ router.post('/admin/login/mfa', [
|
||||
const ipAddress = getClientIp(req);
|
||||
const userAgent = req.headers['user-agent'] || '';
|
||||
|
||||
// Same SSO policy gate as /admin/login (#798 phase 2): an mfa_pending
|
||||
// token minted moments before the policy flipped must not complete into
|
||||
// a local session through this second step.
|
||||
if (await require('../services/oidcService').isLocalLoginDisabled()) {
|
||||
logger.warn('Local admin MFA completion refused — disabled by SSO policy', { ipAddress });
|
||||
return res.status(403).json({ error: 'Local login is disabled — sign in through SSO', code: 'LOCAL_LOGIN_DISABLED' });
|
||||
}
|
||||
|
||||
let decoded;
|
||||
try {
|
||||
decoded = jwt.verify(mfaToken, process.env.JWT_SECRET, {
|
||||
@@ -355,7 +389,19 @@ router.post('/gallery/verify', [
|
||||
return res.status(401).json({ error: 'Invalid gallery or password' });
|
||||
}
|
||||
|
||||
const validPassword = await bcrypt.compare(password, event.password_hash);
|
||||
let validPassword = await bcrypt.compare(password, event.password_hash);
|
||||
if (!validPassword) {
|
||||
// Passwords copy-pasted out of chat apps carry invisible Unicode
|
||||
// that fails the byte-exact compare (#654). Retry the compare with
|
||||
// those characters stripped — in the SAME request, so the fallback
|
||||
// costs no reCAPTCHA token and no failed-attempt quota. Exact bytes
|
||||
// are tried first so stored passwords that legitimately contain
|
||||
// such characters keep working.
|
||||
const sanitized = sanitizePasswordInput(password);
|
||||
if (sanitized !== password) {
|
||||
validPassword = await bcrypt.compare(sanitized, event.password_hash);
|
||||
}
|
||||
}
|
||||
if (!validPassword) {
|
||||
await trackFailedAttempt(`gallery:${slug}`, ipAddress, userAgent);
|
||||
await db('access_logs').insert({
|
||||
@@ -650,12 +696,22 @@ router.get('/session', async (req, res) => {
|
||||
// or the gallery event was archived/deleted. Mirror those checks
|
||||
// here so the session endpoint is always at least as strict as
|
||||
// what the protected endpoints will enforce next.
|
||||
// Full user payload for admin sessions — the SSO callback establishes
|
||||
// the session via redirect (no JSON response the SPA could store), so
|
||||
// session restoration must be able to hydrate the user object (#798).
|
||||
let adminUser = null;
|
||||
|
||||
if (decoded.type === 'admin') {
|
||||
let admin = null;
|
||||
try {
|
||||
admin = await db('admin_users')
|
||||
.where({ id: decoded.id, is_active: formatBoolean(true) })
|
||||
.select('id', 'username', 'email', 'password_changed_at')
|
||||
.leftJoin('roles', 'roles.id', 'admin_users.role_id')
|
||||
.where({ 'admin_users.id': decoded.id, 'admin_users.is_active': formatBoolean(true) })
|
||||
.select(
|
||||
'admin_users.id', 'admin_users.username', 'admin_users.email',
|
||||
'admin_users.password_changed_at', 'admin_users.must_change_password',
|
||||
'roles.name as role_name', 'roles.display_name as role_display_name'
|
||||
)
|
||||
.first();
|
||||
} catch (lookupErr) {
|
||||
// admin_users table not present (test fixture, fresh DB) — fall
|
||||
@@ -694,6 +750,19 @@ router.get('/session', async (req, res) => {
|
||||
// Helper lookup failed (test stub may not export it) — fall through
|
||||
// and trust the token. Real deployments always have the middleware.
|
||||
}
|
||||
|
||||
if (admin) {
|
||||
adminUser = {
|
||||
id: admin.id,
|
||||
username: admin.username,
|
||||
email: admin.email,
|
||||
mustChangePassword: admin.must_change_password || false,
|
||||
role: admin.role_name ? {
|
||||
name: admin.role_name,
|
||||
displayName: admin.role_display_name
|
||||
} : null
|
||||
};
|
||||
}
|
||||
} else if (decoded.type === 'gallery') {
|
||||
try {
|
||||
const event = await db('events')
|
||||
@@ -725,7 +794,11 @@ router.get('/session', async (req, res) => {
|
||||
expiresIn: Math.floor(remainingTime),
|
||||
user: decoded.username || decoded.eventSlug,
|
||||
eventSlug: decoded.eventSlug,
|
||||
adminUsername: decoded.username
|
||||
adminUsername: decoded.username,
|
||||
// Full admin payload (or null) — lets the SPA hydrate its user
|
||||
// state after a redirect-established session (SSO, #798) where no
|
||||
// login JSON response ever reached it.
|
||||
adminUser
|
||||
});
|
||||
} catch (err) {
|
||||
res.json({
|
||||
@@ -847,4 +920,125 @@ router.post('/password-strength', [
|
||||
}
|
||||
});
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
// OIDC SSO for admins (#798, phase 1)
|
||||
//
|
||||
// Authorization-code + PKCE. The per-request secrets (state, nonce, PKCE
|
||||
// verifier) cross the IdP redirect in a short-lived signed cookie —
|
||||
// httpOnly, SameSite=Lax (the IdP returns via a top-level GET, which Lax
|
||||
// permits), scoped to this route prefix. Token/claim validation happens in
|
||||
// oidcService via openid-client; a successful callback reuses the exact
|
||||
// session establishment of the local login, so an SSO session is
|
||||
// indistinguishable from a password one downstream. MFA is the IdP's job on
|
||||
// this path — local TOTP guards the password flow SSO users don't take.
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const OIDC_STATE_COOKIE = 'oidc_state';
|
||||
|
||||
function oidcStateCookieOptions(req) {
|
||||
return {
|
||||
httpOnly: true,
|
||||
secure: Boolean(req.secure),
|
||||
sameSite: 'Lax',
|
||||
path: '/api/auth/admin/sso',
|
||||
maxAge: 10 * 60 * 1000,
|
||||
};
|
||||
}
|
||||
|
||||
// Kick off the IdP round-trip. 404 when SSO is off so the endpoint is
|
||||
// invisible on non-SSO installs.
|
||||
router.get('/admin/sso/login', async (req, res) => {
|
||||
const oidcService = require('../services/oidcService');
|
||||
try {
|
||||
const { url, state, nonce, codeVerifier } = await oidcService.buildAuthorizationRequest();
|
||||
const stash = jwt.sign(
|
||||
{ type: 'oidc_state', s: state, n: nonce, cv: codeVerifier },
|
||||
process.env.JWT_SECRET,
|
||||
{ expiresIn: '10m', issuer: 'picpeak-auth' }
|
||||
);
|
||||
res.cookie(OIDC_STATE_COOKIE, stash, oidcStateCookieOptions(req));
|
||||
return res.redirect(url);
|
||||
} catch (error) {
|
||||
if (error.code === 'OIDC_NOT_CONFIGURED') {
|
||||
return res.status(404).json({ error: 'SSO is not enabled' });
|
||||
}
|
||||
logger.error('OIDC login initiation failed', { error: error.message });
|
||||
// Absolute like the callback's redirects: in split-origin deployments a
|
||||
// relative path would resolve on the API origin and 404.
|
||||
const { getFrontendBaseUrl } = require('../utils/frontendUrl');
|
||||
const frontendBase = (await getFrontendBaseUrl().catch(() => '')) || '';
|
||||
return res.redirect(`${frontendBase}/admin/login?sso_error=config`);
|
||||
}
|
||||
});
|
||||
|
||||
// IdP redirect target. Every failure lands back on the login page with a
|
||||
// translatable error key — never a raw error, never a broken JSON screen.
|
||||
// Final redirects are ABSOLUTE to the frontend base: in split-origin
|
||||
// deployments (absolute VITE_API_URL / API_URL) this callback runs on the
|
||||
// API origin, where a relative /admin/login would 404.
|
||||
router.get('/admin/sso/callback', async (req, res) => {
|
||||
const oidcService = require('../services/oidcService');
|
||||
const { getFrontendBaseUrl } = require('../utils/frontendUrl');
|
||||
const frontendBase = (await getFrontendBaseUrl().catch(() => '')) || '';
|
||||
const fail = (key) => res.redirect(`${frontendBase}/admin/login?sso_error=${key}`);
|
||||
|
||||
const stashCookie = req.cookies?.[OIDC_STATE_COOKIE];
|
||||
res.clearCookie(OIDC_STATE_COOKIE, { ...oidcStateCookieOptions(req), maxAge: undefined });
|
||||
if (!stashCookie) return fail('state');
|
||||
|
||||
let stash;
|
||||
try {
|
||||
stash = jwt.verify(stashCookie, process.env.JWT_SECRET, { issuer: 'picpeak-auth' });
|
||||
if (stash.type !== 'oidc_state') throw new Error('wrong token type');
|
||||
} catch (_) {
|
||||
return fail('state');
|
||||
}
|
||||
|
||||
try {
|
||||
// Reconstruct the exact redirect URI + the IdP's query for validation.
|
||||
const callbackUrl = new URL(await oidcService.getRedirectUri());
|
||||
callbackUrl.search = req.originalUrl.split('?')[1] || '';
|
||||
|
||||
const claims = await oidcService.handleCallback(callbackUrl.href, {
|
||||
state: stash.s,
|
||||
nonce: stash.n,
|
||||
codeVerifier: stash.cv,
|
||||
});
|
||||
|
||||
const resolved = await oidcService.resolveAdminFromClaims(claims);
|
||||
|
||||
// Reload with role info so the session payload matches a local login.
|
||||
const admin = await db('admin_users')
|
||||
.leftJoin('roles', 'roles.id', 'admin_users.role_id')
|
||||
.where('admin_users.id', resolved.id)
|
||||
.select('admin_users.*', 'roles.name as role_name', 'roles.display_name as role_display_name')
|
||||
.first();
|
||||
|
||||
const ipAddress = getClientIp(req);
|
||||
const userAgent = req.headers['user-agent'] || '';
|
||||
await establishAdminSession(res, admin, ipAddress, userAgent, admin.username);
|
||||
|
||||
await logActivity('admin_sso_login', { provider: 'oidc' }, null, {
|
||||
type: 'admin', id: admin.id, name: admin.username,
|
||||
});
|
||||
|
||||
return res.redirect(`${frontendBase}/admin/dashboard`);
|
||||
} catch (error) {
|
||||
const codeMap = {
|
||||
OIDC_NOT_CONFIGURED: 'config',
|
||||
OIDC_BAD_CONFIG: 'config',
|
||||
OIDC_INACTIVE: 'inactive',
|
||||
OIDC_NOT_PROVISIONED: 'not_provisioned',
|
||||
OIDC_NO_EMAIL: 'no_email',
|
||||
OIDC_NO_ROLE: 'no_role',
|
||||
OIDC_BAD_CLAIMS: 'idp',
|
||||
};
|
||||
const key = codeMap[error.code] || 'idp';
|
||||
// 'idp' covers token-exchange/validation failures from openid-client
|
||||
// (bad state/nonce, signature, issuer mismatch, IdP-side errors).
|
||||
logger.warn('OIDC callback failed', { error: error.message, key });
|
||||
return fail(key);
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
||||
+288
-23
@@ -1,6 +1,6 @@
|
||||
const express = require('express');
|
||||
const jwt = require('jsonwebtoken');
|
||||
const { db } = require('../database/db');
|
||||
const { db, logActivity } = require('../database/db');
|
||||
const { formatBoolean } = require('../utils/dbCompat');
|
||||
const { getAppSetting } = require('../utils/appSettings');
|
||||
const archiver = require('archiver');
|
||||
@@ -25,8 +25,11 @@ const { generateGuestIdentifier } = require('../middleware/feedbackRateLimit');
|
||||
const secureImageService = require('../services/secureImageService');
|
||||
const logger = require('../utils/logger');
|
||||
const { resolvePhotoFilePath } = require('../services/photoResolver');
|
||||
const { getEventCategoriesOrdered } = require('../utils/categoryOrder');
|
||||
const { getEventShareToken, resolveShareIdentifier, buildShareLinkVariants } = require('../services/shareLinkService');
|
||||
const { handleAsync, errorResponse } = require('../utils/routeHelpers');
|
||||
const { isGalleryHidden, guestBlockedByReveal, blockHiddenGallery } = require('../utils/revealMode');
|
||||
const { toIso } = require('../utils/dateNormalize');
|
||||
const { NotFoundError } = require('../utils/errors');
|
||||
const { ensureThumbnail, ensureHeroImage, ensurePreviewImage, withLocalCopy } = require('../services/imageProcessor');
|
||||
const downloadZipService = require('../services/downloadZipService');
|
||||
@@ -37,6 +40,24 @@ const {
|
||||
} = require('../services/downloadFilenameService');
|
||||
const { buildContentDisposition } = require('../utils/filenameSanitizer');
|
||||
const { getStorage } = require('../services/storage');
|
||||
|
||||
// Formats whose ORIGINAL bytes a browser can't render in an <img> (HEIC/HEIF,
|
||||
// camera RAW/DNG). For these the lightbox must be served the generated JPEG
|
||||
// preview instead of `url` (the original) — otherwise it shows a broken image.
|
||||
// So we force `preview_url` for them regardless of the lightbox_preview_enabled
|
||||
// toggle. Detection is by MIME first, extension as a fallback (browsers report
|
||||
// these MIMEs inconsistently). EXPERIMENTAL: whether a preview actually renders
|
||||
// still depends on the backend being able to decode the source (HEVC-in-HEIC on
|
||||
// the prod image; exiftool for DNG) — see #821.
|
||||
const NON_DISPLAYABLE_ORIGINAL_EXT = new Set(['heic', 'heif', 'dng']);
|
||||
const NON_DISPLAYABLE_ORIGINAL_MIME = new Set(['image/heic', 'image/heif', 'image/x-adobe-dng']);
|
||||
function originalNeedsPreview(photo) {
|
||||
const mime = (photo.mime_type || '').toLowerCase();
|
||||
if (NON_DISPLAYABLE_ORIGINAL_MIME.has(mime)) return true;
|
||||
const name = photo.original_filename || photo.filename || '';
|
||||
const ext = name.includes('.') ? name.split('.').pop().toLowerCase() : '';
|
||||
return NON_DISPLAYABLE_ORIGINAL_EXT.has(ext);
|
||||
}
|
||||
const { setGalleryAuthCookies } = require('../utils/tokenUtils');
|
||||
// Read globals from app_settings (the real table) — settingsService.getSetting
|
||||
// queries a non-existent `settings` table and throws.
|
||||
@@ -47,6 +68,54 @@ const fs = require('fs');
|
||||
// Get storage path from environment or default
|
||||
const getStoragePath = () => process.env.STORAGE_PATH || path.join(__dirname, '../../../storage');
|
||||
|
||||
// "Gallery opened" for the admin notification bell (#746). The photo-list
|
||||
// endpoint fires on every gallery page load, so notifying per hit would spam
|
||||
// the bell — debounce to at most one notification per event per window. The
|
||||
// map is in-memory on purpose: losing it on restart merely allows one extra
|
||||
// notification, and it costs the hot view path zero DB reads.
|
||||
const GALLERY_OPENED_DEBOUNCE_MS = 6 * 60 * 60 * 1000; // 6h
|
||||
const galleryOpenedNotifiedAt = new Map();
|
||||
// #746 covers CLIENT activity too — attribute the actor from the session
|
||||
// instead of hard-coding 'guest', so a customer opening from the portal
|
||||
// isn't mislabeled (codex review of #849 round 3).
|
||||
function galleryActor(req) {
|
||||
// Portal tokens run as accessLevel 'guest' but carry via:'customer'
|
||||
// (req.viaCustomer); PIN-client logins carry accessLevel 'client'.
|
||||
// Both are customers, not guests (codex review of #849, final round).
|
||||
const isCustomer = !!(req && (req.viaCustomer || req.accessLevel === 'client'));
|
||||
return { type: isCustomer ? 'customer' : 'guest' };
|
||||
}
|
||||
function notifyGalleryOpened(event, req) {
|
||||
// Customer-PORTAL opens already log `customer_event_access` on the
|
||||
// access-token mint — a second `gallery_opened` per portal click would
|
||||
// double-notify. Keyed on the portal provenance (req.viaCustomer), NOT
|
||||
// on accessLevel: PIN-client logins are 'client' without any other
|
||||
// open signal and must keep notifying (codex review of #849, final
|
||||
// round — the previous check had this inverted).
|
||||
if (req && req.viaCustomer) return;
|
||||
const now = Date.now();
|
||||
const last = galleryOpenedNotifiedAt.get(event.id) || 0;
|
||||
if (now - last < GALLERY_OPENED_DEBOUNCE_MS) return;
|
||||
galleryOpenedNotifiedAt.set(event.id, now);
|
||||
// Fire-and-forget — logActivity swallows its own errors.
|
||||
logActivity('gallery_opened', {}, event.id, galleryActor(req));
|
||||
}
|
||||
|
||||
// Single-photo saves are frequent (a guest saving 30 photos = 30 route
|
||||
// hits) — debounce like gallery_opened so the bell gets one "guest is
|
||||
// downloading photos" signal per event per window instead of a flood
|
||||
// (codex review of #849). ZIP downloads stay un-debounced: rare, high
|
||||
// signal. Exact per-photo counts remain in access_logs/analytics.
|
||||
const SINGLE_DOWNLOAD_DEBOUNCE_MS = 60 * 60 * 1000; // 1h
|
||||
const singleDownloadNotifiedAt = new Map();
|
||||
function notifySinglePhotoDownload(event, req) {
|
||||
const now = Date.now();
|
||||
const last = singleDownloadNotifiedAt.get(event.id) || 0;
|
||||
if (now - last < SINGLE_DOWNLOAD_DEBOUNCE_MS) return;
|
||||
singleDownloadNotifiedAt.set(event.id, now);
|
||||
logActivity('gallery_downloaded', { scope: 'single' }, event.id, galleryActor(req));
|
||||
}
|
||||
|
||||
// Check for slug redirect (for renamed events)
|
||||
async function checkSlugRedirect(slug) {
|
||||
try {
|
||||
@@ -138,6 +207,9 @@ router.get('/:slug/info', async (req, res) => {
|
||||
'share_token',
|
||||
'allow_downloads',
|
||||
'allow_user_uploads',
|
||||
'reveal_mode',
|
||||
'reveal_at',
|
||||
'revealed_at',
|
||||
'disable_right_click',
|
||||
'watermark_downloads',
|
||||
'watermark_text',
|
||||
@@ -208,6 +280,10 @@ router.get('/:slug/info', async (req, res) => {
|
||||
color_theme: event.color_theme,
|
||||
allow_downloads: !(event.allow_downloads === false || event.allow_downloads === 0 || event.allow_downloads === '0'),
|
||||
allow_user_uploads: event.allow_user_uploads === true || event.allow_user_uploads === 1 || event.allow_user_uploads === '1',
|
||||
// Reveal mode (#838): effective hidden state (computed, time-exact) so
|
||||
// the landing page can hint at the reveal before login too.
|
||||
hidden_until_reveal: isGalleryHidden(event),
|
||||
reveal_at: isGalleryHidden(event) ? (event.reveal_at || null) : null,
|
||||
disable_right_click: event.disable_right_click === true || event.disable_right_click === 1 || event.disable_right_click === '1',
|
||||
watermark_downloads: event.watermark_downloads === true || event.watermark_downloads === 1 || event.watermark_downloads === '1',
|
||||
watermark_text: event.watermark_text,
|
||||
@@ -243,8 +319,8 @@ router.get('/:slug/info', async (req, res) => {
|
||||
|
||||
// Photos a slideshow may display: published, finished, non-hidden. Mirrors the
|
||||
// guest filter in GET /:slug/photos so the live count matches the rendered set.
|
||||
function slideshowPhotosQuery(eventId) {
|
||||
return db('photos')
|
||||
function slideshowPhotosQuery(eventId, categoryId = null) {
|
||||
const q = db('photos')
|
||||
.where('photos.event_id', eventId)
|
||||
.where(function() {
|
||||
this.where('photos.processing_status', 'complete').orWhereNull('photos.processing_status');
|
||||
@@ -252,6 +328,10 @@ function slideshowPhotosQuery(eventId) {
|
||||
.where(function() {
|
||||
this.where('photos.visibility', 'visible').orWhereNull('photos.visibility');
|
||||
});
|
||||
// Category filter (#202) — keep the /session + /state count in sync with the
|
||||
// photos the kiosk actually renders.
|
||||
if (categoryId) q.where('photos.category_id', categoryId);
|
||||
return q;
|
||||
}
|
||||
|
||||
// Resolve an active slideshow by slug + token. Returns the event row, or null
|
||||
@@ -282,7 +362,7 @@ async function resolveSlideshow(slug, token) {
|
||||
// watermark (a white, semi-transparent corner logo). The logo URL is resolved
|
||||
// from the chosen source so the kiosk renders it without knowing about
|
||||
// branding/event internals; null url = nothing to overlay.
|
||||
async function slideshowSettings(event) {
|
||||
async function slideshowSettings(event, req) {
|
||||
// The global look/fit (Settings → Slideshow) + branding logo URLs come from a
|
||||
// short-TTL cached bundle so a 3s projector poll doesn't re-fire ~10 settings
|
||||
// reads each time (PR #646 review, concern 2).
|
||||
@@ -319,16 +399,123 @@ async function slideshowSettings(event) {
|
||||
};
|
||||
}
|
||||
}
|
||||
// QR overlay (#837): like the watermark, the LOOK is global-only and the
|
||||
// per-event `show_qr` tri-state (NULL = inherit) decides visibility. The QR
|
||||
// encodes the gallery share URL and ships as a data URI so the public
|
||||
// slideshow client needs no QR library and no extra authenticated endpoint.
|
||||
const qrOverride = event.show_qr;
|
||||
const qrInherit = (qrOverride === null || qrOverride === undefined);
|
||||
const qrEnabled = qrInherit ? g.qr_enabled : (qrOverride === true || qrOverride === 1 || qrOverride === '1');
|
||||
let qr = null;
|
||||
if (qrEnabled) {
|
||||
const dataUrl = await slideshowQrDataUrl(event, req);
|
||||
if (dataUrl) {
|
||||
qr = {
|
||||
data_url: dataUrl,
|
||||
position: g.qr_position,
|
||||
opacity: g.qr_opacity,
|
||||
size: g.qr_size,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
interval_ms: event.show_interval_ms || 5000,
|
||||
transition: event.show_transition || 'crossfade',
|
||||
transition_ms: event.show_transition_ms || 800,
|
||||
colorfilter: event.show_colorfilter || 'none',
|
||||
// Play order (#202): 'chronological' | 'random'. The client shuffles when
|
||||
// 'random' so live-appended uploads keep working.
|
||||
order: event.show_order || 'chronological',
|
||||
fit: g.fit,
|
||||
watermark,
|
||||
qr,
|
||||
};
|
||||
}
|
||||
|
||||
// The state endpoint is polled every ~3s per projector — cache the generated
|
||||
// QR data URI per share URL instead of re-encoding on every poll. Bounded:
|
||||
// entries live for past events / rotated tokens too, so without eviction the
|
||||
// map would grow with every share URL ever displayed (codex review of #848).
|
||||
// Insertion-order eviction is enough — concurrently-shown events stay hot.
|
||||
const SLIDESHOW_QR_CACHE_MAX = 50;
|
||||
// Keyed by event id (NOT by URL): the origin is caller-influenced when the
|
||||
// configured base is loopback, so URL-keyed caching would let a slideshow
|
||||
// -link holder force a fresh QRCode.toDataURL per request with unique
|
||||
// origins — a cheap CPU-exhaustion path (codex review of #848,
|
||||
// confirmation round). Per-event entries + a regeneration throttle bound
|
||||
// the encode rate regardless of what the caller sends.
|
||||
const SLIDESHOW_QR_REGEN_MS = 60_000;
|
||||
const slideshowQrCache = new Map(); // eventId -> { url, dataUrl, at }
|
||||
// Localhost/relative guard (codex review of #848): with the compose-default
|
||||
// FRONTEND_URL=http://localhost:3000 (or none configured) the QR would send
|
||||
// scanning phones to THEIR localhost. The state poll comes from the kiosk
|
||||
// browser itself, so its Host header + protocol are exactly the public
|
||||
// origin guests can reach — prefer that whenever the configured base is
|
||||
// missing or loopback. trust proxy is configured, so req.protocol respects
|
||||
// X-Forwarded-Proto behind the standard reverse-proxy setups.
|
||||
const QR_LOCAL_BASE_RE = /^https?:\/\/(localhost|127\.|0\.0\.0\.0|\[::1\])/i;
|
||||
const QR_ORIGIN_RE = /^https?:\/\/[^\s/]+$/i;
|
||||
async function slideshowQrDataUrl(event, req) {
|
||||
try {
|
||||
const shareToken = getEventShareToken(event);
|
||||
if (!shareToken) return null;
|
||||
let { shareUrl, sharePath } = await buildShareLinkVariants({ slug: event.slug, shareToken });
|
||||
if (!/^https?:\/\//i.test(shareUrl) || QR_LOCAL_BASE_RE.test(shareUrl)) {
|
||||
// Prefer the kiosk's own window.location.origin (?origin=, validated):
|
||||
// req.get('host') is NOT the browser origin behind the standard
|
||||
// proxies — frontend/nginx.conf forwards $host (port stripped), so a
|
||||
// compose LAN deployment on :3000 would encode port 80. A LOOPBACK
|
||||
// kiosk origin is rejected too: it is no more guest-reachable than
|
||||
// the loopback base it would replace (codex review of #848).
|
||||
const rawOrigin = req?.query?.origin;
|
||||
const queryOrigin = typeof rawOrigin === 'string' && QR_ORIGIN_RE.test(rawOrigin) && !QR_LOCAL_BASE_RE.test(rawOrigin)
|
||||
? rawOrigin.replace(/\/$/, '')
|
||||
: null;
|
||||
const host = req && req.get ? req.get('host') : null;
|
||||
const hostOrigin = host ? `${req.protocol}://${host}` : null;
|
||||
if (queryOrigin) shareUrl = `${queryOrigin}${sharePath}`;
|
||||
else if (hostOrigin && !QR_LOCAL_BASE_RE.test(hostOrigin)) shareUrl = `${hostOrigin}${sharePath}`;
|
||||
// Still loopback/relative → no reachable URL exists; suppress the
|
||||
// overlay rather than encode a QR that sends phones to localhost.
|
||||
else return null;
|
||||
}
|
||||
|
||||
const cached = slideshowQrCache.get(event.id);
|
||||
if (cached && cached.url === shareUrl) return cached.dataUrl;
|
||||
// URL differs from the cached one: NEVER serve the mismatched artifact —
|
||||
// a slideshow-token holder could otherwise poison the projector's QR
|
||||
// with an attacker origin for a whole throttle window (codex review of
|
||||
// #848, final round). Inside the window the overlay is briefly
|
||||
// suppressed instead; regeneration stays bounded per event.
|
||||
if (cached && Date.now() - cached.at < SLIDESHOW_QR_REGEN_MS) {
|
||||
return cached.pending ? cached.dataUrl : null;
|
||||
}
|
||||
// Single-flight: concurrent polls on a cold cache must not each
|
||||
// schedule their own 512px encode — reserve the entry with a shared
|
||||
// promise before awaiting.
|
||||
if (cached && cached.pending && cached.url === shareUrl) return cached.pending;
|
||||
const QRCode = require('qrcode');
|
||||
const entry = { url: shareUrl, dataUrl: null, at: Date.now(), pending: null };
|
||||
entry.pending = QRCode.toDataURL(shareUrl, { width: 512, margin: 4 }).then((dataUrl) => {
|
||||
entry.dataUrl = dataUrl;
|
||||
entry.pending = null;
|
||||
return dataUrl;
|
||||
}).catch((e) => {
|
||||
slideshowQrCache.delete(event.id);
|
||||
throw e;
|
||||
});
|
||||
if (!slideshowQrCache.has(event.id) && slideshowQrCache.size >= SLIDESHOW_QR_CACHE_MAX) {
|
||||
slideshowQrCache.delete(slideshowQrCache.keys().next().value);
|
||||
}
|
||||
slideshowQrCache.set(event.id, entry);
|
||||
return await entry.pending;
|
||||
} catch (e) {
|
||||
logger.error('Slideshow QR generation failed:', e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Open a slideshow session: validate the token and mint a short-lived gallery
|
||||
// JWT scoped to `accessLevel:'slideshow'` (treated as a guest by the photo /
|
||||
// image endpoints → visible photos only, no client-only/hidden). The page
|
||||
@@ -356,7 +543,7 @@ router.get('/:slug/show/:token/session', handleAsync(async (req, res) => {
|
||||
// here so the kiosk's image requests are authorized with zero extra wiring.
|
||||
setGalleryAuthCookies(res, sessionToken, event.slug);
|
||||
|
||||
const [{ count }] = await slideshowPhotosQuery(event.id).count('* as count');
|
||||
const [{ count }] = await slideshowPhotosQuery(event.id, event.show_category_id).count('* as count');
|
||||
|
||||
res.json({
|
||||
token: sessionToken,
|
||||
@@ -365,7 +552,7 @@ router.get('/:slug/show/:token/session', handleAsync(async (req, res) => {
|
||||
event_type: event.event_type,
|
||||
color_theme: event.color_theme
|
||||
},
|
||||
settings: await slideshowSettings(event),
|
||||
settings: await slideshowSettings(event, req),
|
||||
photo_count: parseInt(count, 10) || 0,
|
||||
expires_at: event.expires_at || null
|
||||
});
|
||||
@@ -382,10 +569,10 @@ router.get('/:slug/show/:token/state', handleAsync(async (req, res) => {
|
||||
throw new NotFoundError('Slideshow');
|
||||
}
|
||||
|
||||
const [{ count }] = await slideshowPhotosQuery(event.id).count('* as count');
|
||||
const [{ count }] = await slideshowPhotosQuery(event.id, event.show_category_id).count('* as count');
|
||||
|
||||
res.json({
|
||||
...(await slideshowSettings(event)),
|
||||
...(await slideshowSettings(event, req)),
|
||||
photo_count: parseInt(count, 10) || 0,
|
||||
expires_at: event.expires_at || null
|
||||
});
|
||||
@@ -426,6 +613,13 @@ router.get('/:slug/photos', verifyGalleryAccess, resolveGuest, async (req, res)
|
||||
});
|
||||
}
|
||||
|
||||
// Live Slideshow category filter (#202). Enforced server-side so the kiosk
|
||||
// viewer can't widen the set: when the event pins show_category_id, the
|
||||
// slideshow only sees that category. NULL = all photos (unchanged).
|
||||
if (req.accessLevel === 'slideshow' && req.event.show_category_id) {
|
||||
photosQuery = photosQuery.where('photos.category_id', req.event.show_category_id);
|
||||
}
|
||||
|
||||
// Apply sort option
|
||||
if (sort === 'capture_date') {
|
||||
// Sort by capture date, falling back to uploaded_at if capture date is null
|
||||
@@ -437,8 +631,15 @@ router.get('/:slug/photos', verifyGalleryAccess, resolveGuest, async (req, res)
|
||||
photosQuery = photosQuery.orderBy('photos.uploaded_at', sortOrder);
|
||||
}
|
||||
|
||||
// Reveal mode (#838): while the gallery is hidden, plain guests get
|
||||
// the event shell with an empty photo/category set plus the
|
||||
// hidden_until_reveal flag — the frontend renders the upload-only view
|
||||
// from it. Slideshow, client access and the admin preview bypass
|
||||
// (guestBlockedByReveal). Enforced here, not just in the UI.
|
||||
const hiddenForGuest = guestBlockedByReveal(req);
|
||||
|
||||
// Execute the query
|
||||
let photos = await photosQuery;
|
||||
let photos = hiddenForGuest ? [] : await photosQuery;
|
||||
|
||||
// Apply filtering if requested (supports global stats + per-guest interactions)
|
||||
if (filter) {
|
||||
@@ -564,7 +765,7 @@ router.get('/:slug/photos', verifyGalleryAccess, resolveGuest, async (req, res)
|
||||
|
||||
// Get actual categories used by photos in this event
|
||||
// This includes both global categories and event-specific ones
|
||||
const usedCategoryIds = await db('photos')
|
||||
const usedCategoryIds = hiddenForGuest ? [] : await db('photos')
|
||||
.where('event_id', req.event.id)
|
||||
.whereNotNull('category_id')
|
||||
.distinct('category_id')
|
||||
@@ -573,10 +774,12 @@ router.get('/:slug/photos', verifyGalleryAccess, resolveGuest, async (req, res)
|
||||
// Fetch category details from photo_categories table
|
||||
let categories = [];
|
||||
if (usedCategoryIds.length > 0) {
|
||||
const categoryDetails = await db('photo_categories')
|
||||
.whereIn('id', usedCategoryIds)
|
||||
.select('id', 'name', 'slug', 'is_global', 'hero_photo_id', 'allow_downloads')
|
||||
.orderBy('name', 'asc');
|
||||
// Resolved category order (#782): per-event override, else global
|
||||
// default, else name — restricted to categories that have photos.
|
||||
const categoryDetails = await getEventCategoriesOrdered(req.event.id, {
|
||||
onlyIds: usedCategoryIds,
|
||||
select: ['c.id', 'c.name', 'c.slug', 'c.is_global', 'c.hero_photo_id', 'c.allow_downloads'],
|
||||
});
|
||||
|
||||
categories = categoryDetails.map(cat => ({
|
||||
id: cat.id,
|
||||
@@ -608,6 +811,7 @@ router.get('/:slug/photos', verifyGalleryAccess, resolveGuest, async (req, res)
|
||||
user_agent: req.headers['user-agent'],
|
||||
action: 'view'
|
||||
});
|
||||
notifyGalleryOpened(req.event, req);
|
||||
}
|
||||
|
||||
// Include protection settings in response
|
||||
@@ -665,6 +869,9 @@ router.get('/:slug/photos', verifyGalleryAccess, resolveGuest, async (req, res)
|
||||
hero_photo_id: req.event.hero_photo_id,
|
||||
allow_downloads: req.event.allow_downloads !== false,
|
||||
allow_user_uploads: req.event.allow_user_uploads === true,
|
||||
// Reveal mode (#838): armed flag lets an open VISIBLE gallery keep
|
||||
// polling so a re-hide propagates without a manual reload.
|
||||
reveal_armed: req.event.reveal_mode === true || req.event.reveal_mode === 1 || req.event.reveal_mode === '1',
|
||||
disable_right_click: req.event.disable_right_click === true,
|
||||
watermark_downloads: req.event.watermark_downloads === true,
|
||||
watermark_text: req.event.watermark_text,
|
||||
@@ -684,6 +891,10 @@ router.get('/:slug/photos', verifyGalleryAccess, resolveGuest, async (req, res)
|
||||
use_original_filenames: useOriginalFilenames,
|
||||
...protectionSettings
|
||||
},
|
||||
// Reveal mode (#838): the guest UI switches to the upload-only view
|
||||
// on this flag; reveal_at lets it show the scheduled time.
|
||||
hidden_until_reveal: hiddenForGuest,
|
||||
reveal_at: hiddenForGuest ? (req.event.reveal_at || null) : undefined,
|
||||
categories: categories,
|
||||
photos: photos.map(photo => {
|
||||
const useJwtUrl = (protectionSettings.protection_level === 'basic' || protectionSettings.protection_level === 'standard');
|
||||
@@ -709,7 +920,7 @@ router.get('/:slug/photos', verifyGalleryAccess, resolveGuest, async (req, res)
|
||||
// installs that haven't opted in keep loading the original
|
||||
// (current behaviour). Skipped for videos since they don't
|
||||
// get a preview tier; lightbox will use the original .url.
|
||||
preview_url: lightboxPreviewEnabled
|
||||
preview_url: (lightboxPreviewEnabled || originalNeedsPreview(photo))
|
||||
&& photo.media_type !== 'video'
|
||||
&& (!photo.mime_type || !photo.mime_type.startsWith('video/'))
|
||||
? `/api/gallery/${req.params.slug}/preview/${photo.id}${wmQuery}`
|
||||
@@ -726,14 +937,17 @@ router.get('/:slug/photos', verifyGalleryAccess, resolveGuest, async (req, res)
|
||||
: true,
|
||||
category_slug: photo.category_id && categoryMap[photo.category_id] ? categoryMap[photo.category_id].slug : null,
|
||||
size: photo.size_bytes,
|
||||
uploaded_at: photo.uploaded_at,
|
||||
// toIso: on SQLite installs rows written with a raw Date (e.g.
|
||||
// the pre-fix archive-restore path) hold epoch numbers — the
|
||||
// Timeline layout's parseISO() crashes on those (#485 class).
|
||||
uploaded_at: toIso(photo.uploaded_at),
|
||||
// Image dimensions for layout calculations
|
||||
width: photo.width || null,
|
||||
height: photo.height || null,
|
||||
// Fixed: Use the calculated useJwtUrl variable instead of recalculating
|
||||
requires_token: !useJwtUrl,
|
||||
// EXIF capture date
|
||||
captured_at: photo.captured_at || null,
|
||||
captured_at: toIso(photo.captured_at) || null,
|
||||
// Media type
|
||||
media_type: photo.media_type || null,
|
||||
mime_type: photo.mime_type || null,
|
||||
@@ -818,8 +1032,9 @@ router.patch('/:slug/photos/visibility/bulk', verifyGalleryAccess, async (req, r
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// Download single photo
|
||||
router.get('/:slug/download/:photoId', verifyGalleryAccess, denySlideshowToken, async (req, res) => {
|
||||
router.get('/:slug/download/:photoId', verifyGalleryAccess, denySlideshowToken, blockHiddenGallery, async (req, res) => {
|
||||
try {
|
||||
const { photoId } = req.params;
|
||||
|
||||
@@ -864,6 +1079,13 @@ router.get('/:slug/download/:photoId', verifyGalleryAccess, denySlideshowToken,
|
||||
action: 'download',
|
||||
photo_id: photoId
|
||||
});
|
||||
// Surface in the admin notification bell (#746) — debounced, and only
|
||||
// once the response actually finished: notifying up-front would log a
|
||||
// download that then 404s/fails and the debounce would suppress the
|
||||
// next real one for an hour (codex review of #849).
|
||||
res.on('finish', () => {
|
||||
if (res.statusCode < 400) notifySinglePhotoDownload(req.event, req);
|
||||
});
|
||||
|
||||
let filePath;
|
||||
try {
|
||||
@@ -933,7 +1155,7 @@ router.get('/:slug/download/:photoId', verifyGalleryAccess, denySlideshowToken,
|
||||
});
|
||||
|
||||
// Download all photos as ZIP
|
||||
router.get('/:slug/download-all', verifyGalleryAccess, denySlideshowToken, async (req, res) => {
|
||||
router.get('/:slug/download-all', verifyGalleryAccess, denySlideshowToken, blockHiddenGallery, async (req, res) => {
|
||||
try {
|
||||
// Check if downloads are allowed for this event
|
||||
if (req.event.allow_downloads === false) {
|
||||
@@ -962,6 +1184,8 @@ router.get('/:slug/download-all', verifyGalleryAccess, denySlideshowToken, async
|
||||
user_agent: req.headers['user-agent'],
|
||||
action: 'download_all_presigned'
|
||||
}).catch(() => {});
|
||||
// Surface in the admin notification bell (#746).
|
||||
logActivity('gallery_downloaded', { scope: 'all' }, req.event.id, galleryActor(req));
|
||||
res.redirect(302, url);
|
||||
return;
|
||||
} catch (err) {
|
||||
@@ -985,6 +1209,12 @@ router.get('/:slug/download-all', verifyGalleryAccess, denySlideshowToken, async
|
||||
user_agent: req.headers['user-agent'],
|
||||
action: 'download_all'
|
||||
}).catch(() => {});
|
||||
// Surface in the admin notification bell (#746) — only once the
|
||||
// stream actually finished; logging at pipe-time would report
|
||||
// downloads that then broke mid-transfer (codex review of #849).
|
||||
res.on('finish', () => {
|
||||
if (res.statusCode < 400) logActivity('gallery_downloaded', { scope: 'all' }, req.event.id, galleryActor(req));
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1089,6 +1319,12 @@ router.get('/:slug/download-all', verifyGalleryAccess, denySlideshowToken, async
|
||||
}
|
||||
}
|
||||
|
||||
// Notification only after the response actually finished — finalize()
|
||||
// ends Archiver's input, not the HTTP transfer (codex review of #849,
|
||||
// confirmation round). Registered before finalize so it can't be missed.
|
||||
res.on('finish', () => {
|
||||
if (res.statusCode < 400) logActivity('gallery_downloaded', { scope: 'all' }, req.event.id, galleryActor(req));
|
||||
});
|
||||
await archive.finalize();
|
||||
|
||||
// Log bulk download
|
||||
@@ -1104,7 +1340,7 @@ router.get('/:slug/download-all', verifyGalleryAccess, denySlideshowToken, async
|
||||
});
|
||||
|
||||
// Download selected photos as ZIP
|
||||
router.post('/:slug/download-selected', verifyGalleryAccess, denySlideshowToken, async (req, res) => {
|
||||
router.post('/:slug/download-selected', verifyGalleryAccess, denySlideshowToken, blockHiddenGallery, async (req, res) => {
|
||||
try {
|
||||
// Check if downloads are allowed for this event
|
||||
if (req.event.allow_downloads === false) {
|
||||
@@ -1207,6 +1443,10 @@ router.post('/:slug/download-selected', verifyGalleryAccess, denySlideshowToken,
|
||||
}
|
||||
}
|
||||
|
||||
// See download-all: notify only on response 'finish'.
|
||||
res.on('finish', () => {
|
||||
if (res.statusCode < 400) logActivity('gallery_downloaded', { scope: 'selected', photo_count: photoIds.length }, req.event.id, galleryActor(req));
|
||||
});
|
||||
await archive.finalize();
|
||||
|
||||
await db('access_logs').insert({
|
||||
@@ -1224,6 +1464,7 @@ router.post('/:slug/download-selected', verifyGalleryAccess, denySlideshowToken,
|
||||
// View single photo (with watermark if enabled)
|
||||
router.get('/:slug/photo/:photoId',
|
||||
verifyGalleryAccess,
|
||||
blockHiddenGallery,
|
||||
async (req, res) => {
|
||||
try {
|
||||
const { photoId } = req.params;
|
||||
@@ -1456,6 +1697,7 @@ router.get('/:slug/photo/:photoId',
|
||||
// Serve thumbnail
|
||||
router.get('/:slug/thumbnail/:photoId',
|
||||
verifyGalleryAccess,
|
||||
blockHiddenGallery,
|
||||
async (req, res) => {
|
||||
try {
|
||||
const { photoId } = req.params;
|
||||
@@ -1547,6 +1789,9 @@ router.get('/:slug/thumbnail/:photoId',
|
||||
// Serve hero-optimized image (1920x1080 for full-width hero sections)
|
||||
router.get('/:slug/hero/:photoId',
|
||||
verifyGalleryAccess,
|
||||
// Reveal-gated too: this route serves a 1920px derivative of ANY photo id,
|
||||
// not just the chosen hero — an open bypass while hidden (review round 1).
|
||||
blockHiddenGallery,
|
||||
async (req, res) => {
|
||||
try {
|
||||
const { photoId } = req.params;
|
||||
@@ -1645,6 +1890,7 @@ router.get('/:slug/hero/:photoId',
|
||||
// guest would see on the full original.
|
||||
router.get('/:slug/preview/:photoId',
|
||||
verifyGalleryAccess,
|
||||
blockHiddenGallery,
|
||||
async (req, res) => {
|
||||
try {
|
||||
const { photoId } = req.params;
|
||||
@@ -1743,6 +1989,7 @@ router.get('/:slug/feedback-settings', verifyGalleryAccess, async (req, res) =>
|
||||
allow_likes: settings.allow_likes,
|
||||
allow_comments: settings.allow_comments,
|
||||
allow_favorites: settings.allow_favorites,
|
||||
allow_reactions: settings.allow_reactions,
|
||||
show_feedback_to_guests: settings.show_feedback_to_guests,
|
||||
require_name_email: settings.require_name_email || false,
|
||||
identity_mode: settings.identity_mode || 'simple'
|
||||
@@ -1753,7 +2000,7 @@ router.get('/:slug/feedback-settings', verifyGalleryAccess, async (req, res) =>
|
||||
});
|
||||
|
||||
// Get photo stats
|
||||
router.get('/:slug/stats', verifyGalleryAccess, async (req, res) => {
|
||||
router.get('/:slug/stats', verifyGalleryAccess, blockHiddenGallery, async (req, res) => {
|
||||
try {
|
||||
const totalPhotos = await db('photos')
|
||||
.where('event_id', req.event.id)
|
||||
@@ -1816,7 +2063,7 @@ router.post('/:eventId/upload', verifyGalleryAccess, denySlideshowToken, async (
|
||||
|
||||
// Import multer and photo processing
|
||||
const multer = require('multer');
|
||||
const { getAllowedMimeTypes, getMaxFilesPerUpload } = require('../services/uploadSettings');
|
||||
const { getAllowedMimeTypes, getMaxFilesPerUpload, getMaxFileSizeBytes, DEFAULT_MAX_FILE_SIZE_MB } = require('../services/uploadSettings');
|
||||
const { validateFileType } = require('../utils/fileSecurityUtils');
|
||||
|
||||
// Resolve allowed MIME types from settings
|
||||
@@ -1842,10 +2089,22 @@ router.post('/:eventId/upload', verifyGalleryAccess, denySlideshowToken, async (
|
||||
maxFilesPerUpload = 500;
|
||||
}
|
||||
|
||||
// Per-file size cap was hardcoded to 50MB here, so the admin's Settings →
|
||||
// General → "Max File Size (MB)" value (general_max_file_size_mb) never
|
||||
// applied to guest uploads — a guest could not upload a large video even
|
||||
// when the admin allowed it (reported on #613 by mat1990dj). Resolve it from
|
||||
// settings like the count above; fall back to the 50MB default on read error.
|
||||
let maxFileSizeBytes;
|
||||
try {
|
||||
maxFileSizeBytes = await getMaxFileSizeBytes();
|
||||
} catch {
|
||||
maxFileSizeBytes = DEFAULT_MAX_FILE_SIZE_MB * 1024 * 1024;
|
||||
}
|
||||
|
||||
const upload = multer({
|
||||
dest: tempUploadDir,
|
||||
limits: {
|
||||
fileSize: 50 * 1024 * 1024, // 50MB per file (separate concern from #613)
|
||||
fileSize: maxFileSizeBytes,
|
||||
files: maxFilesPerUpload
|
||||
},
|
||||
fileFilter: (req, file, cb) => {
|
||||
@@ -1861,6 +2120,12 @@ router.post('/:eventId/upload', verifyGalleryAccess, denySlideshowToken, async (
|
||||
upload(req, res, async (err) => {
|
||||
if (err) {
|
||||
logger.error('Upload error:', err);
|
||||
// Turn multer's generic "File too large" into an actionable message
|
||||
// that names the configured limit.
|
||||
if (err.code === 'LIMIT_FILE_SIZE') {
|
||||
const limitMb = Math.floor(maxFileSizeBytes / (1024 * 1024));
|
||||
return res.status(400).json({ error: `File too large. Maximum size is ${limitMb} MB per file.` });
|
||||
}
|
||||
return res.status(400).json({ error: err.message });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { verifyGalleryAccess, denySlideshowToken } = require('../middleware/gallery');
|
||||
const { guestBlockedByReveal, blockHiddenGallery } = require('../utils/revealMode');
|
||||
const { feedbackRateLimit, generateGuestIdentifier } = require('../middleware/feedbackRateLimit');
|
||||
const { resolveGuest } = require('../middleware/guestAuth');
|
||||
const feedbackService = require('../services/feedbackService');
|
||||
@@ -31,6 +32,7 @@ router.get('/:slug/feedback-settings',
|
||||
allow_likes: Boolean(settings.allow_likes),
|
||||
allow_comments: Boolean(settings.allow_comments),
|
||||
allow_favorites: Boolean(settings.allow_favorites),
|
||||
allow_reactions: Boolean(settings.allow_reactions),
|
||||
require_name_email: Boolean(settings.require_name_email),
|
||||
show_feedback_to_guests: Boolean(settings.show_feedback_to_guests),
|
||||
identity_mode: settings.identity_mode || 'simple',
|
||||
@@ -52,6 +54,9 @@ router.get('/:slug/feedback-settings',
|
||||
// Get feedback for a specific photo
|
||||
router.get('/:slug/photos/:photoId/feedback',
|
||||
verifyGalleryAccess,
|
||||
// Reveal-gated (#838): sequential photo ids would let hidden-gallery
|
||||
// guests enumerate comments/stats.
|
||||
blockHiddenGallery,
|
||||
resolveGuest,
|
||||
validatePhotoId,
|
||||
checkValidation,
|
||||
@@ -117,6 +122,9 @@ router.get('/:slug/photos/:photoId/feedback',
|
||||
.then(r => r.count),
|
||||
like_count: photo.like_count || 0,
|
||||
favorite_count: photo.favorite_count || 0,
|
||||
// Gated like the per-emoji map below — aggregate reaction data is
|
||||
// a new surface, kept fully hidden while sharing is off.
|
||||
reaction_count: settings.show_feedback_to_guests ? (photo.reaction_count || 0) : 0,
|
||||
comment_count: await db('photo_feedback')
|
||||
.where({
|
||||
photo_id: photoId,
|
||||
@@ -128,10 +136,17 @@ router.get('/:slug/photos/:photoId/feedback',
|
||||
.first()
|
||||
.then(r => r.count)
|
||||
},
|
||||
// Per-emoji tallies for the reaction bar (#839). Gated on
|
||||
// show_feedback_to_guests: with sharing off a guest sees only their
|
||||
// own selection (my_feedback.reaction below), no aggregate counts.
|
||||
reactions: settings.show_feedback_to_guests
|
||||
? await feedbackService.getPhotoReactionCounts(photoId)
|
||||
: {},
|
||||
my_feedback: {
|
||||
rating: guestFeedback.find(f => f.feedback_type === 'rating')?.rating,
|
||||
liked: !!guestFeedback.find(f => f.feedback_type === 'like'),
|
||||
favorited: !!guestFeedback.find(f => f.feedback_type === 'favorite')
|
||||
favorited: !!guestFeedback.find(f => f.feedback_type === 'favorite'),
|
||||
reaction: guestFeedback.find(f => f.feedback_type === 'reaction')?.reaction || null
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
@@ -145,6 +160,8 @@ router.get('/:slug/photos/:photoId/feedback',
|
||||
router.post('/:slug/photos/:photoId/feedback',
|
||||
verifyGalleryAccess,
|
||||
denySlideshowToken,
|
||||
// Reveal-gated (#838): no interacting with photos you cannot see.
|
||||
blockHiddenGallery,
|
||||
resolveGuest,
|
||||
validatePhotoId,
|
||||
validateFeedbackSubmission,
|
||||
@@ -181,7 +198,8 @@ router.post('/:slug/photos/:photoId/feedback',
|
||||
rating: settings.allow_ratings,
|
||||
like: settings.allow_likes,
|
||||
comment: settings.allow_comments,
|
||||
favorite: settings.allow_favorites
|
||||
favorite: settings.allow_favorites,
|
||||
reaction: settings.allow_reactions
|
||||
};
|
||||
|
||||
if (!typeAllowed[feedbackType]) {
|
||||
@@ -227,6 +245,7 @@ router.post('/:slug/photos/:photoId/feedback',
|
||||
feedback_type: feedbackType,
|
||||
rating: req.body.rating,
|
||||
comment_text: req.body.comment_text,
|
||||
reaction: req.body.reaction,
|
||||
guest_name: req.guest?.name ?? req.body.guest_name,
|
||||
guest_email: req.guest?.email ?? req.body.guest_email,
|
||||
guest_id: req.guest?.id ?? null,
|
||||
@@ -313,7 +332,13 @@ router.get('/:slug/feedback-summary',
|
||||
async (req, res) => {
|
||||
try {
|
||||
const event = req.event;
|
||||
|
||||
|
||||
// Reveal mode (#838): the summary lists top photos by filename —
|
||||
// hidden along with the gallery for plain guests.
|
||||
if (guestBlockedByReveal(req)) {
|
||||
return res.json({ enabled: false, summary: null });
|
||||
}
|
||||
|
||||
// Get feedback settings
|
||||
const settings = await feedbackService.getEventFeedbackSettings(event.id);
|
||||
|
||||
@@ -346,7 +371,8 @@ router.get('/:slug/feedback-summary',
|
||||
allow_ratings: settings.allow_ratings,
|
||||
allow_likes: settings.allow_likes,
|
||||
allow_comments: settings.allow_comments,
|
||||
allow_favorites: settings.allow_favorites
|
||||
allow_favorites: settings.allow_favorites,
|
||||
allow_reactions: settings.allow_reactions
|
||||
},
|
||||
summary: guestSummary
|
||||
});
|
||||
@@ -365,6 +391,13 @@ router.get('/:slug/my-feedback',
|
||||
try {
|
||||
const event = req.event;
|
||||
|
||||
// Reveal mode (#838): rows join photos (filename + storage path) —
|
||||
// return the empty back-compat shape rather than a 403 so the gallery
|
||||
// shell loading in parallel doesn't surface error toasts.
|
||||
if (guestBlockedByReveal(req)) {
|
||||
return res.json([]);
|
||||
}
|
||||
|
||||
const query = db('photo_feedback')
|
||||
.join('photos', 'photo_feedback.photo_id', 'photos.id')
|
||||
.where('photo_feedback.event_id', event.id);
|
||||
|
||||
@@ -2,6 +2,7 @@ const express = require('express');
|
||||
const { db } = require('../database/db');
|
||||
const { formatBoolean } = require('../utils/dbCompat');
|
||||
const { verifyGalleryAccess } = require('../middleware/gallery');
|
||||
const { blockHiddenGallery, bypassesReveal, isGalleryHidden } = require('../utils/revealMode');
|
||||
const watermarkService = require('../services/watermarkService');
|
||||
const secureImageService = require('../services/secureImageService');
|
||||
const { getStorage } = require('../services/storage');
|
||||
@@ -16,10 +17,13 @@ const router = express.Router();
|
||||
/**
|
||||
* Generate a signed URL token for image access
|
||||
*/
|
||||
function generateImageToken(photoId, expiresIn = 3600) {
|
||||
function generateImageToken(photoId, expiresIn = 3600, revealBypass = false) {
|
||||
const secret = process.env.JWT_SECRET;
|
||||
const expires = Date.now() + (expiresIn * 1000);
|
||||
const data = `${photoId}:${expires}`;
|
||||
// Third segment (#838): whether the minting context bypasses reveal mode
|
||||
// (slideshow/client/admin). Old two-segment tokens verify unchanged and
|
||||
// read as no-bypass.
|
||||
const data = `${photoId}:${expires}:${revealBypass ? 1 : 0}`;
|
||||
const signature = crypto.createHmac('sha256', secret).update(data).digest('hex');
|
||||
return `${Buffer.from(data).toString('base64')}.${signature}`;
|
||||
}
|
||||
@@ -32,7 +36,7 @@ function verifyImageToken(token) {
|
||||
const secret = process.env.JWT_SECRET;
|
||||
const [data, signature] = token.split('.');
|
||||
const decoded = Buffer.from(data, 'base64').toString();
|
||||
const [photoId, expires] = decoded.split(':');
|
||||
const [photoId, expires, bypassFlag] = decoded.split(':');
|
||||
|
||||
// Verify signature (constant-time — avoids leaking the HMAC byte-by-byte)
|
||||
const expectedSignature = crypto.createHmac('sha256', secret).update(decoded).digest('hex');
|
||||
@@ -45,7 +49,7 @@ function verifyImageToken(token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return { photoId: parseInt(photoId), expires: parseInt(expires) };
|
||||
return { photoId: parseInt(photoId), expires: parseInt(expires), revealBypass: bypassFlag === '1' };
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
@@ -54,7 +58,7 @@ function verifyImageToken(token) {
|
||||
/**
|
||||
* Serve protected image with enhanced security
|
||||
*/
|
||||
router.get('/:slug/photo/:photoId/view', verifyGalleryAccess, async (req, res) => {
|
||||
router.get('/:slug/photo/:photoId/view', verifyGalleryAccess, blockHiddenGallery, async (req, res) => {
|
||||
try {
|
||||
const { photoId } = req.params;
|
||||
const { protectionLevel = 'standard', token } = req.query;
|
||||
@@ -174,7 +178,7 @@ router.get('/:slug/photo/:photoId/view', verifyGalleryAccess, async (req, res) =
|
||||
/**
|
||||
* Generate secure token for enhanced image access
|
||||
*/
|
||||
router.post('/:slug/photo/:photoId/generate-secure-token', verifyGalleryAccess, async (req, res) => {
|
||||
router.post('/:slug/photo/:photoId/generate-secure-token', verifyGalleryAccess, blockHiddenGallery, async (req, res) => {
|
||||
try {
|
||||
const { photoId } = req.params;
|
||||
const { protectionLevel = 'standard', expiresIn = 300 } = req.body;
|
||||
@@ -219,6 +223,11 @@ router.post('/:slug/photo/:photoId/generate-secure-token', verifyGalleryAccess,
|
||||
* Generate signed URL for image access (legacy support)
|
||||
*/
|
||||
router.post('/:slug/photo/:photoId/generate-url', verifyGalleryAccess, async (req, res) => {
|
||||
// Reveal-gated for plain guests; bypass callers get a token that stays
|
||||
// valid at SERVE time too (third token segment below).
|
||||
if (require('../utils/revealMode').guestBlockedByReveal(req)) {
|
||||
return res.status(403).json({ error: 'Gallery is hidden until reveal', code: 'GALLERY_HIDDEN' });
|
||||
}
|
||||
try {
|
||||
const { photoId } = req.params;
|
||||
|
||||
@@ -235,7 +244,7 @@ router.post('/:slug/photo/:photoId/generate-url', verifyGalleryAccess, async (re
|
||||
}
|
||||
|
||||
// Generate signed token
|
||||
const token = generateImageToken(photoId);
|
||||
const token = generateImageToken(photoId, 3600, bypassesReveal(req));
|
||||
const signedUrl = `/api/images/${req.params.slug}/photo/${photoId}/signed/${token}`;
|
||||
|
||||
res.json({
|
||||
@@ -271,7 +280,13 @@ router.get('/:slug/photo/:photoId/signed/:token', async (req, res) => {
|
||||
if (!event) {
|
||||
return res.status(404).json({ error: 'Event not found' });
|
||||
}
|
||||
|
||||
|
||||
// Reveal mode (#838): a signed URL minted before a re-hide must not keep
|
||||
// serving hidden photos; tokens minted by bypass contexts carry the flag.
|
||||
if (isGalleryHidden(event) && !tokenData.revealBypass) {
|
||||
return res.status(403).json({ error: 'Gallery is hidden until reveal', code: 'GALLERY_HIDDEN' });
|
||||
}
|
||||
|
||||
// Get photo
|
||||
const photo = await db('photos')
|
||||
.where({
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user