Säkerhetskopior, papperskorg, historik, härdning, adminsida och snabbsök
- Automatisk nattlig säkerhetskopiering (zip per bok med bilder), schemaläggare via instrumentation, adminsida med manuell körning och nedladdning - Papperskorg för poster (ögonblicksbild med relationer, scheman, markeringar) och böcker (zip), återställning och automatisk rensning - Ändringshistorik för poster med fältvis diff och återställning - Härdning: säkerhetsrubriker och CSP via middleware, hastighetsbegränsning, lagringskvot per användare, konfigurerbar sessionstid - Bildoptimering med sharp (EXIF-rotation, nedskalning, metadata borttagen) och miniatyrer - Strukturerade JSON-loggar, onRequestError och Prometheus-mätvärden på /api/metrics - Snabbsök och kommandopalett (Ctrl+K) med sökning i poster och mallfält - Migration 0005_system, nya volymer och miljövariabler, versionsinfo via build-args - README, .env.example och TODO uppdaterade Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
323e50d9ac
commit
4e8d79ee10
60 files changed
+2499
-251
No files matched your search
@@ -28,6 +28,28 @@ AUTHENTIK_CLIENT_SECRET=
|
|||||||
# Var databas och uppladdningar sparas i produktion (standard ./data bredvid compose-filen)
|
# Var databas och uppladdningar sparas i produktion (standard ./data bredvid compose-filen)
|
||||||
# DATA_DIR=./data
|
# DATA_DIR=./data
|
||||||
|
|
||||||
|
# ---------- Drift, säkerhet och loggar (alla valfria) ----------
|
||||||
|
# Vem som är administratör (adminsidan /admin). Kommaseparerade e-postadresser.
|
||||||
|
# Saknas värdet är den äldsta användaren administratör.
|
||||||
|
# ADMIN_EMAILS=du@example.com
|
||||||
|
# Tidszon för schemalagda jobb, t.ex. nattens säkerhetskopia (standard Europe/Stockholm i produktion)
|
||||||
|
# TZ=Europe/Stockholm
|
||||||
|
# Automatisk säkerhetskopiering av alla böcker: på/av, timme på dygnet och hur många körningar som behålls
|
||||||
|
# BACKUP_ENABLED=true
|
||||||
|
# BACKUP_HOUR=3
|
||||||
|
# BACKUP_KEEP=14
|
||||||
|
# Hur länge borttaget ligger i papperskorgen (dagar) och hur många tidigare versioner av en post som sparas
|
||||||
|
# TRASH_DAYS=30
|
||||||
|
# MAX_VERSIONS=30
|
||||||
|
# Inloggningens livslängd i dagar och lagringskvot för bilder per användare (MB)
|
||||||
|
# SESSION_DAYS=14
|
||||||
|
# USER_QUOTA_MB=2048
|
||||||
|
# Loggar: nivå (debug, info, warn, error) och format (json eller text, JSON är standard i produktion)
|
||||||
|
# LOG_LEVEL=info
|
||||||
|
# LOG_FORMAT=json
|
||||||
|
# Prometheus-mätvärden på /api/metrics. Avstängt tills en token är satt: openssl rand -hex 24
|
||||||
|
# METRICS_TOKEN=
|
||||||
|
|
||||||
# Kartor: standard är OpenStreetMaps publika servrar, som är tänkta för lätt användning.
|
# Kartor: standard är OpenStreetMaps publika servrar, som är tänkta för lätt användning.
|
||||||
# MAP_TILE_URL=https://tile.openstreetmap.org/{z}/{x}/{y}.png
|
# MAP_TILE_URL=https://tile.openstreetmap.org/{z}/{x}/{y}.png
|
||||||
# MAP_TILE_ATTRIBUTION=© OpenStreetMap-bidragsgivare
|
# MAP_TILE_ATTRIBUTION=© OpenStreetMap-bidragsgivare
|
||||||
|
|||||||
@@ -32,6 +32,11 @@ RUN DATABASE_URL="postgresql://build:build@localhost:5432/build" AUTH_SECRET="bu
|
|||||||
|
|
||||||
# ---------- Produktion ----------
|
# ---------- Produktion ----------
|
||||||
FROM base AS prod
|
FROM base AS prod
|
||||||
|
# Version och bygge som visas i sidomenyn, på adminsidan och i /api/metrics
|
||||||
|
ARG APP_VERSION=dev
|
||||||
|
ARG APP_COMMIT=
|
||||||
|
ENV APP_VERSION=$APP_VERSION \
|
||||||
|
APP_COMMIT=$APP_COMMIT
|
||||||
ENV NODE_ENV=production \
|
ENV NODE_ENV=production \
|
||||||
NEXT_TELEMETRY_DISABLED=1 \
|
NEXT_TELEMETRY_DISABLED=1 \
|
||||||
PORT=3000 \
|
PORT=3000 \
|
||||||
|
|||||||
@@ -154,6 +154,24 @@ Alla ID skapas automatiskt enligt ID-översikten, med löpande nummer per bok oc
|
|||||||
|
|
||||||
Appar och Hemsidor har inget ID. Prefixen ligger samlade i `src/lib/ids.ts`. Sidan **ID-register** listar alla ID i boken med sökning och filter. Befintliga poster får ID vid uppgraderingen i den ordning de skapades, och tidigare handskrivna koder ersätts.
|
Appar och Hemsidor har inget ID. Prefixen ligger samlade i `src/lib/ids.ts`. Sidan **ID-register** listar alla ID i boken med sökning och filter. Befintliga poster får ID vid uppgraderingen i den ordning de skapades, och tidigare handskrivna koder ersätts.
|
||||||
|
|
||||||
|
## Säkerhet och drift
|
||||||
|
|
||||||
|
**Säkerhetskopior.** Varje natt (klockan `BACKUP_HOUR`, standard 03:00 i `TZ`) sparas en zip per bok med bilder i `./data/backups/<tidpunkt>/`. De `BACKUP_KEEP` senaste körningarna (standard 14) behålls. Zip-filerna är samma format som exporten och importeras via *Importera bok*. Missade körningar tas igen vid nästa start. Administratören kan köra en säkerhetskopia direkt och ladda ner filerna på *Administration*. Kopiera gärna `backups/` till en annan maskin.
|
||||||
|
|
||||||
|
**Papperskorg.** Borttagna poster och böcker flyttas till papperskorgen i `TRASH_DAYS` dagar (standard 30) och kan återställas. En post återställs med sina relationer, scheman och markeringar, och behåller sitt ID. En bok sparas som zip i `./data/trash` och återställs som en ny bok. Papperskorgen rensas automatiskt.
|
||||||
|
|
||||||
|
**Ändringshistorik.** Varje ändring av en post sparar den tidigare versionen (de `MAX_VERSIONS` senaste, standard 30). *Historik* på postens sida visar skillnaderna fält för fält och kan återställa en tidigare version. Att återställa sparar först den nuvarande, så det går att ångra. Bilder ingår inte i historiken.
|
||||||
|
|
||||||
|
**Snabbsök.** Ctrl+K (Cmd+K på Mac) öppnar en kommandopalett: sök poster (namn, ID, sammanfattning, taggar och mallfält), hoppa till en sida eller skapa något nytt.
|
||||||
|
|
||||||
|
**Bilder.** Uppladdade bilder roteras efter EXIF, skalas ned (längsta sida 2 400 px, kartbilder 6 000 px), omkomprimeras och rensas från metadata som GPS-position. Listor använder små miniatyrer. Varje användare har en lagringskvot (`USER_QUOTA_MB`, standard 2 048 MB).
|
||||||
|
|
||||||
|
**Härdning.** Säkerhetsrubriker sätts på alla sidor (Content-Security-Policy som släpper igenom kartservrarna från `MAP_TILE_URL` och `MAP_GEOCODER_URL`, HSTS över https, skydd mot inramning). Inloggning, import, export, sök och namnstatistik har hastighetsbegränsning per IP-adress. Inloggningen gäller i `SESSION_DAYS` dagar (standard 14).
|
||||||
|
|
||||||
|
**Administration.** Sidan `/admin` visar version, databas- och lagringsstorlek, antal användare och böcker, säkerhetskopior och om SCB och Skatteverket går att nå. Administratör är den som anges i `ADMIN_EMAILS`, och finns inget värde är den äldsta användaren administratör. Versionen visas också i sidomenyn. Den sätts när imagen byggs: `docker build --build-arg APP_VERSION=1.0.4 --build-arg APP_COMMIT=$(git rev-parse HEAD) ...`.
|
||||||
|
|
||||||
|
**Loggar och mätvärden.** Loggar skrivs som JSON, en rad per händelse (`LOG_LEVEL`, `LOG_FORMAT`), och serverfel loggas med sidans sökväg. Sätter du `METRICS_TOKEN` finns Prometheus-mätvärden på `/api/metrics` (anropa med `Authorization: Bearer <token>`): antal användare, böcker och poster, databas- och bildstorlek, papperskorg, senaste lyckade säkerhetskopia, minne och antal anrop som hastighetsbegränsningen stoppat.
|
||||||
|
|
||||||
## Namngenerator
|
## Namngenerator
|
||||||
|
|
||||||
Under *Planering → Namngenerator* slumpas svenska namn fram. Välj kvinna, man eller slumpa, **födelseår**, efternamnstyp (alla, bara -son eller utan -son), antal förslag och om ett mellannamn ska ingå. Kopiera ett namn eller klicka *Skapa karaktär* för att starta ett formulär med namnet ifyllt.
|
Under *Planering → Namngenerator* slumpas svenska namn fram. Välj kvinna, man eller slumpa, **födelseår**, efternamnstyp (alla, bara -son eller utan -son), antal förslag och om ett mellannamn ska ingå. Kopiera ett namn eller klicka *Skapa karaktär* för att starta ett formulär med namnet ifyllt.
|
||||||
|
|||||||
@@ -57,6 +57,9 @@ jobs:
|
|||||||
target: prod
|
target: prod
|
||||||
push: true
|
push: true
|
||||||
tags: ${{ steps.tags.outputs.list }}
|
tags: ${{ steps.tags.outputs.list }}
|
||||||
|
build-args: |
|
||||||
|
APP_VERSION=${{ gitea.ref_type == 'tag' && gitea.ref_name || 'main' }}
|
||||||
|
APP_COMMIT=${{ gitea.sha }}
|
||||||
cache-from: type=registry,ref=${{ env.IMAGE }}:buildcache
|
cache-from: type=registry,ref=${{ env.IMAGE }}:buildcache
|
||||||
cache-to: type=registry,ref=${{ env.IMAGE }}:buildcache,mode=max
|
cache-to: type=registry,ref=${{ env.IMAGE }}:buildcache,mode=max
|
||||||
```
|
```
|
||||||
@@ -70,6 +73,12 @@ jobs:
|
|||||||
- Ladda upp en stor kartbild (10–15 MB). Gränsen för förfrågningar via inloggningskontrollen höjdes till 300 MB i samband med import och export, men en stor kartbild är inte testad.
|
- Ladda upp en stor kartbild (10–15 MB). Gränsen för förfrågningar via inloggningskontrollen höjdes till 300 MB i samband med import och export, men en stor kartbild är inte testad.
|
||||||
- Kör Docker-filerna på riktigt (`docker compose ... config` och en full start). Dev- och prod-compose har inte körts i miljön där koden skrevs.
|
- Kör Docker-filerna på riktigt (`docker compose ... config` och en full start). Dev- och prod-compose har inte körts i miljön där koden skrevs.
|
||||||
- Bygg imagen med den mindre Dockerfile och jämför storleken mot den gamla.
|
- Bygg imagen med den mindre Dockerfile och jämför storleken mot den gamla.
|
||||||
|
- Efter uppdateringen med säkerhetskopior, papperskorg och bildoptimering (testat lokalt, men inte i Docker):
|
||||||
|
- Att `sharp` (bildbehandling) installeras och fungerar i imagen (Debian, linux-x64) och att bilder skalas vid uppladdning.
|
||||||
|
- Att `uploads-init` ger skrivrätt till `./data/backups` och `./data/trash`, och att nattens säkerhetskopia skapas där.
|
||||||
|
- Att Content-Security-Policy inte stör inloggningen mot Authentik (omdirigeringen till och från Authentik) i en riktig miljö.
|
||||||
|
- Att `ADMIN_EMAILS` och `TZ` ger rätt administratör och rätt tid för säkerhetskopian.
|
||||||
|
- Att `/api/metrics` fungerar mot din Prometheus (sätt `METRICS_TOKEN`).
|
||||||
|
|
||||||
## Idéer
|
## Idéer
|
||||||
|
|
||||||
|
|||||||
@@ -45,6 +45,9 @@ services:
|
|||||||
AUTHENTIK_CLIENT_ID: ${AUTHENTIK_CLIENT_ID:-}
|
AUTHENTIK_CLIENT_ID: ${AUTHENTIK_CLIENT_ID:-}
|
||||||
AUTHENTIK_CLIENT_SECRET: ${AUTHENTIK_CLIENT_SECRET:-}
|
AUTHENTIK_CLIENT_SECRET: ${AUTHENTIK_CLIENT_SECRET:-}
|
||||||
UPLOAD_DIR: /data/uploads
|
UPLOAD_DIR: /data/uploads
|
||||||
|
BACKUP_DIR: /data/backups
|
||||||
|
TRASH_DIR: /data/trash
|
||||||
|
BACKUP_ENABLED: ${BACKUP_ENABLED:-false}
|
||||||
WATCHPACK_POLLING: "true" # filändringar upptäcks även via Windows/Mac-volymer
|
WATCHPACK_POLLING: "true" # filändringar upptäcks även via Windows/Mac-volymer
|
||||||
NEXT_TELEMETRY_DISABLED: "1"
|
NEXT_TELEMETRY_DISABLED: "1"
|
||||||
ports:
|
ports:
|
||||||
@@ -54,6 +57,8 @@ services:
|
|||||||
- node-modules:/app/node_modules # beroenden från bilden, inte från värddatorn
|
- node-modules:/app/node_modules # beroenden från bilden, inte från värddatorn
|
||||||
- next-cache:/app/.next
|
- next-cache:/app/.next
|
||||||
- ./data/dev/uploads:/data/uploads
|
- ./data/dev/uploads:/data/uploads
|
||||||
|
- ./data/dev/backups:/data/backups
|
||||||
|
- ./data/dev/trash:/data/trash
|
||||||
# node_modules ligger i en volym som överlever ombyggnad av bilden. Därför synkas beroenden och
|
# node_modules ligger i en volym som överlever ombyggnad av bilden. Därför synkas beroenden och
|
||||||
# Prisma-klienten vid varje start, så att nya paket och schemaändringar alltid slår igenom.
|
# Prisma-klienten vid varje start, så att nya paket och schemaändringar alltid slår igenom.
|
||||||
command: sh -c "npm install --no-audit --no-fund && npx prisma generate && npx prisma migrate deploy && npm run dev"
|
command: sh -c "npm install --no-audit --no-fund && npx prisma generate && npx prisma migrate deploy && npm run dev"
|
||||||
|
|||||||
+11
-3
@@ -20,12 +20,14 @@ services:
|
|||||||
networks:
|
networks:
|
||||||
- internal
|
- internal
|
||||||
|
|
||||||
# Engångssteg: ger appen (användare "node", uid 1000) skrivrätt i uppladdningsmappen på värddatorn.
|
# Engångssteg: ger appen (användare "node", uid 1000) skrivrätt i mapparna på värddatorn.
|
||||||
uploads-init:
|
uploads-init:
|
||||||
image: alpine:3
|
image: alpine:3
|
||||||
command: chown -R 1000:1000 /data/uploads
|
command: chown -R 1000:1000 /data/uploads /data/backups /data/trash
|
||||||
volumes:
|
volumes:
|
||||||
- ${DATA_DIR:-./data}/uploads:/data/uploads
|
- ${DATA_DIR:-./data}/uploads:/data/uploads
|
||||||
|
- ${DATA_DIR:-./data}/backups:/data/backups
|
||||||
|
- ${DATA_DIR:-./data}/trash:/data/trash
|
||||||
networks:
|
networks:
|
||||||
- internal
|
- internal
|
||||||
|
|
||||||
@@ -52,8 +54,13 @@ services:
|
|||||||
AUTHENTIK_CLIENT_ID: ${AUTHENTIK_CLIENT_ID:?Sätt AUTHENTIK_CLIENT_ID i .env}
|
AUTHENTIK_CLIENT_ID: ${AUTHENTIK_CLIENT_ID:?Sätt AUTHENTIK_CLIENT_ID i .env}
|
||||||
AUTHENTIK_CLIENT_SECRET: ${AUTHENTIK_CLIENT_SECRET:?Sätt AUTHENTIK_CLIENT_SECRET i .env}
|
AUTHENTIK_CLIENT_SECRET: ${AUTHENTIK_CLIENT_SECRET:?Sätt AUTHENTIK_CLIENT_SECRET i .env}
|
||||||
UPLOAD_DIR: /data/uploads
|
UPLOAD_DIR: /data/uploads
|
||||||
|
BACKUP_DIR: /data/backups
|
||||||
|
TRASH_DIR: /data/trash
|
||||||
|
TZ: ${TZ:-Europe/Stockholm} # styr när nattens säkerhetskopia körs
|
||||||
volumes:
|
volumes:
|
||||||
- ${DATA_DIR:-./data}/uploads:/data/uploads
|
- ${DATA_DIR:-./data}/uploads:/data/uploads
|
||||||
|
- ${DATA_DIR:-./data}/backups:/data/backups
|
||||||
|
- ${DATA_DIR:-./data}/trash:/data/trash
|
||||||
ports:
|
ports:
|
||||||
# Lägg en omvänd proxy (Traefik, Nginx Proxy Manager, Caddy ...) framför med HTTPS.
|
# Lägg en omvänd proxy (Traefik, Nginx Proxy Manager, Caddy ...) framför med HTTPS.
|
||||||
- "${APP_PORT:-3000}:3000"
|
- "${APP_PORT:-3000}:3000"
|
||||||
@@ -66,4 +73,5 @@ networks:
|
|||||||
# proxy:
|
# proxy:
|
||||||
# external: true
|
# external: true
|
||||||
|
|
||||||
# All persistent data ligger i ${DATA_DIR:-./data}/db och ${DATA_DIR:-./data}/uploads. Ta backup på mappen.
|
# All persistent data ligger i ${DATA_DIR:-./data}: db (databas), uploads (bilder), backups (automatiska
|
||||||
|
# säkerhetskopior) och trash (borttagna böcker). Kopiera gärna backups/ till en annan maskin.
|
||||||
@@ -1,7 +1,18 @@
|
|||||||
/** @type {import('next').NextConfig} */
|
/** @type {import('next').NextConfig} */
|
||||||
|
// Statiska säkerhetsrubriker. Content-Security-Policy och HSTS beror på miljön och sätts i src/middleware.ts.
|
||||||
|
const securityHeaders = [
|
||||||
|
{ key: "X-Content-Type-Options", value: "nosniff" },
|
||||||
|
{ key: "X-Frame-Options", value: "DENY" },
|
||||||
|
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
|
||||||
|
{ key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=(), payment=()" },
|
||||||
|
];
|
||||||
|
|
||||||
const nextConfig = {
|
const nextConfig = {
|
||||||
reactStrictMode: true,
|
reactStrictMode: true,
|
||||||
poweredByHeader: false,
|
poweredByHeader: false,
|
||||||
|
async headers() {
|
||||||
|
return [{ source: "/:path*", headers: securityHeaders }];
|
||||||
|
},
|
||||||
eslint: { ignoreDuringBuilds: true },
|
eslint: { ignoreDuringBuilds: true },
|
||||||
experimental: {
|
experimental: {
|
||||||
optimizePackageImports: ["@tabler/icons-react"],
|
optimizePackageImports: ["@tabler/icons-react"],
|
||||||
|
|||||||
Generated
+131
-174
@@ -18,7 +18,8 @@
|
|||||||
"next-auth": "5.0.0-beta.32",
|
"next-auth": "5.0.0-beta.32",
|
||||||
"prisma": "^6.19.3",
|
"prisma": "^6.19.3",
|
||||||
"react": "^19.1.0",
|
"react": "^19.1.0",
|
||||||
"react-dom": "^19.1.0"
|
"react-dom": "^19.1.0",
|
||||||
|
"sharp": "^0.34.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/leaflet": "^1.9.20",
|
"@types/leaflet": "^1.9.20",
|
||||||
@@ -81,15 +82,14 @@
|
|||||||
"resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",
|
||||||
"integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",
|
"integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=18"
|
"node": ">=18"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@img/sharp-darwin-arm64": {
|
"node_modules/@img/sharp-darwin-arm64": {
|
||||||
"version": "0.35.5",
|
"version": "0.34.5",
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz",
|
"resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz",
|
||||||
"integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==",
|
"integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -99,19 +99,19 @@
|
|||||||
"darwin"
|
"darwin"
|
||||||
],
|
],
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20.9.0"
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://opencollective.com/libvips"
|
"url": "https://opencollective.com/libvips"
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@img/sharp-libvips-darwin-arm64": "1.3.4"
|
"@img/sharp-libvips-darwin-arm64": "1.2.4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@img/sharp-darwin-x64": {
|
"node_modules/@img/sharp-darwin-x64": {
|
||||||
"version": "0.35.5",
|
"version": "0.34.5",
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz",
|
"resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz",
|
||||||
"integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==",
|
"integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -121,38 +121,19 @@
|
|||||||
"darwin"
|
"darwin"
|
||||||
],
|
],
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20.9.0"
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://opencollective.com/libvips"
|
"url": "https://opencollective.com/libvips"
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@img/sharp-libvips-darwin-x64": "1.3.4"
|
"@img/sharp-libvips-darwin-x64": "1.2.4"
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@img/sharp-freebsd-wasm32": {
|
|
||||||
"version": "0.35.5",
|
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz",
|
|
||||||
"integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==",
|
|
||||||
"license": "Apache-2.0",
|
|
||||||
"optional": true,
|
|
||||||
"os": [
|
|
||||||
"freebsd"
|
|
||||||
],
|
|
||||||
"dependencies": {
|
|
||||||
"@img/sharp-wasm32": "0.35.5"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20.9.0"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://opencollective.com/libvips"
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@img/sharp-libvips-darwin-arm64": {
|
"node_modules/@img/sharp-libvips-darwin-arm64": {
|
||||||
"version": "1.3.4",
|
"version": "1.2.4",
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz",
|
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz",
|
||||||
"integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==",
|
"integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -166,9 +147,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@img/sharp-libvips-darwin-x64": {
|
"node_modules/@img/sharp-libvips-darwin-x64": {
|
||||||
"version": "1.3.4",
|
"version": "1.2.4",
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz",
|
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz",
|
||||||
"integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==",
|
"integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -182,9 +163,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@img/sharp-libvips-linux-arm": {
|
"node_modules/@img/sharp-libvips-linux-arm": {
|
||||||
"version": "1.3.4",
|
"version": "1.2.4",
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz",
|
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz",
|
||||||
"integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==",
|
"integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm"
|
"arm"
|
||||||
],
|
],
|
||||||
@@ -201,9 +182,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@img/sharp-libvips-linux-arm64": {
|
"node_modules/@img/sharp-libvips-linux-arm64": {
|
||||||
"version": "1.3.4",
|
"version": "1.2.4",
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz",
|
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz",
|
||||||
"integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==",
|
"integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -220,9 +201,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@img/sharp-libvips-linux-ppc64": {
|
"node_modules/@img/sharp-libvips-linux-ppc64": {
|
||||||
"version": "1.3.4",
|
"version": "1.2.4",
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz",
|
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.4.tgz",
|
||||||
"integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==",
|
"integrity": "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"ppc64"
|
"ppc64"
|
||||||
],
|
],
|
||||||
@@ -239,9 +220,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@img/sharp-libvips-linux-riscv64": {
|
"node_modules/@img/sharp-libvips-linux-riscv64": {
|
||||||
"version": "1.3.4",
|
"version": "1.2.4",
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz",
|
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.2.4.tgz",
|
||||||
"integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==",
|
"integrity": "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"riscv64"
|
"riscv64"
|
||||||
],
|
],
|
||||||
@@ -258,9 +239,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@img/sharp-libvips-linux-s390x": {
|
"node_modules/@img/sharp-libvips-linux-s390x": {
|
||||||
"version": "1.3.4",
|
"version": "1.2.4",
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz",
|
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.4.tgz",
|
||||||
"integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==",
|
"integrity": "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"s390x"
|
"s390x"
|
||||||
],
|
],
|
||||||
@@ -277,9 +258,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@img/sharp-libvips-linux-x64": {
|
"node_modules/@img/sharp-libvips-linux-x64": {
|
||||||
"version": "1.3.4",
|
"version": "1.2.4",
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz",
|
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz",
|
||||||
"integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==",
|
"integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -296,9 +277,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@img/sharp-libvips-linuxmusl-arm64": {
|
"node_modules/@img/sharp-libvips-linuxmusl-arm64": {
|
||||||
"version": "1.3.4",
|
"version": "1.2.4",
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz",
|
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz",
|
||||||
"integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==",
|
"integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -315,9 +296,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@img/sharp-libvips-linuxmusl-x64": {
|
"node_modules/@img/sharp-libvips-linuxmusl-x64": {
|
||||||
"version": "1.3.4",
|
"version": "1.2.4",
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz",
|
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz",
|
||||||
"integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==",
|
"integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -334,9 +315,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@img/sharp-linux-arm": {
|
"node_modules/@img/sharp-linux-arm": {
|
||||||
"version": "0.35.5",
|
"version": "0.34.5",
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz",
|
"resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz",
|
||||||
"integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==",
|
"integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm"
|
"arm"
|
||||||
],
|
],
|
||||||
@@ -349,19 +330,19 @@
|
|||||||
"linux"
|
"linux"
|
||||||
],
|
],
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20.9.0"
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://opencollective.com/libvips"
|
"url": "https://opencollective.com/libvips"
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@img/sharp-libvips-linux-arm": "1.3.4"
|
"@img/sharp-libvips-linux-arm": "1.2.4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@img/sharp-linux-arm64": {
|
"node_modules/@img/sharp-linux-arm64": {
|
||||||
"version": "0.35.5",
|
"version": "0.34.5",
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz",
|
"resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz",
|
||||||
"integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==",
|
"integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -374,19 +355,19 @@
|
|||||||
"linux"
|
"linux"
|
||||||
],
|
],
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20.9.0"
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://opencollective.com/libvips"
|
"url": "https://opencollective.com/libvips"
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@img/sharp-libvips-linux-arm64": "1.3.4"
|
"@img/sharp-libvips-linux-arm64": "1.2.4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@img/sharp-linux-ppc64": {
|
"node_modules/@img/sharp-linux-ppc64": {
|
||||||
"version": "0.35.5",
|
"version": "0.34.5",
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz",
|
"resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.5.tgz",
|
||||||
"integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==",
|
"integrity": "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"ppc64"
|
"ppc64"
|
||||||
],
|
],
|
||||||
@@ -399,19 +380,19 @@
|
|||||||
"linux"
|
"linux"
|
||||||
],
|
],
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20.9.0"
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://opencollective.com/libvips"
|
"url": "https://opencollective.com/libvips"
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@img/sharp-libvips-linux-ppc64": "1.3.4"
|
"@img/sharp-libvips-linux-ppc64": "1.2.4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@img/sharp-linux-riscv64": {
|
"node_modules/@img/sharp-linux-riscv64": {
|
||||||
"version": "0.35.5",
|
"version": "0.34.5",
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz",
|
"resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.34.5.tgz",
|
||||||
"integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==",
|
"integrity": "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"riscv64"
|
"riscv64"
|
||||||
],
|
],
|
||||||
@@ -424,19 +405,19 @@
|
|||||||
"linux"
|
"linux"
|
||||||
],
|
],
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20.9.0"
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://opencollective.com/libvips"
|
"url": "https://opencollective.com/libvips"
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@img/sharp-libvips-linux-riscv64": "1.3.4"
|
"@img/sharp-libvips-linux-riscv64": "1.2.4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@img/sharp-linux-s390x": {
|
"node_modules/@img/sharp-linux-s390x": {
|
||||||
"version": "0.35.5",
|
"version": "0.34.5",
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz",
|
"resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.5.tgz",
|
||||||
"integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==",
|
"integrity": "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"s390x"
|
"s390x"
|
||||||
],
|
],
|
||||||
@@ -449,19 +430,19 @@
|
|||||||
"linux"
|
"linux"
|
||||||
],
|
],
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20.9.0"
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://opencollective.com/libvips"
|
"url": "https://opencollective.com/libvips"
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@img/sharp-libvips-linux-s390x": "1.3.4"
|
"@img/sharp-libvips-linux-s390x": "1.2.4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@img/sharp-linux-x64": {
|
"node_modules/@img/sharp-linux-x64": {
|
||||||
"version": "0.35.5",
|
"version": "0.34.5",
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz",
|
"resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz",
|
||||||
"integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==",
|
"integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -474,19 +455,19 @@
|
|||||||
"linux"
|
"linux"
|
||||||
],
|
],
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20.9.0"
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://opencollective.com/libvips"
|
"url": "https://opencollective.com/libvips"
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@img/sharp-libvips-linux-x64": "1.3.4"
|
"@img/sharp-libvips-linux-x64": "1.2.4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@img/sharp-linuxmusl-arm64": {
|
"node_modules/@img/sharp-linuxmusl-arm64": {
|
||||||
"version": "0.35.5",
|
"version": "0.34.5",
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz",
|
"resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz",
|
||||||
"integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==",
|
"integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -499,19 +480,19 @@
|
|||||||
"linux"
|
"linux"
|
||||||
],
|
],
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20.9.0"
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://opencollective.com/libvips"
|
"url": "https://opencollective.com/libvips"
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@img/sharp-libvips-linuxmusl-arm64": "1.3.4"
|
"@img/sharp-libvips-linuxmusl-arm64": "1.2.4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@img/sharp-linuxmusl-x64": {
|
"node_modules/@img/sharp-linuxmusl-x64": {
|
||||||
"version": "0.35.5",
|
"version": "0.34.5",
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz",
|
"resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz",
|
||||||
"integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==",
|
"integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -524,54 +505,38 @@
|
|||||||
"linux"
|
"linux"
|
||||||
],
|
],
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20.9.0"
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://opencollective.com/libvips"
|
"url": "https://opencollective.com/libvips"
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@img/sharp-libvips-linuxmusl-x64": "1.3.4"
|
"@img/sharp-libvips-linuxmusl-x64": "1.2.4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@img/sharp-wasm32": {
|
"node_modules/@img/sharp-wasm32": {
|
||||||
"version": "0.35.5",
|
"version": "0.34.5",
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz",
|
"resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.5.tgz",
|
||||||
"integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==",
|
"integrity": "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==",
|
||||||
"license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
|
|
||||||
"optional": true,
|
|
||||||
"dependencies": {
|
|
||||||
"@emnapi/runtime": "^1.11.3"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20.9.0"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://opencollective.com/libvips"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@img/sharp-webcontainers-wasm32": {
|
|
||||||
"version": "0.35.5",
|
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz",
|
|
||||||
"integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==",
|
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"wasm32"
|
"wasm32"
|
||||||
],
|
],
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@img/sharp-wasm32": "0.35.5"
|
"@emnapi/runtime": "^1.7.0"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20.9.0"
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://opencollective.com/libvips"
|
"url": "https://opencollective.com/libvips"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@img/sharp-win32-arm64": {
|
"node_modules/@img/sharp-win32-arm64": {
|
||||||
"version": "0.35.5",
|
"version": "0.34.5",
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz",
|
"resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz",
|
||||||
"integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==",
|
"integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -581,16 +546,16 @@
|
|||||||
"win32"
|
"win32"
|
||||||
],
|
],
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20.9.0"
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://opencollective.com/libvips"
|
"url": "https://opencollective.com/libvips"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@img/sharp-win32-ia32": {
|
"node_modules/@img/sharp-win32-ia32": {
|
||||||
"version": "0.35.5",
|
"version": "0.34.5",
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz",
|
"resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.5.tgz",
|
||||||
"integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==",
|
"integrity": "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"ia32"
|
"ia32"
|
||||||
],
|
],
|
||||||
@@ -600,16 +565,16 @@
|
|||||||
"win32"
|
"win32"
|
||||||
],
|
],
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "^20.9.0"
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://opencollective.com/libvips"
|
"url": "https://opencollective.com/libvips"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@img/sharp-win32-x64": {
|
"node_modules/@img/sharp-win32-x64": {
|
||||||
"version": "0.35.5",
|
"version": "0.34.5",
|
||||||
"resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz",
|
"resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz",
|
||||||
"integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==",
|
"integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -619,7 +584,7 @@
|
|||||||
"win32"
|
"win32"
|
||||||
],
|
],
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20.9.0"
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://opencollective.com/libvips"
|
"url": "https://opencollective.com/libvips"
|
||||||
@@ -1107,7 +1072,6 @@
|
|||||||
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
|
||||||
"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
|
"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"optional": true,
|
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=8"
|
"node": ">=8"
|
||||||
}
|
}
|
||||||
@@ -1537,7 +1501,6 @@
|
|||||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
|
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
|
||||||
"integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
|
"integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"optional": true,
|
|
||||||
"bin": {
|
"bin": {
|
||||||
"semver": "bin/semver.js"
|
"semver": "bin/semver.js"
|
||||||
},
|
},
|
||||||
@@ -1546,53 +1509,47 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/sharp": {
|
"node_modules/sharp": {
|
||||||
"version": "0.35.5",
|
"version": "0.34.5",
|
||||||
"resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz",
|
"resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz",
|
||||||
"integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==",
|
"integrity": "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==",
|
||||||
|
"hasInstallScript": true,
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"optional": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@img/colour": "^1.1.0",
|
"@img/colour": "^1.0.0",
|
||||||
"detect-libc": "^2.1.2",
|
"detect-libc": "^2.1.2",
|
||||||
"semver": "^7.8.5"
|
"semver": "^7.7.3"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20.9.0"
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://opencollective.com/libvips"
|
"url": "https://opencollective.com/libvips"
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@img/sharp-darwin-arm64": "0.35.5",
|
"@img/sharp-darwin-arm64": "0.34.5",
|
||||||
"@img/sharp-darwin-x64": "0.35.5",
|
"@img/sharp-darwin-x64": "0.34.5",
|
||||||
"@img/sharp-freebsd-wasm32": "0.35.5",
|
"@img/sharp-libvips-darwin-arm64": "1.2.4",
|
||||||
"@img/sharp-libvips-darwin-arm64": "1.3.4",
|
"@img/sharp-libvips-darwin-x64": "1.2.4",
|
||||||
"@img/sharp-libvips-darwin-x64": "1.3.4",
|
"@img/sharp-libvips-linux-arm": "1.2.4",
|
||||||
"@img/sharp-libvips-linux-arm": "1.3.4",
|
"@img/sharp-libvips-linux-arm64": "1.2.4",
|
||||||
"@img/sharp-libvips-linux-arm64": "1.3.4",
|
"@img/sharp-libvips-linux-ppc64": "1.2.4",
|
||||||
"@img/sharp-libvips-linux-ppc64": "1.3.4",
|
"@img/sharp-libvips-linux-riscv64": "1.2.4",
|
||||||
"@img/sharp-libvips-linux-riscv64": "1.3.4",
|
"@img/sharp-libvips-linux-s390x": "1.2.4",
|
||||||
"@img/sharp-libvips-linux-s390x": "1.3.4",
|
"@img/sharp-libvips-linux-x64": "1.2.4",
|
||||||
"@img/sharp-libvips-linux-x64": "1.3.4",
|
"@img/sharp-libvips-linuxmusl-arm64": "1.2.4",
|
||||||
"@img/sharp-libvips-linuxmusl-arm64": "1.3.4",
|
"@img/sharp-libvips-linuxmusl-x64": "1.2.4",
|
||||||
"@img/sharp-libvips-linuxmusl-x64": "1.3.4",
|
"@img/sharp-linux-arm": "0.34.5",
|
||||||
"@img/sharp-linux-arm": "0.35.5",
|
"@img/sharp-linux-arm64": "0.34.5",
|
||||||
"@img/sharp-linux-arm64": "0.35.5",
|
"@img/sharp-linux-ppc64": "0.34.5",
|
||||||
"@img/sharp-linux-ppc64": "0.35.5",
|
"@img/sharp-linux-riscv64": "0.34.5",
|
||||||
"@img/sharp-linux-riscv64": "0.35.5",
|
"@img/sharp-linux-s390x": "0.34.5",
|
||||||
"@img/sharp-linux-s390x": "0.35.5",
|
"@img/sharp-linux-x64": "0.34.5",
|
||||||
"@img/sharp-linux-x64": "0.35.5",
|
"@img/sharp-linuxmusl-arm64": "0.34.5",
|
||||||
"@img/sharp-linuxmusl-arm64": "0.35.5",
|
"@img/sharp-linuxmusl-x64": "0.34.5",
|
||||||
"@img/sharp-linuxmusl-x64": "0.35.5",
|
"@img/sharp-wasm32": "0.34.5",
|
||||||
"@img/sharp-webcontainers-wasm32": "0.35.5",
|
"@img/sharp-win32-arm64": "0.34.5",
|
||||||
"@img/sharp-win32-arm64": "0.35.5",
|
"@img/sharp-win32-ia32": "0.34.5",
|
||||||
"@img/sharp-win32-ia32": "0.35.5",
|
"@img/sharp-win32-x64": "0.34.5"
|
||||||
"@img/sharp-win32-x64": "0.35.5"
|
|
||||||
},
|
|
||||||
"peerDependenciesMeta": {
|
|
||||||
"@types/node": {
|
|
||||||
"optional": true
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/source-map-js": {
|
"node_modules/source-map-js": {
|
||||||
|
|||||||
+2
-1
@@ -21,7 +21,8 @@
|
|||||||
"next-auth": "5.0.0-beta.32",
|
"next-auth": "5.0.0-beta.32",
|
||||||
"prisma": "^6.19.3",
|
"prisma": "^6.19.3",
|
||||||
"react": "^19.1.0",
|
"react": "^19.1.0",
|
||||||
"react-dom": "^19.1.0"
|
"react-dom": "^19.1.0",
|
||||||
|
"sharp": "^0.34.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/leaflet": "^1.9.20",
|
"@types/leaflet": "^1.9.20",
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "TrashItem" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"ownerId" TEXT NOT NULL,
|
||||||
|
"bookId" TEXT,
|
||||||
|
"kind" TEXT NOT NULL,
|
||||||
|
"label" TEXT NOT NULL,
|
||||||
|
"detail" TEXT,
|
||||||
|
"payload" JSONB,
|
||||||
|
"file" TEXT,
|
||||||
|
"deletedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "TrashItem_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "EntityVersion" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"bookId" TEXT NOT NULL,
|
||||||
|
"entityId" TEXT NOT NULL,
|
||||||
|
"userId" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"snapshot" JSONB NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "EntityVersion_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "BackupRun" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"trigger" TEXT NOT NULL,
|
||||||
|
"status" TEXT NOT NULL,
|
||||||
|
"startedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"finishedAt" TIMESTAMP(3),
|
||||||
|
"books" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"megabytes" DOUBLE PRECISION NOT NULL DEFAULT 0,
|
||||||
|
"folder" TEXT,
|
||||||
|
"error" TEXT,
|
||||||
|
|
||||||
|
CONSTRAINT "BackupRun_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "TrashItem_ownerId_idx" ON "TrashItem"("ownerId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "TrashItem_bookId_idx" ON "TrashItem"("bookId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "TrashItem_deletedAt_idx" ON "TrashItem"("deletedAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "EntityVersion_entityId_createdAt_idx" ON "EntityVersion"("entityId", "createdAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "EntityVersion_bookId_idx" ON "EntityVersion"("bookId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "BackupRun_startedAt_idx" ON "BackupRun"("startedAt");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "TrashItem" ADD CONSTRAINT "TrashItem_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "EntityVersion" ADD CONSTRAINT "EntityVersion_bookId_fkey" FOREIGN KEY ("bookId") REFERENCES "Book"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
@@ -44,6 +44,7 @@ model User {
|
|||||||
name String?
|
name String?
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
books Book[]
|
books Book[]
|
||||||
|
trash TrashItem[]
|
||||||
}
|
}
|
||||||
|
|
||||||
model Book {
|
model Book {
|
||||||
@@ -63,6 +64,7 @@ model Book {
|
|||||||
maps BookMap[]
|
maps BookMap[]
|
||||||
templates Template[]
|
templates Template[]
|
||||||
counters IdCounter[]
|
counters IdCounter[]
|
||||||
|
versions EntityVersion[]
|
||||||
|
|
||||||
@@index([ownerId])
|
@@index([ownerId])
|
||||||
}
|
}
|
||||||
@@ -229,3 +231,53 @@ model NameStat {
|
|||||||
|
|
||||||
@@id([kind, year])
|
@@id([kind, year])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Borttagna poster och böcker. Posten sparas som en ögonblicksbild (payload) och boken som en zip-fil (file)
|
||||||
|
// tills den återställs eller rensas efter 30 dagar.
|
||||||
|
model TrashItem {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
ownerId String
|
||||||
|
bookId String? // boken en post hörde till, tom för borttagna böcker
|
||||||
|
kind String // "entity" eller "book"
|
||||||
|
label String
|
||||||
|
detail String? // t.ex. typ av post
|
||||||
|
payload Json?
|
||||||
|
file String?
|
||||||
|
deletedAt DateTime @default(now())
|
||||||
|
|
||||||
|
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@index([ownerId])
|
||||||
|
@@index([bookId])
|
||||||
|
@@index([deletedAt])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tidigare versioner av en post. entityId är medvetet ingen främmande nyckel, så att historiken överlever
|
||||||
|
// att posten flyttas till papperskorgen.
|
||||||
|
model EntityVersion {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
bookId String
|
||||||
|
entityId String
|
||||||
|
userId String?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
snapshot Json
|
||||||
|
|
||||||
|
book Book @relation(fields: [bookId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@index([entityId, createdAt])
|
||||||
|
@@index([bookId])
|
||||||
|
}
|
||||||
|
|
||||||
|
model BackupRun {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
trigger String // "schedule" eller "manual"
|
||||||
|
status String // "running", "ok" eller "error"
|
||||||
|
startedAt DateTime @default(now())
|
||||||
|
finishedAt DateTime?
|
||||||
|
books Int @default(0)
|
||||||
|
megabytes Float @default(0)
|
||||||
|
folder String?
|
||||||
|
error String?
|
||||||
|
|
||||||
|
@@index([startedAt])
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { runBackup } from "@/lib/backup";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { log } from "@/lib/log";
|
||||||
|
import { requireAdmin } from "@/lib/session";
|
||||||
|
|
||||||
|
/** Startar en säkerhetskopiering i bakgrunden. Sidan visar status när den laddas om. */
|
||||||
|
export async function runBackupNow() {
|
||||||
|
const user = await requireAdmin();
|
||||||
|
const running = await prisma.backupRun.findFirst({ where: { status: "running", startedAt: { gte: new Date(Date.now() - 60 * 60 * 1000) } } });
|
||||||
|
if (!running) {
|
||||||
|
log.info("Manuell säkerhetskopiering begärd", { userId: user.id });
|
||||||
|
void runBackup("manual").catch((error) => log.error("Manuell säkerhetskopiering misslyckades", { error }));
|
||||||
|
}
|
||||||
|
redirect("/admin?started=1");
|
||||||
|
}
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
import { prisma } from "@/lib/db";
|
import { prisma } from "@/lib/db";
|
||||||
import { deleteImage } from "@/lib/files";
|
import { trashBook } from "@/lib/trash";
|
||||||
import { optStr, revalidateBook, str } from "@/lib/form";
|
import { optStr, revalidateBook, str } from "@/lib/form";
|
||||||
import { requireBook, requireUser } from "@/lib/session";
|
import { requireBook, requireUser } from "@/lib/session";
|
||||||
|
|
||||||
@@ -43,12 +43,8 @@ export async function updateBook(formData: FormData) {
|
|||||||
|
|
||||||
export async function deleteBook(formData: FormData) {
|
export async function deleteBook(formData: FormData) {
|
||||||
const book = await requireBook(str(formData, "bookId"));
|
const book = await requireBook(str(formData, "bookId"));
|
||||||
const [entities, maps] = await Promise.all([
|
// Boken flyttas till papperskorgen (som zip med bilder) och kan återställas i 30 dagar
|
||||||
prisma.entity.findMany({ where: { bookId: book.id, imageFile: { not: null } }, select: { imageFile: true } }),
|
await trashBook(book.ownerId, book.id);
|
||||||
prisma.bookMap.findMany({ where: { bookId: book.id, imageFile: { not: null } }, select: { imageFile: true } }),
|
|
||||||
]);
|
|
||||||
await prisma.book.delete({ where: { id: book.id } });
|
|
||||||
await Promise.all([...entities, ...maps].map((row) => deleteImage(row.imageFile)));
|
|
||||||
revalidatePath("/");
|
revalidatePath("/");
|
||||||
redirect("/");
|
redirect("/");
|
||||||
}
|
}
|
||||||
+11
-2
@@ -4,11 +4,14 @@ import type { Prisma } from "@prisma/client";
|
|||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { prisma } from "@/lib/db";
|
import { prisma } from "@/lib/db";
|
||||||
import { deleteImage, isUpload, saveImage } from "@/lib/files";
|
import { deleteImage, isUpload, saveImage } from "@/lib/files";
|
||||||
|
import { recordVersion, sameSnapshot, snapshotOf } from "@/lib/history";
|
||||||
import { optStr, parseTags, revalidateBook, str } from "@/lib/form";
|
import { optStr, parseTags, revalidateBook, str } from "@/lib/form";
|
||||||
import { collectFieldData } from "@/lib/field-values";
|
import { collectFieldData } from "@/lib/field-values";
|
||||||
import { KIND_INFO, parseKind } from "@/lib/kinds";
|
import { KIND_INFO, parseKind } from "@/lib/kinds";
|
||||||
import { nextEntityCode } from "@/lib/ids";
|
import { nextEntityCode } from "@/lib/ids";
|
||||||
import { requireBook, requireEntity } from "@/lib/session";
|
import { requireBook, requireEntity } from "@/lib/session";
|
||||||
|
import { withinQuota } from "@/lib/storage";
|
||||||
|
import { trashEntity } from "@/lib/trash";
|
||||||
import { getTemplate } from "@/lib/templates";
|
import { getTemplate } from "@/lib/templates";
|
||||||
import { getLocale } from "@/i18n/server";
|
import { getLocale } from "@/i18n/server";
|
||||||
|
|
||||||
@@ -28,6 +31,9 @@ export async function saveEntity(formData: FormData) {
|
|||||||
let imageFile = existing?.imageFile ?? null;
|
let imageFile = existing?.imageFile ?? null;
|
||||||
const upload = formData.get("image");
|
const upload = formData.get("image");
|
||||||
if (isUpload(upload)) {
|
if (isUpload(upload)) {
|
||||||
|
if (!(await withinQuota(book.ownerId, upload.size))) {
|
||||||
|
redirect(existing ? `/books/${book.id}/entity/${existing.id}/edit?error=quota` : `/books/${book.id}/e/${KIND_INFO[kind].slug}/new?error=quota`);
|
||||||
|
}
|
||||||
const saved = await saveImage(upload);
|
const saved = await saveImage(upload);
|
||||||
await deleteImage(imageFile);
|
await deleteImage(imageFile);
|
||||||
imageFile = saved;
|
imageFile = saved;
|
||||||
@@ -47,6 +53,9 @@ export async function saveEntity(formData: FormData) {
|
|||||||
// ID skapas automatiskt vid första sparningen och ändras aldrig därefter
|
// ID skapas automatiskt vid första sparningen och ändras aldrig därefter
|
||||||
const saved = await prisma.$transaction(async (tx) => {
|
const saved = await prisma.$transaction(async (tx) => {
|
||||||
if (existing) {
|
if (existing) {
|
||||||
|
// Den tidigare versionen sparas bara om något faktiskt ändrats
|
||||||
|
const before = snapshotOf(existing);
|
||||||
|
if (!sameSnapshot(before, snapshotOf(values))) await recordVersion(tx, book.id, existing.id, book.ownerId, before);
|
||||||
const code = existing.code ?? (await nextEntityCode(book.id, kind, tx));
|
const code = existing.code ?? (await nextEntityCode(book.id, kind, tx));
|
||||||
return tx.entity.update({ where: { id: existing.id }, data: { ...values, code } });
|
return tx.entity.update({ where: { id: existing.id }, data: { ...values, code } });
|
||||||
}
|
}
|
||||||
@@ -61,8 +70,8 @@ export async function saveEntity(formData: FormData) {
|
|||||||
export async function deleteEntity(formData: FormData) {
|
export async function deleteEntity(formData: FormData) {
|
||||||
const book = await requireBook(str(formData, "bookId"));
|
const book = await requireBook(str(formData, "bookId"));
|
||||||
const entity = await requireEntity(book.id, str(formData, "id"));
|
const entity = await requireEntity(book.id, str(formData, "id"));
|
||||||
await prisma.entity.delete({ where: { id: entity.id } });
|
// Posten flyttas till papperskorgen och kan återställas i 30 dagar
|
||||||
await deleteImage(entity.imageFile);
|
await trashEntity(book.ownerId, book.id, entity.id);
|
||||||
revalidateBook(book.id);
|
revalidateBook(book.id);
|
||||||
redirect(`/books/${book.id}/e/${KIND_INFO[entity.kind].slug}`);
|
redirect(`/books/${book.id}/e/${KIND_INFO[entity.kind].slug}`);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import type { Prisma } from "@prisma/client";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { str, revalidateBook } from "@/lib/form";
|
||||||
|
import { recordVersion, sameSnapshot, snapshotOf, type Snapshot } from "@/lib/history";
|
||||||
|
import { requireBook, requireEntity } from "@/lib/session";
|
||||||
|
|
||||||
|
/** Återställer en tidigare version. Den nuvarande versionen sparas först i historiken, så åtgärden kan ångras. */
|
||||||
|
export async function restoreVersion(formData: FormData) {
|
||||||
|
const bookId = str(formData, "bookId");
|
||||||
|
const book = await requireBook(bookId);
|
||||||
|
const entity = await requireEntity(bookId, str(formData, "entityId"));
|
||||||
|
const version = await prisma.entityVersion.findFirst({ where: { id: str(formData, "versionId"), entityId: entity.id, bookId } });
|
||||||
|
if (!version) redirect(`/books/${bookId}/entity/${entity.id}/history`);
|
||||||
|
|
||||||
|
const target = version.snapshot as unknown as Snapshot;
|
||||||
|
const current = snapshotOf(entity);
|
||||||
|
await prisma.$transaction(async (tx) => {
|
||||||
|
if (!sameSnapshot(current, target)) await recordVersion(tx, bookId, entity.id, book.ownerId, current);
|
||||||
|
await tx.entity.update({
|
||||||
|
where: { id: entity.id },
|
||||||
|
data: { name: target.name, summary: target.summary, tags: target.tags, data: (target.data ?? {}) as Prisma.InputJsonObject },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
revalidateBook(bookId);
|
||||||
|
redirect(`/books/${bookId}/entity/${entity.id}`);
|
||||||
|
}
|
||||||
+3
-1
@@ -7,6 +7,7 @@ import { revalidateBook, str } from "@/lib/form";
|
|||||||
import { MARKER_COLORS } from "@/lib/kinds";
|
import { MARKER_COLORS } from "@/lib/kinds";
|
||||||
import { nextMapCode, nextMarkerCode } from "@/lib/ids";
|
import { nextMapCode, nextMarkerCode } from "@/lib/ids";
|
||||||
import { requireBook } from "@/lib/session";
|
import { requireBook } from "@/lib/session";
|
||||||
|
import { withinQuota } from "@/lib/storage";
|
||||||
|
|
||||||
async function requireMap(bookId: string, mapId: string) {
|
async function requireMap(bookId: string, mapId: string) {
|
||||||
const book = await requireBook(bookId);
|
const book = await requireBook(bookId);
|
||||||
@@ -25,7 +26,8 @@ export async function createMap(formData: FormData) {
|
|||||||
if (kind === "IMAGE") {
|
if (kind === "IMAGE") {
|
||||||
const upload = formData.get("image");
|
const upload = formData.get("image");
|
||||||
if (!isUpload(upload)) return;
|
if (!isUpload(upload)) return;
|
||||||
imageFile = await saveImage(upload);
|
if (!(await withinQuota(book.ownerId, upload.size))) redirect(`/books/${book.id}/maps?error=quota`);
|
||||||
|
imageFile = await saveImage(upload, "map");
|
||||||
}
|
}
|
||||||
|
|
||||||
const code = await nextMapCode(book.id, kind);
|
const code = await nextMapCode(book.id, kind);
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { str } from "@/lib/form";
|
||||||
|
import { emptyBookTrash, purgeTrashItem, restoreBook, restoreEntity } from "@/lib/trash";
|
||||||
|
import { requireBook, requireUser } from "@/lib/session";
|
||||||
|
|
||||||
|
export async function restoreTrashEntity(formData: FormData) {
|
||||||
|
const user = await requireUser();
|
||||||
|
const restored = await restoreEntity(user.id, str(formData, "id"));
|
||||||
|
if (!restored) redirect(`/books/${str(formData, "bookId")}/trash?restore=failed`);
|
||||||
|
revalidatePath(`/books/${restored.bookId}`, "layout");
|
||||||
|
redirect(`/books/${restored.bookId}/entity/${restored.entityId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function restoreTrashBook(formData: FormData) {
|
||||||
|
const user = await requireUser();
|
||||||
|
const bookId = await restoreBook(user.id, str(formData, "id"));
|
||||||
|
if (!bookId) redirect("/?restore=failed");
|
||||||
|
revalidatePath("/");
|
||||||
|
redirect(`/books/${bookId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function purgeTrash(formData: FormData) {
|
||||||
|
const user = await requireUser();
|
||||||
|
await purgeTrashItem(user.id, str(formData, "id"));
|
||||||
|
revalidatePath("/");
|
||||||
|
const bookId = str(formData, "bookId");
|
||||||
|
if (bookId) revalidatePath(`/books/${bookId}/trash`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function emptyTrash(formData: FormData) {
|
||||||
|
const book = await requireBook(str(formData, "bookId"));
|
||||||
|
await emptyBookTrash(book.ownerId, book.id);
|
||||||
|
revalidatePath(`/books/${book.id}/trash`);
|
||||||
|
}
|
||||||
+40
-2
@@ -1,6 +1,10 @@
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { IconBook2 } from "@tabler/icons-react";
|
import { IconBook2 } from "@tabler/icons-react";
|
||||||
|
import { IconArrowBackUp } from "@tabler/icons-react";
|
||||||
import { createBook } from "@/actions/books";
|
import { createBook } from "@/actions/books";
|
||||||
|
import { purgeTrash, restoreTrashBook } from "@/actions/trash";
|
||||||
|
import { ConfirmSubmit } from "@/components/confirm-submit";
|
||||||
|
import { TRASH_DAYS } from "@/lib/trash";
|
||||||
import { IMPORT_ERROR_CODES, type ImportErrorCode } from "@/lib/book-transfer";
|
import { IMPORT_ERROR_CODES, type ImportErrorCode } from "@/lib/book-transfer";
|
||||||
import { EmptyState, PageBody, PageHeader } from "@/components/page";
|
import { EmptyState, PageBody, PageHeader } from "@/components/page";
|
||||||
import { getT } from "@/i18n/server";
|
import { getT } from "@/i18n/server";
|
||||||
@@ -12,9 +16,9 @@ export const metadata = { title: "Mina böcker" };
|
|||||||
export default async function BooksPage({
|
export default async function BooksPage({
|
||||||
searchParams,
|
searchParams,
|
||||||
}: {
|
}: {
|
||||||
searchParams: Promise<{ importError?: string; detail?: string }>;
|
searchParams: Promise<{ importError?: string; detail?: string; restore?: string }>;
|
||||||
}) {
|
}) {
|
||||||
const { importError, detail } = await searchParams;
|
const { importError, detail, restore } = await searchParams;
|
||||||
const user = await requireUser();
|
const user = await requireUser();
|
||||||
const { t } = await getT();
|
const { t } = await getT();
|
||||||
const books = await prisma.book.findMany({
|
const books = await prisma.book.findMany({
|
||||||
@@ -22,11 +26,13 @@ export default async function BooksPage({
|
|||||||
orderBy: { updatedAt: "desc" },
|
orderBy: { updatedAt: "desc" },
|
||||||
include: { _count: { select: { entities: true } } },
|
include: { _count: { select: { entities: true } } },
|
||||||
});
|
});
|
||||||
|
const trashedBooks = await prisma.trashItem.findMany({ where: { ownerId: user.id, kind: "book" }, orderBy: { deletedAt: "desc" } });
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<PageHeader title={t("books.title")} />
|
<PageHeader title={t("books.title")} />
|
||||||
<PageBody>
|
<PageBody>
|
||||||
|
{restore === "failed" ? <div className="alert alert-warning">{t("trash.restoreFailed")}</div> : null}
|
||||||
{importError ? (
|
{importError ? (
|
||||||
<div className="alert alert-danger">
|
<div className="alert alert-danger">
|
||||||
{t("import.failed", {
|
{t("import.failed", {
|
||||||
@@ -111,6 +117,38 @@ export default async function BooksPage({
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
|
{trashedBooks.length > 0 ? (
|
||||||
|
<div className="card mt-3">
|
||||||
|
<div className="card-header">
|
||||||
|
<h3 className="card-title">{t("trash.books")}</h3>
|
||||||
|
</div>
|
||||||
|
<div className="card-body text-secondary pb-0">{t("trash.intro", { days: TRASH_DAYS })}</div>
|
||||||
|
<div className="list-group list-group-flush">
|
||||||
|
{trashedBooks.map((item) => (
|
||||||
|
<div key={item.id} className="list-group-item d-flex align-items-center gap-2">
|
||||||
|
<div className="flex-fill min-w-0">
|
||||||
|
<div className="fw-bold text-truncate">{item.label}</div>
|
||||||
|
<div className="text-secondary small">{t("books.items", { n: item.detail ?? 0 })}</div>
|
||||||
|
</div>
|
||||||
|
<form action={restoreTrashBook}>
|
||||||
|
<input type="hidden" name="id" value={item.id} />
|
||||||
|
<button type="submit" className="btn btn-sm">
|
||||||
|
<IconArrowBackUp size={16} className="me-1" />
|
||||||
|
{t("trash.restore")}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
<form action={purgeTrash}>
|
||||||
|
<input type="hidden" name="id" value={item.id} />
|
||||||
|
<ConfirmSubmit className="btn btn-sm btn-outline-danger" message={t("trash.purgeConfirm")}>
|
||||||
|
{t("trash.purge")}
|
||||||
|
</ConfirmSubmit>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</PageBody>
|
</PageBody>
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { Shell } from "@/components/shell";
|
||||||
|
import { requireAdmin } from "@/lib/session";
|
||||||
|
|
||||||
|
export default async function AdminLayout({ children }: { children: React.ReactNode }) {
|
||||||
|
const user = await requireAdmin();
|
||||||
|
return <Shell user={user}>{children}</Shell>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import { IconDatabaseExport, IconDownload, IconRefresh } from "@tabler/icons-react";
|
||||||
|
import { runBackupNow } from "@/actions/admin";
|
||||||
|
import { PageBody, PageHeader } from "@/components/page";
|
||||||
|
import { getT } from "@/i18n/server";
|
||||||
|
import { formatBytes, formatDuration } from "@/lib/format";
|
||||||
|
import { checkExternalServices, collectStats } from "@/lib/system-stats";
|
||||||
|
|
||||||
|
export const metadata = { title: "Administration" };
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
const STATUS_BADGE: Record<string, string> = { ok: "bg-green-lt", error: "bg-red-lt", running: "bg-blue-lt" };
|
||||||
|
|
||||||
|
export default async function AdminPage({ searchParams }: { searchParams: Promise<{ started?: string; check?: string }> }) {
|
||||||
|
const { started, check } = await searchParams;
|
||||||
|
const { t } = await getT();
|
||||||
|
const [s, services] = await Promise.all([collectStats(), check ? checkExternalServices() : Promise.resolve(null)]);
|
||||||
|
const last = s.backup.lastRun;
|
||||||
|
|
||||||
|
const rows = (items: [string, string][]) => (
|
||||||
|
<dl className="mb-0">
|
||||||
|
{items.map(([label, value]) => (
|
||||||
|
<div className="row mb-2" key={label}>
|
||||||
|
<dt className="col-sm-5 text-secondary fw-normal">{label}</dt>
|
||||||
|
<dd className="col-sm-7 mb-0">{value}</dd>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</dl>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<PageHeader title={t("admin.title")} />
|
||||||
|
<PageBody>
|
||||||
|
<p className="text-secondary">{t("admin.intro")}</p>
|
||||||
|
{started ? <div className="alert alert-info">{t("admin.backupStarted")}</div> : null}
|
||||||
|
|
||||||
|
<div className="row row-cards">
|
||||||
|
<div className="col-lg-6">
|
||||||
|
<div className="card">
|
||||||
|
<div className="card-header">
|
||||||
|
<h3 className="card-title">{t("admin.system")}</h3>
|
||||||
|
</div>
|
||||||
|
<div className="card-body">
|
||||||
|
{rows([
|
||||||
|
[t("admin.version"), s.version],
|
||||||
|
[t("admin.node"), s.node],
|
||||||
|
[t("admin.uptime"), formatDuration(s.uptimeSeconds)],
|
||||||
|
[t("admin.memory"), formatBytes(s.memory.rss)],
|
||||||
|
])}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="col-lg-6">
|
||||||
|
<div className="card">
|
||||||
|
<div className="card-header">
|
||||||
|
<h3 className="card-title">{t("admin.data")}</h3>
|
||||||
|
</div>
|
||||||
|
<div className="card-body">
|
||||||
|
{rows([
|
||||||
|
[t("admin.users"), String(s.counts.users)],
|
||||||
|
[t("admin.books"), String(s.counts.books)],
|
||||||
|
[t("admin.entities"), String(s.counts.entities)],
|
||||||
|
[t("admin.relations"), String(s.counts.relations)],
|
||||||
|
[t("admin.maps"), `${s.counts.maps} (${s.counts.markers} ${t("admin.markers").toLowerCase()})`],
|
||||||
|
[t("admin.dbSize"), formatBytes(s.database.bytes)],
|
||||||
|
[t("admin.uploads"), `${s.uploads.files} · ${formatBytes(s.uploads.bytes)}`],
|
||||||
|
[t("admin.thumbs"), `${s.thumbs.files} · ${formatBytes(s.thumbs.bytes)}`],
|
||||||
|
[t("admin.trash"), t("admin.trashSummary", { entities: s.trash.entities, books: s.trash.books, days: s.trash.days })],
|
||||||
|
])}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="col-12">
|
||||||
|
<div className="card">
|
||||||
|
<div className="card-header">
|
||||||
|
<h3 className="card-title">{t("admin.backup")}</h3>
|
||||||
|
<div className="card-actions">
|
||||||
|
<form action={runBackupNow}>
|
||||||
|
<button type="submit" className="btn btn-primary btn-sm">
|
||||||
|
<IconDatabaseExport size={16} className="me-1" />
|
||||||
|
{t("admin.backupNow")}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="card-body">
|
||||||
|
<p className="text-secondary mb-2">
|
||||||
|
{t("admin.backupSettings", {
|
||||||
|
enabled: s.backup.enabled ? t("admin.backupOn") : t("admin.backupOff"),
|
||||||
|
hour: s.backup.hour,
|
||||||
|
keep: s.backup.keep,
|
||||||
|
dir: s.backup.dir,
|
||||||
|
})}
|
||||||
|
</p>
|
||||||
|
<p className="mb-0">
|
||||||
|
<span className="text-secondary">{t("admin.backupLast")}: </span>
|
||||||
|
{last ? (
|
||||||
|
<>
|
||||||
|
{last.startedAt.toISOString().slice(0, 16).replace("T", " ")}{" "}
|
||||||
|
<span className={`badge ${STATUS_BADGE[last.status] ?? ""}`}>{t(`admin.backupStatus.${last.status}`)}</span>
|
||||||
|
{last.status === "ok" ? (
|
||||||
|
<span className="text-secondary"> · {last.books} {t("admin.books").toLowerCase()}, {formatBytes(last.megabytes * 1048576)}</span>
|
||||||
|
) : null}
|
||||||
|
{last.error ? <span className="text-danger"> · {last.error}</span> : null}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
t("admin.backupNever")
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{s.backup.folders.length === 0 ? (
|
||||||
|
<div className="card-body border-top text-secondary">{t("admin.backupNone")}</div>
|
||||||
|
) : (
|
||||||
|
<div className="table-responsive border-top">
|
||||||
|
<table className="table table-vcenter card-table">
|
||||||
|
<tbody>
|
||||||
|
{s.backup.folders.map((folder) => (
|
||||||
|
<tr key={folder.folder}>
|
||||||
|
<td className="text-nowrap fw-bold">{folder.folder.replace("T", " ").replace(/-(\d\d)-(\d\d)$/, ":$1:$2")}</td>
|
||||||
|
<td className="text-secondary text-nowrap">
|
||||||
|
{t("admin.backupFiles", { n: folder.files.length })} · {formatBytes(folder.bytes)}
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
{folder.files.map((file) => (
|
||||||
|
<a
|
||||||
|
key={file.name}
|
||||||
|
href={`/api/admin/backups/${folder.folder}/${file.name}`}
|
||||||
|
className="badge bg-azure-lt me-1 mb-1 text-decoration-none"
|
||||||
|
title={formatBytes(file.bytes)}
|
||||||
|
>
|
||||||
|
<IconDownload size={12} className="me-1" />
|
||||||
|
{file.name}
|
||||||
|
</a>
|
||||||
|
))}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="card-footer text-secondary small">{t("admin.backupHelp")}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="col-lg-6">
|
||||||
|
<div className="card">
|
||||||
|
<div className="card-header">
|
||||||
|
<h3 className="card-title">{t("admin.services")}</h3>
|
||||||
|
<div className="card-actions">
|
||||||
|
<Link href="/admin?check=1" className="btn btn-sm">
|
||||||
|
<IconRefresh size={16} className="me-1" />
|
||||||
|
{t("admin.check")}
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="card-body">
|
||||||
|
<p className="text-secondary">{t("admin.servicesHelp")}</p>
|
||||||
|
{services
|
||||||
|
? services.map((svc) => (
|
||||||
|
<div key={svc.name} className="d-flex align-items-center gap-2 mb-1">
|
||||||
|
<span className={`badge ${svc.ok ? "bg-green-lt" : "bg-red-lt"}`}>{svc.ok ? "OK" : "Fel"}</span>
|
||||||
|
<span>{svc.name}</span>
|
||||||
|
<span className="text-secondary small ms-auto">
|
||||||
|
{svc.detail} · {svc.ms} ms
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
: null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="col-lg-6">
|
||||||
|
<div className="card">
|
||||||
|
<div className="card-header">
|
||||||
|
<h3 className="card-title">{t("admin.observability")}</h3>
|
||||||
|
</div>
|
||||||
|
<div className="card-body">
|
||||||
|
{rows([
|
||||||
|
[t("admin.logLevel"), `${process.env.LOG_LEVEL ?? "info"} (${process.env.NODE_ENV === "production" ? "JSON" : "text"})`],
|
||||||
|
["/api/metrics", process.env.METRICS_TOKEN ? t("admin.metricsOn") : t("admin.metricsOff")],
|
||||||
|
])}
|
||||||
|
<div className="text-secondary small mt-2">{t("admin.rateLimit", { n: s.rateLimitBlocked })}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</PageBody>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import { readFile } from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
import { isAdminUser } from "@/lib/admin";
|
||||||
|
import { BACKUP_DIR, BACKUP_FILE_PATTERN, FOLDER_PATTERN } from "@/lib/backup";
|
||||||
|
import { log } from "@/lib/log";
|
||||||
|
import { limitRequest } from "@/lib/rate-limit";
|
||||||
|
import { getCurrentUser } from "@/lib/session";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
// GET /api/admin/backups/<mapp>/<fil>: ladda ner en säkerhetskopia. Bara administratörer.
|
||||||
|
export async function GET(req: Request, { params }: { params: Promise<{ folder: string; file: string }> }) {
|
||||||
|
const user = await getCurrentUser();
|
||||||
|
if (!user || !(await isAdminUser(user.id, user.email ?? null))) return new Response("Not found", { status: 404 });
|
||||||
|
const limited = limitRequest(req, "backup-download", 30, 10 * 60_000);
|
||||||
|
if (limited) return limited;
|
||||||
|
|
||||||
|
const { folder, file } = await params;
|
||||||
|
if (!FOLDER_PATTERN.test(folder) || !BACKUP_FILE_PATTERN.test(file)) return new Response("Not found", { status: 404 });
|
||||||
|
|
||||||
|
const full = path.join(BACKUP_DIR, folder, file);
|
||||||
|
if (!full.startsWith(BACKUP_DIR + path.sep)) return new Response("Not found", { status: 404 });
|
||||||
|
|
||||||
|
try {
|
||||||
|
const data = await readFile(full);
|
||||||
|
log.info("Säkerhetskopia nedladdad", { userId: user.id, folder, file });
|
||||||
|
return new Response(new Uint8Array(data), {
|
||||||
|
headers: {
|
||||||
|
"Content-Type": file.endsWith(".zip") ? "application/zip" : "application/json",
|
||||||
|
"Content-Disposition": `attachment; filename="${file}"`,
|
||||||
|
"Cache-Control": "no-store",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
return new Response("Not found", { status: 404 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,18 @@
|
|||||||
|
import type { NextRequest } from "next/server";
|
||||||
import { handlers } from "@/auth";
|
import { handlers } from "@/auth";
|
||||||
|
import { limitRequest } from "@/lib/rate-limit";
|
||||||
|
|
||||||
export const { GET, POST } = handlers;
|
// Inloggningsflödet begränsas per IP-adress mot upprepade försök. Sessionsanrop (/session, /csrf) går fritt.
|
||||||
|
function guarded(handler: (req: NextRequest) => Promise<Response>) {
|
||||||
|
return async (req: NextRequest) => {
|
||||||
|
const path = new URL(req.url).pathname;
|
||||||
|
if (path.includes("/callback/") || path.endsWith("/signin") || path.includes("/signin/")) {
|
||||||
|
const limited = limitRequest(req, "auth", 30, 60_000);
|
||||||
|
if (limited) return limited;
|
||||||
|
}
|
||||||
|
return handler(req);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const GET = guarded(handlers.GET);
|
||||||
|
export const POST = guarded(handlers.POST);
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { strToU8, zipSync, type Zippable } from "fflate";
|
import { strToU8, zipSync, type Zippable } from "fflate";
|
||||||
import { buildExport } from "@/lib/book-transfer";
|
import { buildExport } from "@/lib/book-transfer";
|
||||||
import { prisma } from "@/lib/db";
|
import { prisma } from "@/lib/db";
|
||||||
|
import { limitRequest } from "@/lib/rate-limit";
|
||||||
import { getCurrentUser } from "@/lib/session";
|
import { getCurrentUser } from "@/lib/session";
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
@@ -10,6 +11,8 @@ export const dynamic = "force-dynamic";
|
|||||||
export async function GET(req: Request, { params }: { params: Promise<{ bookId: string }> }) {
|
export async function GET(req: Request, { params }: { params: Promise<{ bookId: string }> }) {
|
||||||
const user = await getCurrentUser();
|
const user = await getCurrentUser();
|
||||||
if (!user) return new Response("Unauthorized", { status: 401 });
|
if (!user) return new Response("Unauthorized", { status: 401 });
|
||||||
|
const limited = limitRequest(req, "export", 30, 10 * 60_000);
|
||||||
|
if (limited) return limited;
|
||||||
|
|
||||||
const { bookId } = await params;
|
const { bookId } = await params;
|
||||||
const book = await prisma.book.findFirst({ where: { id: bookId, ownerId: user.id }, select: { title: true } });
|
const book = await prisma.book.findFirst({ where: { id: bookId, ownerId: user.id }, select: { title: true } });
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { limitRequest } from "@/lib/rate-limit";
|
||||||
|
import { getCurrentUser } from "@/lib/session";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
type Row = { id: string; name: string; kind: string; code: string | null; summary: string };
|
||||||
|
|
||||||
|
// GET /api/books/<id>/search?q=text: söker namn, ID, sammanfattning, taggar och värden i mallfält
|
||||||
|
export async function GET(req: Request, { params }: { params: Promise<{ bookId: string }> }) {
|
||||||
|
const user = await getCurrentUser();
|
||||||
|
if (!user) return new Response("Unauthorized", { status: 401 });
|
||||||
|
const limited = limitRequest(req, "search", 240, 60_000);
|
||||||
|
if (limited) return limited;
|
||||||
|
|
||||||
|
const { bookId } = await params;
|
||||||
|
const book = await prisma.book.findFirst({ where: { id: bookId, ownerId: user.id }, select: { id: true } });
|
||||||
|
if (!book) return new Response("Not found", { status: 404 });
|
||||||
|
|
||||||
|
const q = (new URL(req.url).searchParams.get("q") ?? "").trim().slice(0, 100);
|
||||||
|
if (q.length < 2) return Response.json({ results: [] });
|
||||||
|
|
||||||
|
// % och _ ska tolkas som vanliga tecken
|
||||||
|
const escaped = q.replace(/[\\%_]/g, "\\$&");
|
||||||
|
const contains = `%${escaped}%`;
|
||||||
|
const starts = `${escaped}%`;
|
||||||
|
|
||||||
|
const rows = await prisma.$queryRaw<Row[]>`
|
||||||
|
SELECT id, name, kind::text AS kind, code, left(coalesce(summary, ''), 120) AS summary
|
||||||
|
FROM "Entity"
|
||||||
|
WHERE "bookId" = ${bookId}
|
||||||
|
AND (
|
||||||
|
name ILIKE ${contains}
|
||||||
|
OR code ILIKE ${contains}
|
||||||
|
OR summary ILIKE ${contains}
|
||||||
|
OR EXISTS (SELECT 1 FROM unnest(tags) AS tag WHERE tag ILIKE ${contains})
|
||||||
|
OR EXISTS (SELECT 1 FROM jsonb_each_text(data) AS field WHERE field.value ILIKE ${contains})
|
||||||
|
)
|
||||||
|
ORDER BY (name ILIKE ${starts}) DESC, (name ILIKE ${contains}) DESC, name ASC
|
||||||
|
LIMIT 20`;
|
||||||
|
|
||||||
|
return Response.json({ results: rows });
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { ImportError, MAX_IMPORT_BYTES, importBook, readImportFile } from "@/lib/book-transfer";
|
import { ImportError, MAX_IMPORT_BYTES, importBook, readImportFile } from "@/lib/book-transfer";
|
||||||
|
import { limitRequest } from "@/lib/rate-limit";
|
||||||
import { getCurrentUser } from "@/lib/session";
|
import { getCurrentUser } from "@/lib/session";
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
@@ -24,6 +25,8 @@ export async function POST(req: Request) {
|
|||||||
const user = await getCurrentUser();
|
const user = await getCurrentUser();
|
||||||
if (!user) return new Response("Unauthorized", { status: 401 });
|
if (!user) return new Response("Unauthorized", { status: 401 });
|
||||||
if (!sameOrigin(req)) return new Response("Forbidden", { status: 403 });
|
if (!sameOrigin(req)) return new Response("Forbidden", { status: 403 });
|
||||||
|
const limited = limitRequest(req, "import", 10, 10 * 60_000);
|
||||||
|
if (limited) return limited;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const form = await req.formData();
|
const form = await req.formData();
|
||||||
|
|||||||
@@ -1,11 +1,16 @@
|
|||||||
import { readFile } from "node:fs/promises";
|
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { auth } from "@/auth";
|
import { auth } from "@/auth";
|
||||||
import { CONTENT_TYPES, FILE_NAME_PATTERN, UPLOAD_DIR } from "@/lib/files";
|
import { CONTENT_TYPES, FILE_NAME_PATTERN, THUMB_DIR, UPLOAD_DIR } from "@/lib/files";
|
||||||
|
import { makeThumbnail } from "@/lib/images";
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
export async function GET(_req: Request, { params }: { params: Promise<{ name: string }> }) {
|
const CACHE = "private, max-age=31536000, immutable";
|
||||||
|
|
||||||
|
// GET /api/files/<namn> originalbilden
|
||||||
|
// GET /api/files/<namn>?size=thumb miniatyr (skapas första gången och sparas)
|
||||||
|
export async function GET(req: Request, { params }: { params: Promise<{ name: string }> }) {
|
||||||
const session = await auth();
|
const session = await auth();
|
||||||
if (!session?.user) return new Response("Unauthorized", { status: 401 });
|
if (!session?.user) return new Response("Unauthorized", { status: 401 });
|
||||||
|
|
||||||
@@ -13,12 +18,27 @@ export async function GET(_req: Request, { params }: { params: Promise<{ name: s
|
|||||||
if (!FILE_NAME_PATTERN.test(name)) return new Response("Not found", { status: 404 });
|
if (!FILE_NAME_PATTERN.test(name)) return new Response("Not found", { status: 404 });
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
if (new URL(req.url).searchParams.get("size") === "thumb") {
|
||||||
|
const thumbPath = path.join(THUMB_DIR, `${name}.webp`);
|
||||||
|
let thumb: Uint8Array;
|
||||||
|
try {
|
||||||
|
thumb = await readFile(thumbPath);
|
||||||
|
} catch {
|
||||||
|
thumb = await makeThumbnail(await readFile(path.join(UPLOAD_DIR, name)));
|
||||||
|
await mkdir(THUMB_DIR, { recursive: true });
|
||||||
|
await writeFile(thumbPath, thumb);
|
||||||
|
}
|
||||||
|
return new Response(new Uint8Array(thumb), {
|
||||||
|
headers: { "Content-Type": "image/webp", "Cache-Control": CACHE, "X-Content-Type-Options": "nosniff" },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const data = await readFile(path.join(UPLOAD_DIR, name));
|
const data = await readFile(path.join(UPLOAD_DIR, name));
|
||||||
const ext = name.split(".").pop() ?? "";
|
const ext = name.split(".").pop() ?? "";
|
||||||
return new Response(new Uint8Array(data), {
|
return new Response(new Uint8Array(data), {
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": CONTENT_TYPES[ext] ?? "application/octet-stream",
|
"Content-Type": CONTENT_TYPES[ext] ?? "application/octet-stream",
|
||||||
"Cache-Control": "private, max-age=31536000, immutable",
|
"Cache-Control": CACHE,
|
||||||
"X-Content-Type-Options": "nosniff",
|
"X-Content-Type-Options": "nosniff",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import { timingSafeEqual } from "node:crypto";
|
||||||
|
import { collectStats } from "@/lib/system-stats";
|
||||||
|
import { APP_VERSION } from "@/lib/version";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
function validToken(req: Request): boolean {
|
||||||
|
const expected = process.env.METRICS_TOKEN;
|
||||||
|
if (!expected) return false;
|
||||||
|
const header = req.headers.get("authorization") ?? "";
|
||||||
|
const given = header.startsWith("Bearer ") ? header.slice(7) : "";
|
||||||
|
const a = Buffer.from(given);
|
||||||
|
const b = Buffer.from(expected);
|
||||||
|
return a.length === b.length && timingSafeEqual(a, b);
|
||||||
|
}
|
||||||
|
|
||||||
|
const esc = (value: string) => value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
||||||
|
|
||||||
|
// Prometheus-mätvärden. Avstängt (404) tills METRICS_TOKEN är satt. Anropa med: Authorization: Bearer <token>
|
||||||
|
export async function GET(req: Request) {
|
||||||
|
if (!process.env.METRICS_TOKEN) return new Response("Not found", { status: 404 });
|
||||||
|
if (!validToken(req)) return new Response("Unauthorized", { status: 401, headers: { "WWW-Authenticate": "Bearer" } });
|
||||||
|
|
||||||
|
const s = await collectStats();
|
||||||
|
const lines: string[] = [];
|
||||||
|
const gauge = (name: string, help: string, value: number, labels = "", type: "gauge" | "counter" = "gauge") => {
|
||||||
|
lines.push(`# HELP bookmanager_${name} ${help}`, `# TYPE bookmanager_${name} ${type}`, `bookmanager_${name}${labels} ${value}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
gauge("info", "Bygginformation", 1, `{version="${esc(APP_VERSION)}"}`);
|
||||||
|
gauge("uptime_seconds", "Sekunder sedan processen startade", s.uptimeSeconds);
|
||||||
|
gauge("process_resident_memory_bytes", "Resident minnesanvändning", s.memory.rss);
|
||||||
|
gauge("process_heap_used_bytes", "Använd heap", s.memory.heapUsed);
|
||||||
|
for (const [name, value] of Object.entries(s.counts)) gauge(name, `Antal ${name}`, value);
|
||||||
|
gauge("database_size_bytes", "Databasens storlek", s.database.bytes);
|
||||||
|
gauge("uploads_bytes", "Uppladdade bilder, storlek", s.uploads.bytes);
|
||||||
|
gauge("uploads_files", "Uppladdade bilder, antal", s.uploads.files);
|
||||||
|
gauge("trash_entities", "Poster i papperskorgen", s.trash.entities);
|
||||||
|
gauge("trash_books", "Böcker i papperskorgen", s.trash.books);
|
||||||
|
gauge("backups_bytes", "Säkerhetskopior, storlek", s.backup.bytes);
|
||||||
|
gauge("backup_last_success_timestamp_seconds", "Tidpunkt för senaste lyckade säkerhetskopia", s.backup.lastOk ? Math.floor(s.backup.lastOk.startedAt.getTime() / 1000) : 0);
|
||||||
|
gauge("backup_last_run_ok", "1 om senaste körningen lyckades, annars 0", s.backup.lastRun?.status === "ok" ? 1 : 0);
|
||||||
|
gauge("backup_runs_ok_total", "Lyckade säkerhetskopieringar", s.backup.runsOk, "", "counter");
|
||||||
|
gauge("backup_runs_error_total", "Misslyckade säkerhetskopieringar", s.backup.runsError, "", "counter");
|
||||||
|
gauge("rate_limit_blocked_total", "Anrop som stoppats av hastighetsbegränsningen sedan start", s.rateLimitBlocked, "", "counter");
|
||||||
|
|
||||||
|
return new Response(lines.join("\n") + "\n", { headers: { "Content-Type": "text/plain; version=0.0.4; charset=utf-8", "Cache-Control": "no-store" } });
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { auth } from "@/auth";
|
import { auth } from "@/auth";
|
||||||
import { getGivenNames, getSurnames } from "@/lib/name-stats";
|
import { getGivenNames, getSurnames } from "@/lib/name-stats";
|
||||||
|
import { limitRequest } from "@/lib/rate-limit";
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
@@ -7,6 +8,8 @@ export const dynamic = "force-dynamic";
|
|||||||
export async function GET(req: Request) {
|
export async function GET(req: Request) {
|
||||||
const session = await auth();
|
const session = await auth();
|
||||||
if (!session?.user) return new Response("Unauthorized", { status: 401 });
|
if (!session?.user) return new Response("Unauthorized", { status: 401 });
|
||||||
|
const limited = limitRequest(req, "names", 120, 60_000);
|
||||||
|
if (limited) return limited;
|
||||||
|
|
||||||
const url = new URL(req.url);
|
const url = new URL(req.url);
|
||||||
const type = url.searchParams.get("type");
|
const type = url.searchParams.get("type");
|
||||||
|
|||||||
@@ -13,10 +13,10 @@ export default async function NewEntityPage({
|
|||||||
searchParams,
|
searchParams,
|
||||||
}: {
|
}: {
|
||||||
params: Promise<{ bookId: string; kind: string }>;
|
params: Promise<{ bookId: string; kind: string }>;
|
||||||
searchParams: Promise<{ name?: string }>;
|
searchParams: Promise<{ name?: string; error?: string }>;
|
||||||
}) {
|
}) {
|
||||||
const { bookId, kind: slug } = await params;
|
const { bookId, kind: slug } = await params;
|
||||||
const { name } = await searchParams;
|
const { name, error } = await searchParams;
|
||||||
await requireBook(bookId);
|
await requireBook(bookId);
|
||||||
const info = KIND_BY_SLUG.get(slug);
|
const info = KIND_BY_SLUG.get(slug);
|
||||||
if (!info) notFound();
|
if (!info) notFound();
|
||||||
@@ -32,6 +32,7 @@ export default async function NewEntityPage({
|
|||||||
<>
|
<>
|
||||||
<PageHeader title={t(`kind.${info.kind}.new`)} pretitle={t(`kind.${info.kind}.other`)} />
|
<PageHeader title={t(`kind.${info.kind}.new`)} pretitle={t(`kind.${info.kind}.other`)} />
|
||||||
<PageBody>
|
<PageBody>
|
||||||
|
{error === "quota" ? <div className="alert alert-danger">{t("quota.exceeded")}</div> : null}
|
||||||
<EntityForm
|
<EntityForm
|
||||||
action={saveEntity}
|
action={saveEntity}
|
||||||
bookId={bookId}
|
bookId={bookId}
|
||||||
|
|||||||
@@ -88,7 +88,7 @@ export default async function EntityListPage({
|
|||||||
<table className="table table-vcenter card-table">
|
<table className="table table-vcenter card-table">
|
||||||
<tbody>
|
<tbody>
|
||||||
{entities.map((entity) => {
|
{entities.map((entity) => {
|
||||||
const image = fileUrl(entity.imageFile);
|
const image = fileUrl(entity.imageFile, "thumb");
|
||||||
return (
|
return (
|
||||||
<tr key={entity.id}>
|
<tr key={entity.id}>
|
||||||
<td className="w-1">
|
<td className="w-1">
|
||||||
|
|||||||
@@ -6,8 +6,15 @@ import { prisma } from "@/lib/db";
|
|||||||
import { requireEntity } from "@/lib/session";
|
import { requireEntity } from "@/lib/session";
|
||||||
import { getTemplate } from "@/lib/templates";
|
import { getTemplate } from "@/lib/templates";
|
||||||
|
|
||||||
export default async function EditEntityPage({ params }: { params: Promise<{ bookId: string; entityId: string }> }) {
|
export default async function EditEntityPage({
|
||||||
|
params,
|
||||||
|
searchParams,
|
||||||
|
}: {
|
||||||
|
params: Promise<{ bookId: string; entityId: string }>;
|
||||||
|
searchParams: Promise<{ error?: string }>;
|
||||||
|
}) {
|
||||||
const { bookId, entityId } = await params;
|
const { bookId, entityId } = await params;
|
||||||
|
const { error } = await searchParams;
|
||||||
const entity = await requireEntity(bookId, entityId);
|
const entity = await requireEntity(bookId, entityId);
|
||||||
const { t, locale } = await getT();
|
const { t, locale } = await getT();
|
||||||
const { fields } = await getTemplate(bookId, entity.kind, locale);
|
const { fields } = await getTemplate(bookId, entity.kind, locale);
|
||||||
@@ -21,6 +28,7 @@ export default async function EditEntityPage({ params }: { params: Promise<{ boo
|
|||||||
<>
|
<>
|
||||||
<PageHeader title={t("entity.editTitle", { name: entity.name })} pretitle={t(`kind.${entity.kind}.one`)} />
|
<PageHeader title={t("entity.editTitle", { name: entity.name })} pretitle={t(`kind.${entity.kind}.one`)} />
|
||||||
<PageBody>
|
<PageBody>
|
||||||
|
{error === "quota" ? <div className="alert alert-danger">{t("quota.exceeded")}</div> : null}
|
||||||
<EntityForm
|
<EntityForm
|
||||||
action={saveEntity}
|
action={saveEntity}
|
||||||
bookId={bookId}
|
bookId={bookId}
|
||||||
|
|||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import { IconArrowBackUp } from "@tabler/icons-react";
|
||||||
|
import { restoreVersion } from "@/actions/history";
|
||||||
|
import { ConfirmSubmit } from "@/components/confirm-submit";
|
||||||
|
import { EmptyState, PageBody, PageHeader } from "@/components/page";
|
||||||
|
import { getT } from "@/i18n/server";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { diffSnapshots, MAX_VERSIONS, snapshotOf, type Snapshot } from "@/lib/history";
|
||||||
|
import { requireEntity } from "@/lib/session";
|
||||||
|
import { getTemplate } from "@/lib/templates";
|
||||||
|
|
||||||
|
export const metadata = { title: "Historik" };
|
||||||
|
|
||||||
|
export default async function HistoryPage({ params }: { params: Promise<{ bookId: string; entityId: string }> }) {
|
||||||
|
const { bookId, entityId } = await params;
|
||||||
|
const entity = await requireEntity(bookId, entityId);
|
||||||
|
const { t, locale } = await getT();
|
||||||
|
const { fields } = await getTemplate(bookId, entity.kind, locale);
|
||||||
|
|
||||||
|
const versions = await prisma.entityVersion.findMany({ where: { entityId, bookId }, orderBy: { createdAt: "desc" } });
|
||||||
|
const users = await prisma.user.findMany({
|
||||||
|
where: { id: { in: [...new Set(versions.map((v) => v.userId).filter((id): id is string => !!id))] } },
|
||||||
|
select: { id: true, name: true, email: true },
|
||||||
|
});
|
||||||
|
const userName = new Map(users.map((u) => [u.id, u.name ?? u.email ?? ""]));
|
||||||
|
const labels = { name: t("common.name"), summary: t("common.summary"), tags: t("common.tags") };
|
||||||
|
|
||||||
|
// Varje version jämförs med det som kom efter den (nästa version, eller nuvarande för den senaste)
|
||||||
|
let newer: Snapshot = snapshotOf(entity);
|
||||||
|
const rows = versions.map((version) => {
|
||||||
|
const snapshot = version.snapshot as unknown as Snapshot;
|
||||||
|
const changes = diffSnapshots(snapshot, newer, fields, labels);
|
||||||
|
newer = snapshot;
|
||||||
|
return { version, changes };
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<PageHeader
|
||||||
|
title={t("history.title", { name: entity.name })}
|
||||||
|
pretitle={
|
||||||
|
<Link href={`/books/${bookId}/entity/${entityId}`} className="text-reset">
|
||||||
|
{entity.name}
|
||||||
|
</Link>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<PageBody>
|
||||||
|
<p className="text-secondary">{t("history.intro", { n: MAX_VERSIONS })}</p>
|
||||||
|
{rows.length === 0 ? (
|
||||||
|
<div className="card">
|
||||||
|
<div className="card-body">
|
||||||
|
<EmptyState>{t("history.empty")}</EmptyState>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
rows.map(({ version, changes }) => (
|
||||||
|
<div className="card mb-3" key={version.id}>
|
||||||
|
<div className="card-header">
|
||||||
|
<h3 className="card-title">
|
||||||
|
{version.createdAt.toISOString().slice(0, 16).replace("T", " ")}
|
||||||
|
{version.userId && userName.get(version.userId) ? (
|
||||||
|
<span className="text-secondary fw-normal"> · {userName.get(version.userId)}</span>
|
||||||
|
) : null}
|
||||||
|
</h3>
|
||||||
|
<div className="card-actions">
|
||||||
|
<form action={restoreVersion}>
|
||||||
|
<input type="hidden" name="bookId" value={bookId} />
|
||||||
|
<input type="hidden" name="entityId" value={entityId} />
|
||||||
|
<input type="hidden" name="versionId" value={version.id} />
|
||||||
|
<ConfirmSubmit className="btn btn-sm" message={t("history.restoreConfirm")}>
|
||||||
|
<IconArrowBackUp size={16} className="me-1" />
|
||||||
|
{t("history.restore")}
|
||||||
|
</ConfirmSubmit>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="list-group list-group-flush">
|
||||||
|
{changes.length === 0 ? <div className="list-group-item text-secondary">{t("history.noChanges")}</div> : null}
|
||||||
|
{changes.map((change) => (
|
||||||
|
<div className="list-group-item" key={change.label}>
|
||||||
|
<div className="fw-bold">{change.label}</div>
|
||||||
|
<div className="row g-2">
|
||||||
|
<div className="col-md-6">
|
||||||
|
<div className="text-secondary small">{t("history.before")}</div>
|
||||||
|
<div className="bm-prewrap">{change.before || <span className="text-secondary">—</span>}</div>
|
||||||
|
</div>
|
||||||
|
<div className="col-md-6">
|
||||||
|
<div className="text-secondary small">{t("history.after")}</div>
|
||||||
|
<div className="bm-prewrap">{change.after || <span className="text-secondary">—</span>}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</PageBody>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { IconMapPin, IconPencil, IconTrash, IconX } from "@tabler/icons-react";
|
import { IconHistory, IconMapPin, IconPencil, IconTrash, IconX } from "@tabler/icons-react";
|
||||||
import { deleteEntity } from "@/actions/entities";
|
import { deleteEntity } from "@/actions/entities";
|
||||||
import { deleteRelation } from "@/actions/relations";
|
import { deleteRelation } from "@/actions/relations";
|
||||||
import { ConfirmSubmit } from "@/components/confirm-submit";
|
import { ConfirmSubmit } from "@/components/confirm-submit";
|
||||||
@@ -64,6 +64,7 @@ export default async function EntityPage({ params }: { params: Promise<{ bookId:
|
|||||||
prisma.bookMap.findMany({ where: { bookId }, orderBy: { name: "asc" } }),
|
prisma.bookMap.findMany({ where: { bookId }, orderBy: { name: "asc" } }),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
const versionCount = await prisma.entityVersion.count({ where: { entityId: entity.id } });
|
||||||
const info = KIND_INFO[entity.kind];
|
const info = KIND_INFO[entity.kind];
|
||||||
const Icon = kindIcons[entity.kind];
|
const Icon = kindIcons[entity.kind];
|
||||||
const image = fileUrl(entity.imageFile);
|
const image = fileUrl(entity.imageFile);
|
||||||
@@ -155,10 +156,16 @@ export default async function EntityPage({ params }: { params: Promise<{ bookId:
|
|||||||
<IconPencil size={18} className="me-1" />
|
<IconPencil size={18} className="me-1" />
|
||||||
{t("common.edit")}
|
{t("common.edit")}
|
||||||
</Link>
|
</Link>
|
||||||
|
{versionCount > 0 ? (
|
||||||
|
<Link href={`${entityHref(entity.id)}/history`} className="btn">
|
||||||
|
<IconHistory size={18} className="me-1" />
|
||||||
|
{t("history.button", { n: versionCount })}
|
||||||
|
</Link>
|
||||||
|
) : null}
|
||||||
<form action={deleteEntity}>
|
<form action={deleteEntity}>
|
||||||
<input type="hidden" name="bookId" value={bookId} />
|
<input type="hidden" name="bookId" value={bookId} />
|
||||||
<input type="hidden" name="id" value={entity.id} />
|
<input type="hidden" name="id" value={entity.id} />
|
||||||
<ConfirmSubmit className="btn btn-outline-danger">
|
<ConfirmSubmit className="btn btn-outline-danger" message={t("trash.moveConfirm")}>
|
||||||
<IconTrash size={18} className="me-1" />
|
<IconTrash size={18} className="me-1" />
|
||||||
{t("common.delete")}
|
{t("common.delete")}
|
||||||
</ConfirmSubmit>
|
</ConfirmSubmit>
|
||||||
|
|||||||
@@ -8,8 +8,15 @@ import { requireBook } from "@/lib/session";
|
|||||||
|
|
||||||
export const metadata = { title: "Kartor" };
|
export const metadata = { title: "Kartor" };
|
||||||
|
|
||||||
export default async function MapsPage({ params }: { params: Promise<{ bookId: string }> }) {
|
export default async function MapsPage({
|
||||||
|
params,
|
||||||
|
searchParams,
|
||||||
|
}: {
|
||||||
|
params: Promise<{ bookId: string }>;
|
||||||
|
searchParams: Promise<{ error?: string }>;
|
||||||
|
}) {
|
||||||
const { bookId } = await params;
|
const { bookId } = await params;
|
||||||
|
const { error } = await searchParams;
|
||||||
await requireBook(bookId);
|
await requireBook(bookId);
|
||||||
const { t } = await getT();
|
const { t } = await getT();
|
||||||
const maps = await prisma.bookMap.findMany({
|
const maps = await prisma.bookMap.findMany({
|
||||||
@@ -22,6 +29,7 @@ export default async function MapsPage({ params }: { params: Promise<{ bookId: s
|
|||||||
<>
|
<>
|
||||||
<PageHeader title={t("map.title")} />
|
<PageHeader title={t("map.title")} />
|
||||||
<PageBody>
|
<PageBody>
|
||||||
|
{error === "quota" ? <div className="alert alert-danger">{t("quota.exceeded")}</div> : null}
|
||||||
<div className="row row-cards">
|
<div className="row row-cards">
|
||||||
<div className="col-lg-8">
|
<div className="col-lg-8">
|
||||||
{maps.length === 0 ? (
|
{maps.length === 0 ? (
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import { IconArrowBackUp, IconTrash } from "@tabler/icons-react";
|
||||||
|
import { emptyTrash, purgeTrash, restoreTrashEntity } from "@/actions/trash";
|
||||||
|
import { ConfirmSubmit } from "@/components/confirm-submit";
|
||||||
|
import { kindIcons } from "@/components/kind-icons";
|
||||||
|
import { EmptyState, PageBody, PageHeader } from "@/components/page";
|
||||||
|
import { getT } from "@/i18n/server";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { KIND_INFO, parseKind } from "@/lib/kinds";
|
||||||
|
import { requireBook } from "@/lib/session";
|
||||||
|
import { TRASH_DAYS } from "@/lib/trash";
|
||||||
|
|
||||||
|
export const metadata = { title: "Papperskorg" };
|
||||||
|
|
||||||
|
export default async function TrashPage({
|
||||||
|
params,
|
||||||
|
searchParams,
|
||||||
|
}: {
|
||||||
|
params: Promise<{ bookId: string }>;
|
||||||
|
searchParams: Promise<{ restore?: string }>;
|
||||||
|
}) {
|
||||||
|
const { bookId } = await params;
|
||||||
|
const { restore } = await searchParams;
|
||||||
|
const book = await requireBook(bookId);
|
||||||
|
const { t } = await getT();
|
||||||
|
const items = await prisma.trashItem.findMany({
|
||||||
|
where: { ownerId: book.ownerId, bookId, kind: "entity" },
|
||||||
|
orderBy: { deletedAt: "desc" },
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<PageHeader
|
||||||
|
title={t("trash.title")}
|
||||||
|
actions={
|
||||||
|
items.length > 0 ? (
|
||||||
|
<form action={emptyTrash}>
|
||||||
|
<input type="hidden" name="bookId" value={bookId} />
|
||||||
|
<ConfirmSubmit className="btn btn-outline-danger" message={t("trash.emptyConfirm")}>
|
||||||
|
<IconTrash size={18} className="me-1" />
|
||||||
|
{t("trash.empty")}
|
||||||
|
</ConfirmSubmit>
|
||||||
|
</form>
|
||||||
|
) : null
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<PageBody>
|
||||||
|
{restore === "failed" ? <div className="alert alert-warning">{t("trash.restoreFailed")}</div> : null}
|
||||||
|
<p className="text-secondary">{t("trash.intro", { days: TRASH_DAYS })}</p>
|
||||||
|
<div className="card">
|
||||||
|
{items.length === 0 ? (
|
||||||
|
<div className="card-body">
|
||||||
|
<EmptyState>{t("trash.emptyState")}</EmptyState>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="list-group list-group-flush">
|
||||||
|
{items.map((item) => {
|
||||||
|
const kind = parseKind(item.detail);
|
||||||
|
const Icon = kind ? kindIcons[kind] : null;
|
||||||
|
const daysLeft = Math.max(0, TRASH_DAYS - Math.floor((Date.now() - item.deletedAt.getTime()) / 86_400_000));
|
||||||
|
return (
|
||||||
|
<div key={item.id} className="list-group-item d-flex align-items-center gap-3">
|
||||||
|
{Icon && kind ? (
|
||||||
|
<span className={`avatar avatar-sm bg-${KIND_INFO[kind].color}-lt`}>
|
||||||
|
<Icon size={16} />
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
<div className="flex-fill min-w-0">
|
||||||
|
<div className="fw-bold text-truncate">{item.label}</div>
|
||||||
|
<div className="text-secondary small">
|
||||||
|
{kind ? t(`kind.${kind}.one`) : ""} · {t("trash.deleted", { date: item.deletedAt.toISOString().slice(0, 10) })} ·{" "}
|
||||||
|
{t("trash.daysLeft", { n: daysLeft })}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<form action={restoreTrashEntity}>
|
||||||
|
<input type="hidden" name="bookId" value={bookId} />
|
||||||
|
<input type="hidden" name="id" value={item.id} />
|
||||||
|
<button type="submit" className="btn btn-sm">
|
||||||
|
<IconArrowBackUp size={16} className="me-1" />
|
||||||
|
{t("trash.restore")}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
<form action={purgeTrash}>
|
||||||
|
<input type="hidden" name="bookId" value={bookId} />
|
||||||
|
<input type="hidden" name="id" value={item.id} />
|
||||||
|
<ConfirmSubmit className="btn btn-sm btn-outline-danger" message={t("trash.purgeConfirm")}>
|
||||||
|
{t("trash.purge")}
|
||||||
|
</ConfirmSubmit>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="mt-3">
|
||||||
|
<Link href={`/books/${bookId}`} className="btn">
|
||||||
|
{t("common.back")}
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</PageBody>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -110,3 +110,53 @@
|
|||||||
min-width: 9rem;
|
min-width: 9rem;
|
||||||
vertical-align: top;
|
vertical-align: top;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Kommandopalett (Ctrl+K) */
|
||||||
|
.bm-palette-backdrop {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
z-index: 2000;
|
||||||
|
background: rgba(15, 23, 42, 0.45);
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 12vh 1rem 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bm-palette {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 40rem;
|
||||||
|
max-height: 70vh;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
overflow: hidden;
|
||||||
|
box-shadow: 0 1rem 3rem rgba(0, 0, 0, 0.3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bm-palette .form-control-flush {
|
||||||
|
border: 0;
|
||||||
|
box-shadow: none;
|
||||||
|
padding-top: 0.9rem;
|
||||||
|
padding-bottom: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bm-palette-list {
|
||||||
|
overflow-y: auto;
|
||||||
|
padding-bottom: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bm-palette-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
width: 100%;
|
||||||
|
padding: 0.5rem 1rem;
|
||||||
|
border: 0;
|
||||||
|
background: transparent;
|
||||||
|
color: inherit;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bm-palette-item.active {
|
||||||
|
background: var(--tblr-primary-lt, rgba(32, 107, 196, 0.1));
|
||||||
|
}
|
||||||
+2
-1
@@ -34,7 +34,8 @@ export default {
|
|||||||
: []),
|
: []),
|
||||||
],
|
],
|
||||||
pages: { signIn: "/login" },
|
pages: { signIn: "/login" },
|
||||||
session: { strategy: "jwt" },
|
// Inloggningens livslängd i dagar (SESSION_DAYS), standard 14
|
||||||
|
session: { strategy: "jwt", maxAge: (Number(process.env.SESSION_DAYS) || 14) * 24 * 60 * 60 },
|
||||||
callbacks: {
|
callbacks: {
|
||||||
authorized({ auth, request }) {
|
authorized({ auth, request }) {
|
||||||
if (request.nextUrl.pathname.startsWith("/login")) return true;
|
if (request.nextUrl.pathname.startsWith("/login")) return true;
|
||||||
|
|||||||
@@ -0,0 +1,211 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { IconCornerDownLeft, IconPlus, IconSearch, IconFileText } from "@tabler/icons-react";
|
||||||
|
import type { EntityKind } from "@prisma/client";
|
||||||
|
import { useT } from "@/i18n/client";
|
||||||
|
import { kindIcons } from "./kind-icons";
|
||||||
|
|
||||||
|
type Command = { id: string; label: string; hint?: string; href: string; group: "entity" | "page" | "create"; kind?: EntityKind; code?: string | null };
|
||||||
|
type SearchRow = { id: string; name: string; kind: EntityKind; code: string | null; summary: string };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Snabbsök och kommandopalett. Ctrl+K (Cmd+K på Mac) öppnar den. Sök poster i boken, hoppa till en sida eller
|
||||||
|
* skapa något nytt. Pilar väljer, Enter öppnar, Esc stänger.
|
||||||
|
*/
|
||||||
|
export function CommandPalette({
|
||||||
|
bookId,
|
||||||
|
pages,
|
||||||
|
creates,
|
||||||
|
}: {
|
||||||
|
bookId?: string;
|
||||||
|
pages: { label: string; href: string }[];
|
||||||
|
creates: { label: string; href: string }[];
|
||||||
|
}) {
|
||||||
|
const t = useT();
|
||||||
|
const router = useRouter();
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [query, setQuery] = useState("");
|
||||||
|
const [found, setFound] = useState<SearchRow[]>([]);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [active, setActive] = useState(0);
|
||||||
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const listRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
const close = useCallback(() => {
|
||||||
|
setOpen(false);
|
||||||
|
setQuery("");
|
||||||
|
setFound([]);
|
||||||
|
setActive(0);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Ctrl/Cmd+K öppnar och stänger
|
||||||
|
useEffect(() => {
|
||||||
|
function onKey(event: KeyboardEvent) {
|
||||||
|
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "k") {
|
||||||
|
event.preventDefault();
|
||||||
|
setOpen((value) => !value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
window.addEventListener("keydown", onKey);
|
||||||
|
return () => window.removeEventListener("keydown", onKey);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Knappen i sidomenyn skickar en egen händelse
|
||||||
|
useEffect(() => {
|
||||||
|
const onOpen = () => setOpen(true);
|
||||||
|
window.addEventListener("bm:open-palette", onOpen);
|
||||||
|
return () => window.removeEventListener("bm:open-palette", onOpen);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (open) inputRef.current?.focus();
|
||||||
|
}, [open]);
|
||||||
|
|
||||||
|
// Sökning efter poster, med kort fördröjning medan man skriver
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open || !bookId || query.trim().length < 2) {
|
||||||
|
setFound([]);
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLoading(true);
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timer = setTimeout(async () => {
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/books/${bookId}/search?q=${encodeURIComponent(query.trim())}`, { signal: controller.signal });
|
||||||
|
if (res.ok) setFound(((await res.json()) as { results: SearchRow[] }).results);
|
||||||
|
} catch {
|
||||||
|
// avbruten eller nätverksfel: visa det som redan finns
|
||||||
|
} finally {
|
||||||
|
if (!controller.signal.aborted) setLoading(false);
|
||||||
|
}
|
||||||
|
}, 180);
|
||||||
|
return () => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
controller.abort();
|
||||||
|
};
|
||||||
|
}, [query, open, bookId]);
|
||||||
|
|
||||||
|
const commands = useMemo<Command[]>(() => {
|
||||||
|
const needle = query.trim().toLowerCase();
|
||||||
|
const match = (label: string) => !needle || label.toLowerCase().includes(needle);
|
||||||
|
return [
|
||||||
|
...found.map((row): Command => ({
|
||||||
|
id: `e-${row.id}`,
|
||||||
|
label: row.name,
|
||||||
|
hint: row.summary,
|
||||||
|
href: `/books/${bookId}/entity/${row.id}`,
|
||||||
|
group: "entity",
|
||||||
|
kind: row.kind,
|
||||||
|
code: row.code,
|
||||||
|
})),
|
||||||
|
...pages.filter((p) => match(p.label)).map((p): Command => ({ id: `p-${p.href}`, label: p.label, href: p.href, group: "page" })),
|
||||||
|
...creates.filter((c) => match(c.label)).map((c): Command => ({ id: `c-${c.href}`, label: c.label, href: c.href, group: "create" })),
|
||||||
|
];
|
||||||
|
}, [found, pages, creates, query, bookId]);
|
||||||
|
|
||||||
|
useEffect(() => setActive(0), [query, found]);
|
||||||
|
|
||||||
|
// Håll markerad rad synlig
|
||||||
|
useEffect(() => {
|
||||||
|
listRef.current?.querySelector<HTMLElement>(`[data-index="${active}"]`)?.scrollIntoView({ block: "nearest" });
|
||||||
|
}, [active]);
|
||||||
|
|
||||||
|
function go(command: Command | undefined) {
|
||||||
|
if (!command) return;
|
||||||
|
close();
|
||||||
|
router.push(command.href);
|
||||||
|
}
|
||||||
|
|
||||||
|
function onInputKey(event: React.KeyboardEvent) {
|
||||||
|
if (event.key === "ArrowDown") {
|
||||||
|
event.preventDefault();
|
||||||
|
setActive((i) => Math.min(i + 1, commands.length - 1));
|
||||||
|
} else if (event.key === "ArrowUp") {
|
||||||
|
event.preventDefault();
|
||||||
|
setActive((i) => Math.max(i - 1, 0));
|
||||||
|
} else if (event.key === "Enter") {
|
||||||
|
event.preventDefault();
|
||||||
|
go(commands[active]);
|
||||||
|
} else if (event.key === "Escape") {
|
||||||
|
event.preventDefault();
|
||||||
|
close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!open) return null;
|
||||||
|
|
||||||
|
const heading = (group: Command["group"]) =>
|
||||||
|
group === "entity" ? t("palette.entities") : group === "page" ? t("palette.pages") : t("palette.create");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="bm-palette-backdrop" onMouseDown={close} role="presentation">
|
||||||
|
<div className="bm-palette card" role="dialog" aria-modal="true" aria-label={t("palette.label")} onMouseDown={(e) => e.stopPropagation()}>
|
||||||
|
<div className="input-icon border-bottom">
|
||||||
|
<span className="input-icon-addon">
|
||||||
|
<IconSearch size={18} />
|
||||||
|
</span>
|
||||||
|
<input
|
||||||
|
ref={inputRef}
|
||||||
|
className="form-control form-control-flush"
|
||||||
|
placeholder={bookId ? t("palette.placeholder") : t("palette.placeholderNoBook")}
|
||||||
|
value={query}
|
||||||
|
onChange={(e) => setQuery(e.target.value)}
|
||||||
|
onKeyDown={onInputKey}
|
||||||
|
autoComplete="off"
|
||||||
|
spellCheck={false}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bm-palette-list" ref={listRef}>
|
||||||
|
{commands.length === 0 ? (
|
||||||
|
<div className="text-secondary p-3">{loading ? t("common.loading") : t("palette.empty")}</div>
|
||||||
|
) : (
|
||||||
|
commands.map((command, index) => {
|
||||||
|
const Icon = command.kind ? kindIcons[command.kind] : command.group === "create" ? IconPlus : IconFileText;
|
||||||
|
const showHeading = index === 0 || commands[index - 1].group !== command.group;
|
||||||
|
return (
|
||||||
|
<div key={command.id}>
|
||||||
|
{showHeading ? <div className="subheader px-3 pt-2 pb-1">{heading(command.group)}</div> : null}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-index={index}
|
||||||
|
className={`bm-palette-item ${index === active ? "active" : ""}`}
|
||||||
|
onMouseEnter={() => setActive(index)}
|
||||||
|
onClick={() => go(command)}
|
||||||
|
>
|
||||||
|
<Icon size={18} className="flex-shrink-0" />
|
||||||
|
<span className="text-truncate">
|
||||||
|
<span className="fw-bold">{command.label}</span>
|
||||||
|
{command.hint ? <span className="text-secondary"> · {command.hint}</span> : null}
|
||||||
|
</span>
|
||||||
|
{command.code ? <span className="badge ms-auto flex-shrink-0">{command.code}</span> : null}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="border-top px-3 py-2 text-secondary small d-flex align-items-center gap-3">
|
||||||
|
<span>{t("palette.hint")}</span>
|
||||||
|
<IconCornerDownLeft size={14} className="ms-auto" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Knapp som öppnar paletten. Ligger i sidomenyn. */
|
||||||
|
export function PaletteButton() {
|
||||||
|
const t = useT();
|
||||||
|
return (
|
||||||
|
<button type="button" className="btn btn-sm w-100 d-flex align-items-center gap-2" onClick={() => window.dispatchEvent(new Event("bm:open-palette"))}>
|
||||||
|
<IconSearch size={16} />
|
||||||
|
<span>{t("palette.button")}</span>
|
||||||
|
<kbd className="ms-auto">Ctrl K</kbd>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -109,7 +109,7 @@ export function EntityForm({
|
|||||||
t: TFunction;
|
t: TFunction;
|
||||||
}) {
|
}) {
|
||||||
const data = (entity?.data ?? {}) as Record<string, unknown>;
|
const data = (entity?.data ?? {}) as Record<string, unknown>;
|
||||||
const image = fileUrl(entity?.imageFile);
|
const image = fileUrl(entity?.imageFile, "thumb");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<form action={action}>
|
<form action={action}>
|
||||||
|
|||||||
@@ -9,7 +9,9 @@ import {
|
|||||||
IconListDetails,
|
IconListDetails,
|
||||||
IconLogout,
|
IconLogout,
|
||||||
IconMap2,
|
IconMap2,
|
||||||
|
IconServerCog,
|
||||||
IconSettings,
|
IconSettings,
|
||||||
|
IconTrash,
|
||||||
IconTemplate,
|
IconTemplate,
|
||||||
IconBooks,
|
IconBooks,
|
||||||
} from "@tabler/icons-react";
|
} from "@tabler/icons-react";
|
||||||
@@ -17,14 +19,17 @@ import type { ReactNode } from "react";
|
|||||||
import { signOut } from "@/auth";
|
import { signOut } from "@/auth";
|
||||||
import { setLocale } from "@/actions/settings";
|
import { setLocale } from "@/actions/settings";
|
||||||
import { getT } from "@/i18n/server";
|
import { getT } from "@/i18n/server";
|
||||||
|
import { isAdminUser } from "@/lib/admin";
|
||||||
|
import { APP_VERSION_LABEL } from "@/lib/version";
|
||||||
import { LOCALES } from "@/i18n/core";
|
import { LOCALES } from "@/i18n/core";
|
||||||
import { KINDS } from "@/lib/kinds";
|
import { KINDS } from "@/lib/kinds";
|
||||||
import { kindIcons } from "./kind-icons";
|
import { kindIcons } from "./kind-icons";
|
||||||
|
import { CommandPalette, PaletteButton } from "./command-palette";
|
||||||
import { NavLink } from "./nav-link";
|
import { NavLink } from "./nav-link";
|
||||||
import { ThemeToggle } from "./theme-toggle";
|
import { ThemeToggle } from "./theme-toggle";
|
||||||
|
|
||||||
type ShellProps = {
|
type ShellProps = {
|
||||||
user: { name?: string | null; email?: string | null };
|
user: { id: string; name?: string | null; email?: string | null };
|
||||||
book?: { id: string; title: string };
|
book?: { id: string; title: string };
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
};
|
};
|
||||||
@@ -32,6 +37,28 @@ type ShellProps = {
|
|||||||
export async function Shell({ user, book, children }: ShellProps) {
|
export async function Shell({ user, book, children }: ShellProps) {
|
||||||
const { t, locale } = await getT();
|
const { t, locale } = await getT();
|
||||||
const base = book ? `/books/${book.id}` : "";
|
const base = book ? `/books/${book.id}` : "";
|
||||||
|
const admin = await isAdminUser(user.id, user.email ?? null);
|
||||||
|
|
||||||
|
// Sidor och "skapa ny" för kommandopaletten (Ctrl+K)
|
||||||
|
const pages = [
|
||||||
|
...(book
|
||||||
|
? [
|
||||||
|
{ label: t("nav.books"), href: "/" },
|
||||||
|
{ label: t("nav.overview"), href: base },
|
||||||
|
...KINDS.map((k) => ({ label: t(`kind.${k.kind}.other`), href: `${base}/e/${k.slug}` })),
|
||||||
|
{ label: t("nav.relations"), href: `${base}/relations` },
|
||||||
|
{ label: t("nav.schedules"), href: `${base}/schedules` },
|
||||||
|
{ label: t("nav.maps"), href: `${base}/maps` },
|
||||||
|
{ label: t("nav.names"), href: `${base}/names` },
|
||||||
|
{ label: t("nav.idRegister"), href: `${base}/register` },
|
||||||
|
{ label: t("nav.templates"), href: `${base}/templates` },
|
||||||
|
{ label: t("nav.trash"), href: `${base}/trash` },
|
||||||
|
{ label: t("nav.settings"), href: `${base}/settings` },
|
||||||
|
]
|
||||||
|
: [{ label: t("nav.books"), href: "/" }]),
|
||||||
|
...(admin ? [{ label: t("nav.admin"), href: "/admin" }] : []),
|
||||||
|
];
|
||||||
|
const creates = book ? KINDS.map((k) => ({ label: t(`kind.${k.kind}.new`), href: `${base}/e/${k.slug}/new` })) : [];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="page">
|
<div className="page">
|
||||||
@@ -56,6 +83,9 @@ export async function Shell({ user, book, children }: ShellProps) {
|
|||||||
</h1>
|
</h1>
|
||||||
|
|
||||||
<div className="collapse navbar-collapse" id="sidebar-menu">
|
<div className="collapse navbar-collapse" id="sidebar-menu">
|
||||||
|
<div className="pt-lg-3 pb-1">
|
||||||
|
<PaletteButton />
|
||||||
|
</div>
|
||||||
<ul className="navbar-nav pt-lg-3">
|
<ul className="navbar-nav pt-lg-3">
|
||||||
{book ? (
|
{book ? (
|
||||||
<>
|
<>
|
||||||
@@ -124,6 +154,9 @@ export async function Shell({ user, book, children }: ShellProps) {
|
|||||||
<NavLink href={`${base}/templates`} icon={<IconTemplate size={20} />}>
|
<NavLink href={`${base}/templates`} icon={<IconTemplate size={20} />}>
|
||||||
{t("nav.templates")}
|
{t("nav.templates")}
|
||||||
</NavLink>
|
</NavLink>
|
||||||
|
<NavLink href={`${base}/trash`} icon={<IconTrash size={20} />}>
|
||||||
|
{t("nav.trash")}
|
||||||
|
</NavLink>
|
||||||
<NavLink href={`${base}/settings`} icon={<IconSettings size={20} />}>
|
<NavLink href={`${base}/settings`} icon={<IconSettings size={20} />}>
|
||||||
{t("nav.settings")}
|
{t("nav.settings")}
|
||||||
</NavLink>
|
</NavLink>
|
||||||
@@ -135,6 +168,14 @@ export async function Shell({ user, book, children }: ShellProps) {
|
|||||||
)}
|
)}
|
||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
|
{admin ? (
|
||||||
|
<ul className="navbar-nav mt-3">
|
||||||
|
<NavLink href="/admin" icon={<IconServerCog size={20} />}>
|
||||||
|
{t("nav.admin")}
|
||||||
|
</NavLink>
|
||||||
|
</ul>
|
||||||
|
) : null}
|
||||||
|
|
||||||
<div className="mt-auto pt-4 pb-2 d-flex flex-column gap-2">
|
<div className="mt-auto pt-4 pb-2 d-flex flex-column gap-2">
|
||||||
<div className="d-flex align-items-center gap-2">
|
<div className="d-flex align-items-center gap-2">
|
||||||
<form action={setLocale} className="btn-group" aria-label={t("nav.language")}>
|
<form action={setLocale} className="btn-group" aria-label={t("nav.language")}>
|
||||||
@@ -152,6 +193,7 @@ export async function Shell({ user, book, children }: ShellProps) {
|
|||||||
</form>
|
</form>
|
||||||
<ThemeToggle />
|
<ThemeToggle />
|
||||||
</div>
|
</div>
|
||||||
|
<div className="text-secondary small opacity-75">v{APP_VERSION_LABEL}</div>
|
||||||
<div className="d-flex align-items-center justify-content-between gap-2">
|
<div className="d-flex align-items-center justify-content-between gap-2">
|
||||||
<span className="text-truncate text-secondary small" title={user.email ?? undefined}>
|
<span className="text-truncate text-secondary small" title={user.email ?? undefined}>
|
||||||
{user.name ?? user.email}
|
{user.name ?? user.email}
|
||||||
@@ -173,6 +215,7 @@ export async function Shell({ user, book, children }: ShellProps) {
|
|||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
<div className="page-wrapper">{children}</div>
|
<div className="page-wrapper">{children}</div>
|
||||||
|
<CommandPalette bookId={book?.id} pages={pages} creates={creates} />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
+79
-1
@@ -82,6 +82,82 @@ export const en: Record<keyof typeof sv, string> = {
|
|||||||
"names.fill": "Random name",
|
"names.fill": "Random name",
|
||||||
"names.fillFemale": "Random woman's name",
|
"names.fillFemale": "Random woman's name",
|
||||||
"names.fillMale": "Random man's name",
|
"names.fillMale": "Random man's name",
|
||||||
|
"nav.trash": "Trash",
|
||||||
|
"trash.title": "Trash",
|
||||||
|
"trash.books": "Deleted books",
|
||||||
|
"trash.intro": "Deleted items stay here for {days} days and can be restored. After that they are removed automatically.",
|
||||||
|
"trash.emptyState": "The trash is empty.",
|
||||||
|
"trash.empty": "Empty trash",
|
||||||
|
"trash.emptyConfirm": "Permanently delete everything in the trash? This cannot be undone.",
|
||||||
|
"trash.restore": "Restore",
|
||||||
|
"trash.purge": "Delete permanently",
|
||||||
|
"trash.purgeConfirm": "Delete permanently? This cannot be undone.",
|
||||||
|
"trash.moveConfirm": "Move to the trash? You can restore it for 30 days.",
|
||||||
|
"trash.deleted": "deleted {date}",
|
||||||
|
"trash.daysLeft": "{n} days left",
|
||||||
|
"trash.restoreFailed": "Could not restore. The book or item may already exist again or have been removed.",
|
||||||
|
"history.button": "History ({n})",
|
||||||
|
"history.title": "History: {name}",
|
||||||
|
"history.intro": "Earlier versions are saved whenever something changes (the latest {n} are kept). Images are not included. Restoring a version saves the current one first, so it can be undone.",
|
||||||
|
"history.empty": "No earlier versions yet.",
|
||||||
|
"history.noChanges": "No differences from the next version.",
|
||||||
|
"history.before": "Before",
|
||||||
|
"history.after": "After",
|
||||||
|
"history.restore": "Restore this version",
|
||||||
|
"history.restoreConfirm": "Restore this version? The current one is saved to the history first.",
|
||||||
|
"nav.admin": "Administration",
|
||||||
|
"admin.title": "Administration",
|
||||||
|
"admin.intro": "Status, backups and metrics for the whole installation. Only administrators see this page.",
|
||||||
|
"admin.system": "System",
|
||||||
|
"admin.version": "Version",
|
||||||
|
"admin.node": "Node.js",
|
||||||
|
"admin.uptime": "Uptime",
|
||||||
|
"admin.memory": "Memory (RSS)",
|
||||||
|
"admin.data": "Data",
|
||||||
|
"admin.users": "Users",
|
||||||
|
"admin.books": "Books",
|
||||||
|
"admin.entities": "Items",
|
||||||
|
"admin.relations": "Relationships",
|
||||||
|
"admin.maps": "Maps",
|
||||||
|
"admin.markers": "Markers",
|
||||||
|
"admin.dbSize": "Database size",
|
||||||
|
"admin.uploads": "Uploaded images",
|
||||||
|
"admin.thumbs": "Thumbnails",
|
||||||
|
"admin.trash": "Trash",
|
||||||
|
"admin.trashSummary": "{entities} items and {books} books (removed after {days} days)",
|
||||||
|
"admin.backup": "Backups",
|
||||||
|
"admin.backupSettings": "Scheduled {enabled} at {hour}:00, the {keep} latest are kept. Folder: {dir}",
|
||||||
|
"admin.backupOn": "on",
|
||||||
|
"admin.backupOff": "off",
|
||||||
|
"admin.backupNow": "Run backup now",
|
||||||
|
"admin.backupStarted": "The backup has started. Reload the page in a moment.",
|
||||||
|
"admin.backupLast": "Last run",
|
||||||
|
"admin.backupNever": "No run yet",
|
||||||
|
"admin.backupStatus.ok": "succeeded",
|
||||||
|
"admin.backupStatus.error": "failed",
|
||||||
|
"admin.backupStatus.running": "running",
|
||||||
|
"admin.backupFiles": "{n} files",
|
||||||
|
"admin.backupHelp": "Each zip file can be imported again via Import book on the start page.",
|
||||||
|
"admin.backupNone": "No backups yet.",
|
||||||
|
"admin.services": "External services",
|
||||||
|
"admin.servicesHelp": "Used by the name generator. The check calls the services directly from the server.",
|
||||||
|
"admin.check": "Check",
|
||||||
|
"admin.observability": "Logs and metrics",
|
||||||
|
"admin.logLevel": "Log level",
|
||||||
|
"admin.metricsOn": "Metrics enabled at /api/metrics (Bearer token).",
|
||||||
|
"admin.metricsOff": "Metrics are disabled. Set METRICS_TOKEN to enable /api/metrics.",
|
||||||
|
"admin.rateLimit": "Requests blocked by rate limiting since start: {n}",
|
||||||
|
"admin.download": "Download",
|
||||||
|
"nav.search": "Search",
|
||||||
|
"palette.button": "Search",
|
||||||
|
"palette.label": "Quick search",
|
||||||
|
"palette.placeholder": "Search items, pages and actions…",
|
||||||
|
"palette.placeholderNoBook": "Search pages…",
|
||||||
|
"palette.entities": "Items",
|
||||||
|
"palette.pages": "Pages",
|
||||||
|
"palette.create": "Create new",
|
||||||
|
"palette.empty": "No results.",
|
||||||
|
"palette.hint": "↑↓ to choose, Enter to open, Esc to close",
|
||||||
"nav.settings": "Book settings",
|
"nav.settings": "Book settings",
|
||||||
"nav.logout": "Log out",
|
"nav.logout": "Log out",
|
||||||
"nav.theme": "Toggle theme",
|
"nav.theme": "Toggle theme",
|
||||||
@@ -313,7 +389,7 @@ export const en: Record<keyof typeof sv, string> = {
|
|||||||
"settings.title": "Book settings",
|
"settings.title": "Book settings",
|
||||||
"settings.danger": "Danger zone",
|
"settings.danger": "Danger zone",
|
||||||
"settings.deleteBook": "Delete book",
|
"settings.deleteBook": "Delete book",
|
||||||
"settings.deleteBookHelp": "Permanently deletes the book and all its content. Export first if you want a copy.",
|
"settings.deleteBookHelp": "The book is moved to the trash and can be restored for 30 days. After that it is deleted permanently.",
|
||||||
"settings.export": "Export with images (.zip)",
|
"settings.export": "Export with images (.zip)",
|
||||||
"settings.exportJson": "Export data only (.json)",
|
"settings.exportJson": "Export data only (.json)",
|
||||||
"import.title": "Import book",
|
"import.title": "Import book",
|
||||||
@@ -324,6 +400,8 @@ export const en: Record<keyof typeof sv, string> = {
|
|||||||
"import.error.version": "the export file version is not supported",
|
"import.error.version": "the export file version is not supported",
|
||||||
"import.error.too-large": "the file is too large",
|
"import.error.too-large": "the file is too large",
|
||||||
"import.error.empty": "no file was chosen or the file is empty",
|
"import.error.empty": "no file was chosen or the file is empty",
|
||||||
|
"quota.exceeded": "The image storage quota is full. Remove images or empty the trash and try again.",
|
||||||
|
"import.error.quota": "the image storage quota would be exceeded",
|
||||||
"import.error.invalid": "the file is damaged or has the wrong format",
|
"import.error.invalid": "the file is damaged or has the wrong format",
|
||||||
"import.done": "The book was imported: {entities} items, {relations} relationships and {maps} maps.",
|
"import.done": "The book was imported: {entities} items, {relations} relationships and {maps} maps.",
|
||||||
"import.skipped": "{n} images or links were missing from the file and were skipped.",
|
"import.skipped": "{n} images or links were missing from the file and were skipped.",
|
||||||
|
|||||||
+79
-1
@@ -80,6 +80,82 @@ export const sv = {
|
|||||||
"names.fill": "Slumpa namn",
|
"names.fill": "Slumpa namn",
|
||||||
"names.fillFemale": "Slumpa ett kvinnonamn",
|
"names.fillFemale": "Slumpa ett kvinnonamn",
|
||||||
"names.fillMale": "Slumpa ett mansnamn",
|
"names.fillMale": "Slumpa ett mansnamn",
|
||||||
|
"nav.trash": "Papperskorg",
|
||||||
|
"trash.title": "Papperskorg",
|
||||||
|
"trash.books": "Borttagna böcker",
|
||||||
|
"trash.intro": "Borttaget ligger kvar här i {days} dagar och kan återställas. Därefter rensas det automatiskt.",
|
||||||
|
"trash.emptyState": "Papperskorgen är tom.",
|
||||||
|
"trash.empty": "Töm papperskorgen",
|
||||||
|
"trash.emptyConfirm": "Ta bort allt i papperskorgen för gott? Det kan inte ångras.",
|
||||||
|
"trash.restore": "Återställ",
|
||||||
|
"trash.purge": "Ta bort för gott",
|
||||||
|
"trash.purgeConfirm": "Ta bort för gott? Det kan inte ångras.",
|
||||||
|
"trash.moveConfirm": "Flytta till papperskorgen? Du kan återställa den i 30 dagar.",
|
||||||
|
"trash.deleted": "borttagen {date}",
|
||||||
|
"trash.daysLeft": "{n} dagar kvar",
|
||||||
|
"trash.restoreFailed": "Det gick inte att återställa. Boken eller posten kanske redan finns igen eller har tagits bort.",
|
||||||
|
"history.button": "Historik ({n})",
|
||||||
|
"history.title": "Historik: {name}",
|
||||||
|
"history.intro": "Tidigare versioner sparas varje gång något ändras (de {n} senaste behålls). Bilder ingår inte. Att återställa en version sparar först den nuvarande, så det går att ångra.",
|
||||||
|
"history.empty": "Inga tidigare versioner ännu.",
|
||||||
|
"history.noChanges": "Inga skillnader mot nästa version.",
|
||||||
|
"history.before": "Före",
|
||||||
|
"history.after": "Efter",
|
||||||
|
"history.restore": "Återställ den här versionen",
|
||||||
|
"history.restoreConfirm": "Återställa den här versionen? Den nuvarande sparas först i historiken.",
|
||||||
|
"nav.admin": "Administration",
|
||||||
|
"admin.title": "Administration",
|
||||||
|
"admin.intro": "Status, säkerhetskopior och mätvärden för hela installationen. Bara administratörer ser den här sidan.",
|
||||||
|
"admin.system": "System",
|
||||||
|
"admin.version": "Version",
|
||||||
|
"admin.node": "Node.js",
|
||||||
|
"admin.uptime": "Upptid",
|
||||||
|
"admin.memory": "Minne (RSS)",
|
||||||
|
"admin.data": "Data",
|
||||||
|
"admin.users": "Användare",
|
||||||
|
"admin.books": "Böcker",
|
||||||
|
"admin.entities": "Poster",
|
||||||
|
"admin.relations": "Relationer",
|
||||||
|
"admin.maps": "Kartor",
|
||||||
|
"admin.markers": "Markeringar",
|
||||||
|
"admin.dbSize": "Databasens storlek",
|
||||||
|
"admin.uploads": "Uppladdade bilder",
|
||||||
|
"admin.thumbs": "Miniatyrer",
|
||||||
|
"admin.trash": "Papperskorg",
|
||||||
|
"admin.trashSummary": "{entities} poster och {books} böcker (rensas efter {days} dagar)",
|
||||||
|
"admin.backup": "Säkerhetskopior",
|
||||||
|
"admin.backupSettings": "Schemalagd {enabled} kl {hour}:00, de {keep} senaste behålls. Mapp: {dir}",
|
||||||
|
"admin.backupOn": "på",
|
||||||
|
"admin.backupOff": "av",
|
||||||
|
"admin.backupNow": "Kör säkerhetskopia nu",
|
||||||
|
"admin.backupStarted": "Säkerhetskopieringen har startat. Ladda om sidan om en stund.",
|
||||||
|
"admin.backupLast": "Senaste körning",
|
||||||
|
"admin.backupNever": "Ingen körning ännu",
|
||||||
|
"admin.backupStatus.ok": "lyckades",
|
||||||
|
"admin.backupStatus.error": "misslyckades",
|
||||||
|
"admin.backupStatus.running": "pågår",
|
||||||
|
"admin.backupFiles": "{n} filer",
|
||||||
|
"admin.backupHelp": "Varje zip-fil kan importeras igen via Importera bok på startsidan.",
|
||||||
|
"admin.backupNone": "Inga säkerhetskopior ännu.",
|
||||||
|
"admin.services": "Externa tjänster",
|
||||||
|
"admin.servicesHelp": "Används av namngeneratorn. Kontrollen anropar tjänsterna direkt från servern.",
|
||||||
|
"admin.check": "Kontrollera",
|
||||||
|
"admin.observability": "Loggar och mätvärden",
|
||||||
|
"admin.logLevel": "Loggnivå",
|
||||||
|
"admin.metricsOn": "Mätvärden aktiva på /api/metrics (Bearer-token).",
|
||||||
|
"admin.metricsOff": "Mätvärden är avstängda. Sätt METRICS_TOKEN för att aktivera /api/metrics.",
|
||||||
|
"admin.rateLimit": "Anrop stoppade av hastighetsbegränsning sedan start: {n}",
|
||||||
|
"admin.download": "Ladda ner",
|
||||||
|
"nav.search": "Sök",
|
||||||
|
"palette.button": "Sök",
|
||||||
|
"palette.label": "Snabbsök",
|
||||||
|
"palette.placeholder": "Sök poster, sidor och åtgärder…",
|
||||||
|
"palette.placeholderNoBook": "Sök bland sidor…",
|
||||||
|
"palette.entities": "Poster",
|
||||||
|
"palette.pages": "Sidor",
|
||||||
|
"palette.create": "Skapa ny",
|
||||||
|
"palette.empty": "Inga träffar.",
|
||||||
|
"palette.hint": "↑↓ väljer, Enter öppnar, Esc stänger",
|
||||||
"nav.settings": "Bokinställningar",
|
"nav.settings": "Bokinställningar",
|
||||||
"nav.logout": "Logga ut",
|
"nav.logout": "Logga ut",
|
||||||
"nav.theme": "Växla tema",
|
"nav.theme": "Växla tema",
|
||||||
@@ -311,7 +387,7 @@ export const sv = {
|
|||||||
"settings.title": "Bokinställningar",
|
"settings.title": "Bokinställningar",
|
||||||
"settings.danger": "Farlig zon",
|
"settings.danger": "Farlig zon",
|
||||||
"settings.deleteBook": "Ta bort boken",
|
"settings.deleteBook": "Ta bort boken",
|
||||||
"settings.deleteBookHelp": "Raderar boken och allt innehåll permanent. Exportera först om du vill spara en kopia.",
|
"settings.deleteBookHelp": "Boken flyttas till papperskorgen och kan återställas i 30 dagar. Därefter raderas den permanent.",
|
||||||
"settings.export": "Exportera med bilder (.zip)",
|
"settings.export": "Exportera med bilder (.zip)",
|
||||||
"settings.exportJson": "Exportera bara data (.json)",
|
"settings.exportJson": "Exportera bara data (.json)",
|
||||||
"import.title": "Importera bok",
|
"import.title": "Importera bok",
|
||||||
@@ -322,6 +398,8 @@ export const sv = {
|
|||||||
"import.error.version": "exportfilens version stöds inte",
|
"import.error.version": "exportfilens version stöds inte",
|
||||||
"import.error.too-large": "filen är för stor",
|
"import.error.too-large": "filen är för stor",
|
||||||
"import.error.empty": "ingen fil valdes eller filen är tom",
|
"import.error.empty": "ingen fil valdes eller filen är tom",
|
||||||
|
"quota.exceeded": "Lagringskvoten för bilder är full. Ta bort bilder eller töm papperskorgen och försök igen.",
|
||||||
|
"import.error.quota": "lagringskvoten för bilder skulle överskridas",
|
||||||
"import.error.invalid": "filen är skadad eller har fel format",
|
"import.error.invalid": "filen är skadad eller har fel format",
|
||||||
"import.done": "Boken importerades: {entities} poster, {relations} relationer och {maps} kartor.",
|
"import.done": "Boken importerades: {entities} poster, {relations} relationer och {maps} kartor.",
|
||||||
"import.skipped": "{n} bilder eller kopplingar saknades i filen och hoppades över.",
|
"import.skipped": "{n} bilder eller kopplingar saknades i filen och hoppades över.",
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import type { Instrumentation } from "next";
|
||||||
|
|
||||||
|
// Körs en gång när servern startar. Schemaläggaren (säkerhetskopiering och papperskorg) hör bara hemma i Node-körmiljön.
|
||||||
|
export async function register() {
|
||||||
|
if (process.env.NEXT_RUNTIME === "nodejs") {
|
||||||
|
const { startScheduler } = await import("./lib/scheduler");
|
||||||
|
startScheduler();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fel på servern loggas som strukturerad JSON, med sidans sökväg men utan förfrågningens innehåll.
|
||||||
|
export const onRequestError: Instrumentation.onRequestError = async (error, request, context) => {
|
||||||
|
const { log } = await import("./lib/log");
|
||||||
|
const err = error as Error & { digest?: string };
|
||||||
|
log.error("Serverfel", {
|
||||||
|
error: err,
|
||||||
|
digest: err.digest,
|
||||||
|
path: request.path,
|
||||||
|
method: request.method,
|
||||||
|
route: context.routePath,
|
||||||
|
routeType: context.routeType,
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { cache } from "react";
|
||||||
|
import { prisma } from "./db";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Administratör är den vars e-postadress finns i ADMIN_EMAILS (kommaseparerad). Är variabeln inte satt är den
|
||||||
|
* äldsta användaren administratör, vilket passar en installation med en enda användare.
|
||||||
|
*/
|
||||||
|
export const isAdminUser = cache(async (userId: string, email: string | null): Promise<boolean> => {
|
||||||
|
const emails = (process.env.ADMIN_EMAILS ?? "")
|
||||||
|
.split(",")
|
||||||
|
.map((e) => e.trim().toLowerCase())
|
||||||
|
.filter(Boolean);
|
||||||
|
if (emails.length > 0) return !!email && emails.includes(email.toLowerCase());
|
||||||
|
|
||||||
|
const first = await prisma.user.findFirst({ orderBy: { createdAt: "asc" }, select: { id: true } });
|
||||||
|
return first?.id === userId;
|
||||||
|
});
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import { mkdir, readdir, rm, stat, writeFile } from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
import { strToU8, zipSync, type Zippable } from "fflate";
|
||||||
|
import { buildExport } from "./book-transfer";
|
||||||
|
import { prisma } from "./db";
|
||||||
|
import { log } from "./log";
|
||||||
|
|
||||||
|
// Automatisk säkerhetskopiering. Varje körning sparar en zip per bok (samma format som exporten, med bilder)
|
||||||
|
// i en mapp med tidsstämpel. Zip-filerna kan importeras igen via Importera bok. De senaste BACKUP_KEEP körningarna behålls.
|
||||||
|
|
||||||
|
export const BACKUP_DIR = path.resolve(process.env.BACKUP_DIR ?? "./data/backups");
|
||||||
|
export const BACKUP_ENABLED = process.env.BACKUP_ENABLED !== "false";
|
||||||
|
export const BACKUP_KEEP = Number(process.env.BACKUP_KEEP) || 14;
|
||||||
|
const hour = Number(process.env.BACKUP_HOUR);
|
||||||
|
export const BACKUP_HOUR = Number.isInteger(hour) && hour >= 0 && hour <= 23 ? hour : 3;
|
||||||
|
|
||||||
|
export const FOLDER_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}$/;
|
||||||
|
export const BACKUP_FILE_PATTERN = /^[A-Za-z0-9._-]{1,120}\.(zip|json)$/;
|
||||||
|
|
||||||
|
const safeName = (title: string) => title.replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-|-$/g, "").slice(0, 50) || "bok";
|
||||||
|
|
||||||
|
/** Kör en säkerhetskopiering av alla böcker. Returnerar körningens id. */
|
||||||
|
export async function runBackup(trigger: "schedule" | "manual"): Promise<string> {
|
||||||
|
const run = await prisma.backupRun.create({ data: { trigger, status: "running" } });
|
||||||
|
log.info("Säkerhetskopiering startad", { runId: run.id, trigger });
|
||||||
|
|
||||||
|
try {
|
||||||
|
const folder = new Date().toISOString().slice(0, 19).replace(/:/g, "-");
|
||||||
|
const dir = path.join(BACKUP_DIR, folder);
|
||||||
|
await mkdir(dir, { recursive: true });
|
||||||
|
|
||||||
|
const books = await prisma.book.findMany({
|
||||||
|
select: { id: true, title: true, owner: { select: { name: true, email: true } } },
|
||||||
|
orderBy: { createdAt: "asc" },
|
||||||
|
});
|
||||||
|
|
||||||
|
let bytes = 0;
|
||||||
|
const index: { bookId: string; title: string; owner: string | null; file: string; megabytes: number }[] = [];
|
||||||
|
for (const book of books) {
|
||||||
|
const { data, files } = await buildExport(book.id, true);
|
||||||
|
const entries: Zippable = { "book.json": strToU8(JSON.stringify(data)) };
|
||||||
|
for (const [name, content] of files) entries[`files/${name}`] = [content, { level: 0 }];
|
||||||
|
const zip = zipSync(entries);
|
||||||
|
const file = `${safeName(book.title)}-${book.id.slice(0, 8)}.zip`;
|
||||||
|
await writeFile(path.join(dir, file), zip);
|
||||||
|
bytes += zip.length;
|
||||||
|
index.push({ bookId: book.id, title: book.title, owner: book.owner.name ?? book.owner.email, file, megabytes: Math.round((zip.length / 1048576) * 100) / 100 });
|
||||||
|
}
|
||||||
|
await writeFile(path.join(dir, "index.json"), JSON.stringify({ createdAt: new Date().toISOString(), books: index }, null, 2));
|
||||||
|
|
||||||
|
await pruneBackups();
|
||||||
|
const done = await prisma.backupRun.update({
|
||||||
|
where: { id: run.id },
|
||||||
|
data: { status: "ok", finishedAt: new Date(), books: books.length, megabytes: Math.round((bytes / 1048576) * 100) / 100, folder },
|
||||||
|
});
|
||||||
|
log.info("Säkerhetskopiering klar", { runId: run.id, books: books.length, megabytes: done.megabytes, folder });
|
||||||
|
} catch (error) {
|
||||||
|
await prisma.backupRun.update({
|
||||||
|
where: { id: run.id },
|
||||||
|
data: { status: "error", finishedAt: new Date(), error: error instanceof Error ? error.message.slice(0, 500) : "Okänt fel" },
|
||||||
|
});
|
||||||
|
log.error("Säkerhetskopiering misslyckades", { runId: run.id, error });
|
||||||
|
}
|
||||||
|
return run.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type BackupFolder = { folder: string; files: { name: string; bytes: number }[]; bytes: number };
|
||||||
|
|
||||||
|
export async function listBackups(): Promise<BackupFolder[]> {
|
||||||
|
let folders: string[];
|
||||||
|
try {
|
||||||
|
folders = (await readdir(BACKUP_DIR)).filter((f) => FOLDER_PATTERN.test(f)).sort().reverse();
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
const result: BackupFolder[] = [];
|
||||||
|
for (const folder of folders) {
|
||||||
|
const names = (await readdir(path.join(BACKUP_DIR, folder))).filter((n) => BACKUP_FILE_PATTERN.test(n)).sort();
|
||||||
|
const files = await Promise.all(names.map(async (name) => ({ name, bytes: (await stat(path.join(BACKUP_DIR, folder, name))).size })));
|
||||||
|
result.push({ folder, files, bytes: files.reduce((sum, f) => sum + f.bytes, 0) });
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pruneBackups() {
|
||||||
|
const folders = (await readdir(BACKUP_DIR)).filter((f) => FOLDER_PATTERN.test(f)).sort().reverse();
|
||||||
|
for (const folder of folders.slice(BACKUP_KEEP)) {
|
||||||
|
await rm(path.join(BACKUP_DIR, folder), { recursive: true, force: true });
|
||||||
|
log.info("Gammal säkerhetskopia borttagen", { folder });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sant om det är dags för nattens säkerhetskopia: klockan har passerat BACKUP_HOUR och ingen körning har gjorts i dag. */
|
||||||
|
export async function backupDue(now = new Date()): Promise<boolean> {
|
||||||
|
if (!BACKUP_ENABLED || now.getHours() < BACKUP_HOUR) return false;
|
||||||
|
const startOfDay = new Date(now);
|
||||||
|
startOfDay.setHours(0, 0, 0, 0);
|
||||||
|
const recent = await prisma.backupRun.findFirst({
|
||||||
|
where: { startedAt: { gte: startOfDay }, OR: [{ status: "ok" }, { status: "running" }] },
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
return !recent;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Körningar som fastnat som "running" (t.ex. efter en omstart) markeras som misslyckade. */
|
||||||
|
export async function failStaleRuns() {
|
||||||
|
const limit = new Date(Date.now() - 60 * 60 * 1000);
|
||||||
|
await prisma.backupRun.updateMany({
|
||||||
|
where: { status: "running", startedAt: { lt: limit } },
|
||||||
|
data: { status: "error", finishedAt: new Date(), error: "Avbröts (servern startades om)" },
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -3,6 +3,8 @@ import { strFromU8, unzipSync } from "fflate";
|
|||||||
import type { EntityKind, Prisma, WeekPattern } from "@prisma/client";
|
import type { EntityKind, Prisma, WeekPattern } from "@prisma/client";
|
||||||
import { prisma } from "./db";
|
import { prisma } from "./db";
|
||||||
import { deleteImage, readImageBytes, saveImageBytes } from "./files";
|
import { deleteImage, readImageBytes, saveImageBytes } from "./files";
|
||||||
|
import type { ImageKind } from "./images";
|
||||||
|
import { withinQuota } from "./storage";
|
||||||
import { ENTITY_PREFIX, MAP_PREFIX, MARKER_PREFIX, RELATION_PREFIX, SCHEDULE_PREFIX, mapLetter, pad } from "./ids";
|
import { ENTITY_PREFIX, MAP_PREFIX, MARKER_PREFIX, RELATION_PREFIX, SCHEDULE_PREFIX, mapLetter, pad } from "./ids";
|
||||||
import { MARKER_COLORS, parseKind, parseTemplateKind } from "./kinds";
|
import { MARKER_COLORS, parseKind, parseTemplateKind } from "./kinds";
|
||||||
import { validateFields, type FieldDef } from "./templates";
|
import { validateFields, type FieldDef } from "./templates";
|
||||||
@@ -16,8 +18,8 @@ export const MAX_IMPORT_BYTES = 300 * 1024 * 1024;
|
|||||||
const MAX_FILE_BYTES = 16 * 1024 * 1024;
|
const MAX_FILE_BYTES = 16 * 1024 * 1024;
|
||||||
const MAX_ITEMS = 20000;
|
const MAX_ITEMS = 20000;
|
||||||
|
|
||||||
export type ImportErrorCode = "not-export" | "version" | "too-large" | "empty" | "invalid";
|
export type ImportErrorCode = "not-export" | "version" | "too-large" | "empty" | "invalid" | "quota";
|
||||||
export const IMPORT_ERROR_CODES: ImportErrorCode[] = ["not-export", "version", "too-large", "empty", "invalid"];
|
export const IMPORT_ERROR_CODES: ImportErrorCode[] = ["not-export", "version", "too-large", "empty", "invalid", "quota"];
|
||||||
|
|
||||||
export class ImportError extends Error {
|
export class ImportError extends Error {
|
||||||
constructor(
|
constructor(
|
||||||
@@ -441,10 +443,10 @@ export async function importBook(ownerId: string, data: ExportData, files: Map<s
|
|||||||
let skippedLinks = 0;
|
let skippedLinks = 0;
|
||||||
const savedImages: string[] = [];
|
const savedImages: string[] = [];
|
||||||
|
|
||||||
const saveImage = async (name: string | null): Promise<string | null> => {
|
const saveImage = async (name: string | null, kind: ImageKind = "entity"): Promise<string | null> => {
|
||||||
if (!name) return null;
|
if (!name) return null;
|
||||||
const bytes = files.get(name);
|
const bytes = files.get(name);
|
||||||
const saved = bytes ? await saveImageBytes(bytes) : null;
|
const saved = bytes ? await saveImageBytes(bytes, kind) : null;
|
||||||
if (!saved) {
|
if (!saved) {
|
||||||
skippedImages++;
|
skippedImages++;
|
||||||
return null;
|
return null;
|
||||||
@@ -454,6 +456,9 @@ export async function importBook(ownerId: string, data: ExportData, files: Map<s
|
|||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
const imageBytes = [...files.values()].reduce((sum, f) => sum + f.length, 0);
|
||||||
|
if (!(await withinQuota(ownerId, imageBytes))) throw new ImportError("quota");
|
||||||
|
|
||||||
// Samma namn som en befintlig bok får ett tillägg så att de går att skilja åt
|
// Samma namn som en befintlig bok får ett tillägg så att de går att skilja åt
|
||||||
const existingTitles = new Set((await prisma.book.findMany({ where: { ownerId }, select: { title: true } })).map((b) => b.title));
|
const existingTitles = new Set((await prisma.book.findMany({ where: { ownerId }, select: { title: true } })).map((b) => b.title));
|
||||||
const title = existingTitles.has(data.book.title) ? `${data.book.title} (import)` : data.book.title;
|
const title = existingTitles.has(data.book.title) ? `${data.book.title} (import)` : data.book.title;
|
||||||
@@ -496,7 +501,7 @@ export async function importBook(ownerId: string, data: ExportData, files: Map<s
|
|||||||
const entityImages = new Map<string, string | null>();
|
const entityImages = new Map<string, string | null>();
|
||||||
for (const e of entities) entityImages.set(e.id, await saveImage(e.image));
|
for (const e of entities) entityImages.set(e.id, await saveImage(e.image));
|
||||||
const mapImages = new Map<string, string | null>();
|
const mapImages = new Map<string, string | null>();
|
||||||
for (const m of maps) mapImages.set(m.id, await saveImage(m.image));
|
for (const m of maps) mapImages.set(m.id, await saveImage(m.image, "map"));
|
||||||
|
|
||||||
const sid = (id: string) => entityIds.get(id)!;
|
const sid = (id: string) => entityIds.get(id)!;
|
||||||
|
|
||||||
|
|||||||
+22
-36
@@ -1,17 +1,13 @@
|
|||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
|
import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
|
import { optimizeImage, type ImageKind } from "./images";
|
||||||
|
|
||||||
export const UPLOAD_DIR = path.resolve(process.env.UPLOAD_DIR ?? "./data/uploads");
|
export const UPLOAD_DIR = path.resolve(process.env.UPLOAD_DIR ?? "./data/uploads");
|
||||||
|
// Miniatyrer ligger i en egen mapp och skapas vid behov
|
||||||
|
export const THUMB_DIR = path.join(UPLOAD_DIR, "thumbs");
|
||||||
export const MAX_UPLOAD_BYTES = 15 * 1024 * 1024;
|
export const MAX_UPLOAD_BYTES = 15 * 1024 * 1024;
|
||||||
|
|
||||||
const EXTENSIONS: Record<string, string> = {
|
|
||||||
"image/png": "png",
|
|
||||||
"image/jpeg": "jpg",
|
|
||||||
"image/webp": "webp",
|
|
||||||
"image/gif": "gif",
|
|
||||||
};
|
|
||||||
|
|
||||||
export const CONTENT_TYPES: Record<string, string> = {
|
export const CONTENT_TYPES: Record<string, string> = {
|
||||||
png: "image/png",
|
png: "image/png",
|
||||||
jpg: "image/jpeg",
|
jpg: "image/jpeg",
|
||||||
@@ -25,48 +21,38 @@ export function isUpload(value: FormDataEntryValue | null): value is File {
|
|||||||
return typeof value === "object" && value !== null && value.size > 0;
|
return typeof value === "object" && value !== null && value.size > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Sparar en uppladdad bild och returnerar filnamnet. Kastar vid fel typ eller storlek. */
|
/** Bearbetar och sparar en bild som ligger i minnet. Returnerar filnamnet, eller null om den inte är en giltig bild. */
|
||||||
export async function saveImage(file: File): Promise<string> {
|
export async function saveImageBytes(bytes: Uint8Array, kind: ImageKind = "entity"): Promise<string | null> {
|
||||||
const ext = EXTENSIONS[file.type];
|
if (bytes.length > MAX_UPLOAD_BYTES) return null;
|
||||||
if (!ext) throw new Error("Unsupported image type");
|
const processed = await optimizeImage(bytes, kind);
|
||||||
if (file.size > MAX_UPLOAD_BYTES) throw new Error("Image is too large");
|
if (!processed) return null;
|
||||||
await mkdir(UPLOAD_DIR, { recursive: true });
|
await mkdir(UPLOAD_DIR, { recursive: true });
|
||||||
const name = `${randomUUID()}.${ext}`;
|
const name = `${randomUUID()}.${processed.ext}`;
|
||||||
await writeFile(path.join(UPLOAD_DIR, name), Buffer.from(await file.arrayBuffer()));
|
await writeFile(path.join(UPLOAD_DIR, name), processed.bytes);
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sparar en uppladdad bild. Kastar vid fel typ eller storlek. */
|
||||||
|
export async function saveImage(file: File, kind: ImageKind = "entity"): Promise<string> {
|
||||||
|
if (file.size > MAX_UPLOAD_BYTES) throw new Error("Image is too large");
|
||||||
|
const name = await saveImageBytes(new Uint8Array(await file.arrayBuffer()), kind);
|
||||||
|
if (!name) throw new Error("Unsupported image type");
|
||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function deleteImage(name: string | null | undefined) {
|
export async function deleteImage(name: string | null | undefined) {
|
||||||
if (!name || !FILE_NAME_PATTERN.test(name)) return;
|
if (!name || !FILE_NAME_PATTERN.test(name)) return;
|
||||||
|
for (const file of [path.join(UPLOAD_DIR, name), path.join(THUMB_DIR, `${name}.webp`)]) {
|
||||||
try {
|
try {
|
||||||
await unlink(path.join(UPLOAD_DIR, name));
|
await unlink(file);
|
||||||
} catch {
|
} catch {
|
||||||
// filen kan redan vara borta
|
// filen kan redan vara borta
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function fileUrl(name: string | null | undefined): string | null {
|
|
||||||
return name ? `/api/files/${name}` : null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Bildtyp utifrån filens första bytes (inte filnamnet), eller null om det inte är en tillåten bild. */
|
export function fileUrl(name: string | null | undefined, size?: "thumb"): string | null {
|
||||||
export function detectImageExt(bytes: Uint8Array): "png" | "jpg" | "webp" | "gif" | null {
|
return name ? `/api/files/${name}${size === "thumb" ? "?size=thumb" : ""}` : null;
|
||||||
const at = (i: number) => bytes[i];
|
|
||||||
if (bytes.length > 8 && at(0) === 0x89 && at(1) === 0x50 && at(2) === 0x4e && at(3) === 0x47) return "png";
|
|
||||||
if (bytes.length > 3 && at(0) === 0xff && at(1) === 0xd8 && at(2) === 0xff) return "jpg";
|
|
||||||
if (bytes.length > 6 && at(0) === 0x47 && at(1) === 0x49 && at(2) === 0x46 && at(3) === 0x38) return "gif";
|
|
||||||
if (bytes.length > 12 && at(0) === 0x52 && at(1) === 0x49 && at(2) === 0x46 && at(3) === 0x46 && at(8) === 0x57 && at(9) === 0x45 && at(10) === 0x42 && at(11) === 0x50) return "webp";
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Sparar en bild som redan ligger i minnet (t.ex. från en importfil). Returnerar filnamnet, eller null om bilden inte duger. */
|
|
||||||
export async function saveImageBytes(bytes: Uint8Array): Promise<string | null> {
|
|
||||||
const ext = detectImageExt(bytes);
|
|
||||||
if (!ext || bytes.length > MAX_UPLOAD_BYTES) return null;
|
|
||||||
await mkdir(UPLOAD_DIR, { recursive: true });
|
|
||||||
const name = `${randomUUID()}.${ext}`;
|
|
||||||
await writeFile(path.join(UPLOAD_DIR, name), bytes);
|
|
||||||
return name;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function readImageBytes(name: string | null | undefined): Promise<Buffer | null> {
|
export async function readImageBytes(name: string | null | undefined): Promise<Buffer | null> {
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
/** 1 536 000 → "1,5 MB" */
|
||||||
|
export function formatBytes(bytes: number): string {
|
||||||
|
if (bytes < 1024) return `${bytes} B`;
|
||||||
|
const units = ["KB", "MB", "GB", "TB"];
|
||||||
|
let value = bytes / 1024;
|
||||||
|
let unit = 0;
|
||||||
|
while (value >= 1024 && unit < units.length - 1) {
|
||||||
|
value /= 1024;
|
||||||
|
unit++;
|
||||||
|
}
|
||||||
|
return `${value.toFixed(value >= 100 ? 0 : 1).replace(".", ",")} ${units[unit]}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 93784 → "1 d 2 h 3 min" */
|
||||||
|
export function formatDuration(seconds: number): string {
|
||||||
|
const d = Math.floor(seconds / 86400);
|
||||||
|
const h = Math.floor((seconds % 86400) / 3600);
|
||||||
|
const m = Math.floor((seconds % 3600) / 60);
|
||||||
|
return [d ? `${d} d` : "", h || d ? `${h} h` : "", `${m} min`].filter(Boolean).join(" ");
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import type { Prisma } from "@prisma/client";
|
||||||
|
import { prisma } from "./db";
|
||||||
|
import type { FieldDef } from "./templates";
|
||||||
|
|
||||||
|
// Ändringshistorik för poster. Före varje ändring som faktiskt ändrar något sparas den tidigare versionen.
|
||||||
|
// Bilder ingår inte i historiken. De senaste MAX_VERSIONS versionerna per post behålls.
|
||||||
|
|
||||||
|
export const MAX_VERSIONS = Number(process.env.MAX_VERSIONS) || 30;
|
||||||
|
|
||||||
|
export type Snapshot = {
|
||||||
|
name: string;
|
||||||
|
summary: string | null;
|
||||||
|
tags: string[];
|
||||||
|
data: Record<string, unknown>;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Tx = Prisma.TransactionClient;
|
||||||
|
|
||||||
|
export function snapshotOf(entity: { name: string; summary: string | null; tags: string[]; data: unknown }): Snapshot {
|
||||||
|
return {
|
||||||
|
name: entity.name,
|
||||||
|
summary: entity.summary ?? null,
|
||||||
|
tags: entity.tags,
|
||||||
|
data: (entity.data && typeof entity.data === "object" && !Array.isArray(entity.data) ? entity.data : {}) as Record<string, unknown>,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Nyckelordningen i JSON kan skilja efter att databasen lagrat värdet, så jämförelsen sorterar nycklarna
|
||||||
|
function normalize(value: unknown): unknown {
|
||||||
|
if (Array.isArray(value)) return value.map(normalize);
|
||||||
|
if (value && typeof value === "object") {
|
||||||
|
return Object.fromEntries(Object.entries(value as Record<string, unknown>).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => [k, normalize(v)]));
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sameSnapshot(a: Snapshot, b: Snapshot): boolean {
|
||||||
|
return JSON.stringify(normalize(a)) === JSON.stringify(normalize(b));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sparar den tidigare versionen av posten och rensar bort de äldsta över gränsen. */
|
||||||
|
export async function recordVersion(tx: Tx, bookId: string, entityId: string, userId: string | null, before: Snapshot) {
|
||||||
|
await tx.entityVersion.create({ data: { bookId, entityId, userId, snapshot: before as unknown as Prisma.InputJsonObject } });
|
||||||
|
const old = await tx.entityVersion.findMany({
|
||||||
|
where: { entityId },
|
||||||
|
orderBy: { createdAt: "desc" },
|
||||||
|
skip: MAX_VERSIONS,
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
if (old.length > 0) await tx.entityVersion.deleteMany({ where: { id: { in: old.map((v) => v.id) } } });
|
||||||
|
}
|
||||||
|
|
||||||
|
export type FieldChange = { label: string; before: string; after: string };
|
||||||
|
|
||||||
|
const show = (value: unknown): string => {
|
||||||
|
if (value === null || value === undefined || value === "") return "";
|
||||||
|
if (value === true) return "✓";
|
||||||
|
if (value === false) return "";
|
||||||
|
if (Array.isArray(value)) return value.join(", ");
|
||||||
|
return String(value);
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Skillnaderna mellan två versioner, med mallens fältnamn. Etiketter för grundfälten skickas in (översatta). */
|
||||||
|
export function diffSnapshots(
|
||||||
|
older: Snapshot,
|
||||||
|
newer: Snapshot,
|
||||||
|
fields: FieldDef[],
|
||||||
|
labels: { name: string; summary: string; tags: string },
|
||||||
|
): FieldChange[] {
|
||||||
|
const changes: FieldChange[] = [];
|
||||||
|
const push = (label: string, before: unknown, after: unknown) => {
|
||||||
|
const b = show(before);
|
||||||
|
const a = show(after);
|
||||||
|
if (b !== a) changes.push({ label, before: b, after: a });
|
||||||
|
};
|
||||||
|
|
||||||
|
push(labels.name, older.name, newer.name);
|
||||||
|
push(labels.summary, older.summary, newer.summary);
|
||||||
|
push(labels.tags, older.tags, newer.tags);
|
||||||
|
|
||||||
|
const known = new Set(fields.map((f) => f.key));
|
||||||
|
for (const field of fields) push(field.label, older.data[field.key], newer.data[field.key]);
|
||||||
|
// Värden för fält som inte längre finns i mallen
|
||||||
|
for (const key of new Set([...Object.keys(older.data), ...Object.keys(newer.data)])) {
|
||||||
|
if (!known.has(key)) push(key, older.data[key], newer.data[key]);
|
||||||
|
}
|
||||||
|
return changes;
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import sharp from "sharp";
|
||||||
|
|
||||||
|
// Bildbearbetning vid uppladdning: rätt rotation enligt EXIF, nedskalning, omkomprimering och borttagning av
|
||||||
|
// metadata (t.ex. GPS-position). Animerade GIF-bilder lämnas orörda.
|
||||||
|
|
||||||
|
export type ImageExt = "png" | "jpg" | "webp" | "gif";
|
||||||
|
export type ImageKind = "entity" | "map";
|
||||||
|
|
||||||
|
// Längsta sida i pixlar. Kartbilder behöver mer upplösning än porträtt.
|
||||||
|
const MAX_SIDE: Record<ImageKind, number> = { entity: 2400, map: 6000 };
|
||||||
|
export const THUMB_SIDE = 480;
|
||||||
|
|
||||||
|
export function detectImageExt(bytes: Uint8Array): ImageExt | null {
|
||||||
|
const at = (i: number) => bytes[i];
|
||||||
|
if (bytes.length > 8 && at(0) === 0x89 && at(1) === 0x50 && at(2) === 0x4e && at(3) === 0x47) return "png";
|
||||||
|
if (bytes.length > 3 && at(0) === 0xff && at(1) === 0xd8 && at(2) === 0xff) return "jpg";
|
||||||
|
if (bytes.length > 6 && at(0) === 0x47 && at(1) === 0x49 && at(2) === 0x46 && at(3) === 0x38) return "gif";
|
||||||
|
if (bytes.length > 12 && at(0) === 0x52 && at(1) === 0x49 && at(2) === 0x46 && at(3) === 0x46 && at(8) === 0x57 && at(9) === 0x45 && at(10) === 0x42 && at(11) === 0x50) return "webp";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bearbetar en bild. Returnerar null om filen inte är en giltig bild. */
|
||||||
|
export async function optimizeImage(input: Uint8Array, kind: ImageKind): Promise<{ bytes: Uint8Array; ext: ImageExt } | null> {
|
||||||
|
const ext = detectImageExt(input);
|
||||||
|
if (!ext) return null;
|
||||||
|
if (ext === "gif") return { bytes: input, ext };
|
||||||
|
|
||||||
|
try {
|
||||||
|
let pipeline = sharp(input, { failOn: "error" })
|
||||||
|
.rotate() // lägger bilden rätt enligt EXIF och tar bort orienteringsflaggan
|
||||||
|
.resize({ width: MAX_SIDE[kind], height: MAX_SIDE[kind], fit: "inside", withoutEnlargement: true });
|
||||||
|
if (ext === "png") pipeline = pipeline.png({ compressionLevel: 9, effort: 7 });
|
||||||
|
else if (ext === "jpg") pipeline = pipeline.jpeg({ quality: 85, mozjpeg: true });
|
||||||
|
else pipeline = pipeline.webp({ quality: 85 });
|
||||||
|
return { bytes: new Uint8Array(await pipeline.toBuffer()), ext };
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Liten WebP-bild för listor. */
|
||||||
|
export async function makeThumbnail(input: Uint8Array): Promise<Uint8Array> {
|
||||||
|
const buffer = await sharp(input, { failOn: "none" })
|
||||||
|
.rotate()
|
||||||
|
.resize({ width: THUMB_SIDE, height: THUMB_SIDE, fit: "inside", withoutEnlargement: true })
|
||||||
|
.webp({ quality: 78 })
|
||||||
|
.toBuffer();
|
||||||
|
return new Uint8Array(buffer);
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
// Enkel strukturerad loggning till stdout. JSON i produktion (en rad per händelse, lätt att samla in med
|
||||||
|
// Loki, Elastic och liknande), läsbar text i utveckling. Nivå styrs av LOG_LEVEL (debug, info, warn, error).
|
||||||
|
|
||||||
|
type Level = "debug" | "info" | "warn" | "error";
|
||||||
|
const ORDER: Record<Level, number> = { debug: 10, info: 20, warn: 30, error: 40 };
|
||||||
|
|
||||||
|
const threshold = ORDER[(process.env.LOG_LEVEL as Level) ?? "info"] ?? ORDER.info;
|
||||||
|
const asJson = process.env.LOG_FORMAT ? process.env.LOG_FORMAT === "json" : process.env.NODE_ENV === "production";
|
||||||
|
|
||||||
|
function serialize(value: unknown): unknown {
|
||||||
|
if (value instanceof Error) return { name: value.name, message: value.message, stack: value.stack };
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function write(level: Level, message: string, fields?: Record<string, unknown>) {
|
||||||
|
if (ORDER[level] < threshold) return;
|
||||||
|
const clean = fields ? Object.fromEntries(Object.entries(fields).map(([k, v]) => [k, serialize(v)])) : {};
|
||||||
|
const out = level === "error" || level === "warn" ? console.error : console.log;
|
||||||
|
if (asJson) {
|
||||||
|
out(JSON.stringify({ time: new Date().toISOString(), level, msg: message, ...clean }));
|
||||||
|
} else {
|
||||||
|
const extra = Object.keys(clean).length ? ` ${JSON.stringify(clean)}` : "";
|
||||||
|
out(`[${level}] ${message}${extra}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const log = {
|
||||||
|
debug: (message: string, fields?: Record<string, unknown>) => write("debug", message, fields),
|
||||||
|
info: (message: string, fields?: Record<string, unknown>) => write("info", message, fields),
|
||||||
|
warn: (message: string, fields?: Record<string, unknown>) => write("warn", message, fields),
|
||||||
|
error: (message: string, fields?: Record<string, unknown>) => write("error", message, fields),
|
||||||
|
};
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
// Hastighetsbegränsning i minnet (per process). Räcker för en enskild container och skyddar mot
|
||||||
|
// inloggningsförsök i flod och upprepade tunga anrop (import, export, namnstatistik).
|
||||||
|
|
||||||
|
const hits = new Map<string, number[]>();
|
||||||
|
|
||||||
|
export const rateLimitStats = { blocked: 0 };
|
||||||
|
|
||||||
|
export function clientIp(req: Request): string {
|
||||||
|
const forwarded = req.headers.get("x-forwarded-for")?.split(",")[0]?.trim();
|
||||||
|
return forwarded || req.headers.get("x-real-ip") || "unknown";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Tillåter högst `limit` anrop per `windowMs` för nyckeln. Returnerar ok=false och sekunder att vänta annars. */
|
||||||
|
export function rateLimit(key: string, limit: number, windowMs: number): { ok: boolean; retryAfter: number } {
|
||||||
|
const now = Date.now();
|
||||||
|
const recent = (hits.get(key) ?? []).filter((t) => now - t < windowMs);
|
||||||
|
|
||||||
|
if (recent.length >= limit) {
|
||||||
|
hits.set(key, recent);
|
||||||
|
rateLimitStats.blocked++;
|
||||||
|
return { ok: false, retryAfter: Math.max(1, Math.ceil((windowMs - (now - recent[0])) / 1000)) };
|
||||||
|
}
|
||||||
|
|
||||||
|
recent.push(now);
|
||||||
|
hits.set(key, recent);
|
||||||
|
|
||||||
|
// Städa bort gamla nycklar så att minnet inte växer
|
||||||
|
if (hits.size > 5000) {
|
||||||
|
for (const [k, times] of hits) if (times.every((t) => now - t >= windowMs)) hits.delete(k);
|
||||||
|
}
|
||||||
|
return { ok: true, retryAfter: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Färdigt 429-svar om gränsen är nådd, annars null. */
|
||||||
|
export function limitRequest(req: Request, name: string, limit: number, windowMs: number): Response | null {
|
||||||
|
const result = rateLimit(`${name}:${clientIp(req)}`, limit, windowMs);
|
||||||
|
if (result.ok) return null;
|
||||||
|
return new Response("Too many requests", { status: 429, headers: { "Retry-After": String(result.retryAfter) } });
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { backupDue, failStaleRuns, runBackup } from "./backup";
|
||||||
|
import { log } from "./log";
|
||||||
|
import { purgeExpiredTrash } from "./trash";
|
||||||
|
|
||||||
|
// Bakgrundsjobb i samma process: nattlig säkerhetskopiering och rensning av papperskorgen.
|
||||||
|
// Startas en gång från instrumentation.ts. Kontrollen körs var 15:e minut.
|
||||||
|
|
||||||
|
const TICK_MS = 15 * 60 * 1000;
|
||||||
|
const globalState = globalThis as unknown as { __bookmanagerScheduler?: boolean };
|
||||||
|
|
||||||
|
async function tick() {
|
||||||
|
try {
|
||||||
|
await failStaleRuns();
|
||||||
|
const purged = await purgeExpiredTrash();
|
||||||
|
if (purged > 0) log.info("Papperskorgen rensad", { purged });
|
||||||
|
if (await backupDue()) await runBackup("schedule");
|
||||||
|
} catch (error) {
|
||||||
|
log.error("Schemalagt jobb misslyckades", { error });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function startScheduler() {
|
||||||
|
if (globalState.__bookmanagerScheduler) return;
|
||||||
|
globalState.__bookmanagerScheduler = true;
|
||||||
|
// Första kontrollen strax efter start, så att databasen hunnit bli redo och en missad körning tas igen
|
||||||
|
setTimeout(() => void tick(), 60_000).unref();
|
||||||
|
setInterval(() => void tick(), TICK_MS).unref();
|
||||||
|
log.info("Schemaläggare startad");
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
// Säkerhetsrubriker som beror på miljön och därför sätts vid körning (i middleware), inte vid bygget.
|
||||||
|
// Statiska rubriker (nosniff, frame, referrer) ligger i next.config.mjs.
|
||||||
|
// Edge-säker: inga Node-API:er.
|
||||||
|
|
||||||
|
function origin(url: string | undefined): string | null {
|
||||||
|
if (!url) return null;
|
||||||
|
try {
|
||||||
|
// {s} är platshållare för underdomäner i tilldatans adress, t.ex. https://{s}.tile.example.com/{z}/{x}/{y}.png
|
||||||
|
const hasSubdomain = url.includes("{s}");
|
||||||
|
const parsed = new URL(url.replace("{s}", "a").replace("{z}", "0").replace("{x}", "0").replace("{y}", "0"));
|
||||||
|
return hasSubdomain ? `${parsed.protocol}//*.${parsed.host.replace(/^a\./, "")}` : parsed.origin;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function contentSecurityPolicy(): string {
|
||||||
|
const dev = process.env.NODE_ENV !== "production";
|
||||||
|
const tiles = origin(process.env.MAP_TILE_URL ?? "https://tile.openstreetmap.org/{z}/{x}/{y}.png");
|
||||||
|
const geocoder = origin(process.env.MAP_GEOCODER_URL ?? "https://nominatim.openstreetmap.org/search");
|
||||||
|
|
||||||
|
const directives: Record<string, string[]> = {
|
||||||
|
"default-src": ["'self'"],
|
||||||
|
// Next.js lägger in små inline-skript för hydrering, så 'unsafe-inline' krävs utan nonce-hantering
|
||||||
|
"script-src": ["'self'", "'unsafe-inline'", ...(dev ? ["'unsafe-eval'"] : [])],
|
||||||
|
"style-src": ["'self'", "'unsafe-inline'"],
|
||||||
|
"img-src": ["'self'", "data:", "blob:", ...(tiles ? [tiles] : [])],
|
||||||
|
"font-src": ["'self'", "data:"],
|
||||||
|
"connect-src": ["'self'", ...(geocoder ? [geocoder] : []), ...(dev ? ["ws:", "wss:"] : [])],
|
||||||
|
"frame-ancestors": ["'none'"],
|
||||||
|
"base-uri": ["'self'"],
|
||||||
|
"object-src": ["'none'"],
|
||||||
|
};
|
||||||
|
return Object.entries(directives)
|
||||||
|
.map(([name, values]) => `${name} ${values.join(" ")}`)
|
||||||
|
.join("; ");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rubriker som sätts på varje sida via middleware. */
|
||||||
|
export function runtimeSecurityHeaders(): Record<string, string> {
|
||||||
|
const headers: Record<string, string> = { "Content-Security-Policy": contentSecurityPolicy() };
|
||||||
|
// HSTS bara när adressen är https, annars låser man ute sig själv vid lokal körning över http
|
||||||
|
if (process.env.AUTH_URL?.startsWith("https://")) {
|
||||||
|
headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains";
|
||||||
|
}
|
||||||
|
return headers;
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { cache } from "react";
|
import { cache } from "react";
|
||||||
import { notFound, redirect } from "next/navigation";
|
import { notFound, redirect } from "next/navigation";
|
||||||
import { auth } from "@/auth";
|
import { auth } from "@/auth";
|
||||||
|
import { isAdminUser } from "./admin";
|
||||||
import { prisma } from "./db";
|
import { prisma } from "./db";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -31,6 +32,13 @@ export async function requireUser() {
|
|||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Kräver att inloggad användare är administratör, annars 404. */
|
||||||
|
export async function requireAdmin() {
|
||||||
|
const user = await requireUser();
|
||||||
|
if (!(await isAdminUser(user.id, user.email ?? null))) notFound();
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
/** Hämtar boken om den tillhör inloggad användare, annars 404. */
|
/** Hämtar boken om den tillhör inloggad användare, annars 404. */
|
||||||
export async function requireBook(bookId: string) {
|
export async function requireBook(bookId: string) {
|
||||||
const user = await requireUser();
|
const user = await requireUser();
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { stat } from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
import { prisma } from "./db";
|
||||||
|
import { FILE_NAME_PATTERN, UPLOAD_DIR } from "./files";
|
||||||
|
|
||||||
|
// Lagringskvot per användare för uppladdade bilder (USER_QUOTA_MB, standard 2048). Bilder i papperskorgen räknas med.
|
||||||
|
export const USER_QUOTA_BYTES = (Number(process.env.USER_QUOTA_MB) || 2048) * 1024 * 1024;
|
||||||
|
|
||||||
|
/** Filnamn på alla bilder som tillhör användaren, även sådana som ligger i papperskorgen. */
|
||||||
|
export async function userImageNames(ownerId: string): Promise<string[]> {
|
||||||
|
const [entities, maps, trash] = await Promise.all([
|
||||||
|
prisma.entity.findMany({ where: { book: { ownerId }, imageFile: { not: null } }, select: { imageFile: true } }),
|
||||||
|
prisma.bookMap.findMany({ where: { book: { ownerId }, imageFile: { not: null } }, select: { imageFile: true } }),
|
||||||
|
prisma.trashItem.findMany({ where: { ownerId, kind: "entity" }, select: { payload: true } }),
|
||||||
|
]);
|
||||||
|
const names = new Set<string>();
|
||||||
|
for (const row of [...entities, ...maps]) if (row.imageFile) names.add(row.imageFile);
|
||||||
|
for (const item of trash) {
|
||||||
|
const image = ((item.payload as { entity?: { imageFile?: string | null } } | null)?.entity ?? {}).imageFile;
|
||||||
|
if (image) names.add(image);
|
||||||
|
}
|
||||||
|
return [...names].filter((n) => FILE_NAME_PATTERN.test(n));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fileSize(name: string): Promise<number> {
|
||||||
|
try {
|
||||||
|
return (await stat(path.join(UPLOAD_DIR, name))).size;
|
||||||
|
} catch {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function userStorageBytes(ownerId: string): Promise<number> {
|
||||||
|
const sizes = await Promise.all((await userImageNames(ownerId)).map(fileSize));
|
||||||
|
return sizes.reduce((sum, n) => sum + n, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sant om användaren ryms inom kvoten med ytterligare `extraBytes`. */
|
||||||
|
export async function withinQuota(ownerId: string, extraBytes: number): Promise<boolean> {
|
||||||
|
return (await userStorageBytes(ownerId)) + extraBytes <= USER_QUOTA_BYTES;
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
import { readdir, stat } from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
import { listBackups, BACKUP_DIR, BACKUP_ENABLED, BACKUP_HOUR, BACKUP_KEEP } from "./backup";
|
||||||
|
import { prisma } from "./db";
|
||||||
|
import { THUMB_DIR, UPLOAD_DIR } from "./files";
|
||||||
|
import { rateLimitStats } from "./rate-limit";
|
||||||
|
import { TRASH_DAYS, TRASH_DIR } from "./trash";
|
||||||
|
import { APP_VERSION_LABEL } from "./version";
|
||||||
|
|
||||||
|
async function directorySize(dir: string, recursive = false): Promise<{ files: number; bytes: number }> {
|
||||||
|
let files = 0;
|
||||||
|
let bytes = 0;
|
||||||
|
try {
|
||||||
|
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
||||||
|
const full = path.join(dir, entry.name);
|
||||||
|
if (entry.isDirectory()) {
|
||||||
|
if (recursive) {
|
||||||
|
const sub = await directorySize(full, true);
|
||||||
|
files += sub.files;
|
||||||
|
bytes += sub.bytes;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
files++;
|
||||||
|
bytes += (await stat(full)).size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// mappen finns inte än
|
||||||
|
}
|
||||||
|
return { files, bytes };
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SystemStats = Awaited<ReturnType<typeof collectStats>>;
|
||||||
|
|
||||||
|
/** Samlar status för adminsidan och /api/metrics. */
|
||||||
|
export async function collectStats() {
|
||||||
|
const [users, books, entities, relations, maps, markers, trashEntities, trashBooks, dbSize, lastRun, lastOk, runsOk, runsError] = await Promise.all([
|
||||||
|
prisma.user.count(),
|
||||||
|
prisma.book.count(),
|
||||||
|
prisma.entity.count(),
|
||||||
|
prisma.relation.count(),
|
||||||
|
prisma.bookMap.count(),
|
||||||
|
prisma.marker.count(),
|
||||||
|
prisma.trashItem.count({ where: { kind: "entity" } }),
|
||||||
|
prisma.trashItem.count({ where: { kind: "book" } }),
|
||||||
|
prisma.$queryRaw<{ size: bigint }[]>`SELECT pg_database_size(current_database()) AS size`,
|
||||||
|
prisma.backupRun.findFirst({ orderBy: { startedAt: "desc" } }),
|
||||||
|
prisma.backupRun.findFirst({ where: { status: "ok" }, orderBy: { startedAt: "desc" } }),
|
||||||
|
prisma.backupRun.count({ where: { status: "ok" } }),
|
||||||
|
prisma.backupRun.count({ where: { status: "error" } }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const [uploads, thumbs, trashFiles] = await Promise.all([directorySize(UPLOAD_DIR), directorySize(THUMB_DIR), directorySize(TRASH_DIR)]);
|
||||||
|
const backups = await listBackups();
|
||||||
|
const memory = process.memoryUsage();
|
||||||
|
|
||||||
|
return {
|
||||||
|
version: APP_VERSION_LABEL,
|
||||||
|
node: process.version,
|
||||||
|
uptimeSeconds: Math.round(process.uptime()),
|
||||||
|
memory: { rss: memory.rss, heapUsed: memory.heapUsed },
|
||||||
|
counts: { users, books, entities, relations, maps, markers },
|
||||||
|
database: { bytes: Number(dbSize[0]?.size ?? 0) },
|
||||||
|
uploads,
|
||||||
|
thumbs,
|
||||||
|
trash: { entities: trashEntities, books: trashBooks, files: trashFiles, days: TRASH_DAYS },
|
||||||
|
backup: {
|
||||||
|
enabled: BACKUP_ENABLED,
|
||||||
|
hour: BACKUP_HOUR,
|
||||||
|
keep: BACKUP_KEEP,
|
||||||
|
dir: BACKUP_DIR,
|
||||||
|
lastRun,
|
||||||
|
lastOk,
|
||||||
|
runsOk,
|
||||||
|
runsError,
|
||||||
|
folders: backups,
|
||||||
|
bytes: backups.reduce((sum, b) => sum + b.bytes, 0),
|
||||||
|
},
|
||||||
|
rateLimitBlocked: rateLimitStats.blocked,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ServiceCheck = { name: string; url: string; ok: boolean; ms: number; detail: string };
|
||||||
|
|
||||||
|
/** Kontrollerar att de externa tjänsterna som namnstatistiken använder går att nå. */
|
||||||
|
export async function checkExternalServices(): Promise<ServiceCheck[]> {
|
||||||
|
const targets = [
|
||||||
|
{ name: "SCB (statistik)", url: "https://api.scb.se/OV0104/v1/doris/sv/ssd/BE/BE0001/" },
|
||||||
|
{ name: "Skatteverket (namn på nyfödda)", url: "https://skatteverket.entryscape.net/rowstore/dataset/da2556d0-c717-45e8-a1d8-3320161d3a7d?_limit=1" },
|
||||||
|
];
|
||||||
|
return Promise.all(
|
||||||
|
targets.map(async ({ name, url }) => {
|
||||||
|
const started = Date.now();
|
||||||
|
try {
|
||||||
|
const res = await fetch(url, { signal: AbortSignal.timeout(6000), headers: { Accept: "application/json" } });
|
||||||
|
return { name, url, ok: res.ok, ms: Date.now() - started, detail: `HTTP ${res.status}` };
|
||||||
|
} catch (error) {
|
||||||
|
return { name, url, ok: false, ms: Date.now() - started, detail: error instanceof Error ? error.message : "fel" };
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,288 @@
|
|||||||
|
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
import { strToU8, zipSync, type Zippable } from "fflate";
|
||||||
|
import type { EntityKind, Prisma, WeekPattern } from "@prisma/client";
|
||||||
|
import { buildExport, importBook, readImportFile } from "./book-transfer";
|
||||||
|
import { prisma } from "./db";
|
||||||
|
import { deleteImage } from "./files";
|
||||||
|
import { nextEntityCode, nextRelationCode } from "./ids";
|
||||||
|
import { log } from "./log";
|
||||||
|
|
||||||
|
// Papperskorg. Borttagna poster sparas som en ögonblicksbild i databasen (med relationer, scheman och markeringar),
|
||||||
|
// borttagna böcker som en zip-fil på disk (samma format som exporten). Rensas automatiskt efter TRASH_DAYS.
|
||||||
|
|
||||||
|
export const TRASH_DAYS = Number(process.env.TRASH_DAYS) || 30;
|
||||||
|
export const TRASH_DIR = path.resolve(process.env.TRASH_DIR ?? "./data/trash");
|
||||||
|
|
||||||
|
type Snapshot = {
|
||||||
|
entity: {
|
||||||
|
id: string;
|
||||||
|
bookId: string;
|
||||||
|
kind: EntityKind;
|
||||||
|
name: string;
|
||||||
|
code: string | null;
|
||||||
|
summary: string | null;
|
||||||
|
imageFile: string | null;
|
||||||
|
tags: string[];
|
||||||
|
data: Prisma.JsonValue;
|
||||||
|
};
|
||||||
|
relations: {
|
||||||
|
id: string;
|
||||||
|
code: string | null;
|
||||||
|
fromId: string;
|
||||||
|
toId: string;
|
||||||
|
type: string;
|
||||||
|
description: string | null;
|
||||||
|
data: Prisma.JsonValue;
|
||||||
|
members: string[];
|
||||||
|
}[];
|
||||||
|
memberOf: string[]; // relationer som posten deltog i som extra deltagare
|
||||||
|
shifts: {
|
||||||
|
workplaceId: string | null;
|
||||||
|
weekday: number;
|
||||||
|
startTime: string;
|
||||||
|
endTime: string;
|
||||||
|
weeks: WeekPattern;
|
||||||
|
label: string | null;
|
||||||
|
scheduleCode: string | null;
|
||||||
|
}[];
|
||||||
|
hostedShiftIds: string[]; // pass som hade posten som arbetsplats
|
||||||
|
markerIds: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
// ─── Poster ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** Flyttar en post till papperskorgen. Bilden behålls tills posten återställs eller rensas. */
|
||||||
|
export async function trashEntity(ownerId: string, bookId: string, entityId: string) {
|
||||||
|
const entity = await prisma.entity.findFirstOrThrow({
|
||||||
|
where: { id: entityId, bookId },
|
||||||
|
include: {
|
||||||
|
outgoing: { include: { members: true } },
|
||||||
|
incoming: { include: { members: true } },
|
||||||
|
memberOf: true,
|
||||||
|
shifts: true,
|
||||||
|
hostedShifts: { select: { id: true } },
|
||||||
|
markers: { select: { id: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const snapshot: Snapshot = {
|
||||||
|
entity: {
|
||||||
|
id: entity.id,
|
||||||
|
bookId: entity.bookId,
|
||||||
|
kind: entity.kind,
|
||||||
|
name: entity.name,
|
||||||
|
code: entity.code,
|
||||||
|
summary: entity.summary,
|
||||||
|
imageFile: entity.imageFile,
|
||||||
|
tags: entity.tags,
|
||||||
|
data: entity.data,
|
||||||
|
},
|
||||||
|
relations: [...entity.outgoing, ...entity.incoming].map((r) => ({
|
||||||
|
id: r.id,
|
||||||
|
code: r.code,
|
||||||
|
fromId: r.fromId,
|
||||||
|
toId: r.toId,
|
||||||
|
type: r.type,
|
||||||
|
description: r.description,
|
||||||
|
data: r.data,
|
||||||
|
members: r.members.map((m) => m.entityId),
|
||||||
|
})),
|
||||||
|
memberOf: entity.memberOf.map((m) => m.relationId),
|
||||||
|
shifts: entity.shifts.map((s) => ({
|
||||||
|
workplaceId: s.workplaceId,
|
||||||
|
weekday: s.weekday,
|
||||||
|
startTime: s.startTime,
|
||||||
|
endTime: s.endTime,
|
||||||
|
weeks: s.weeks,
|
||||||
|
label: s.label,
|
||||||
|
scheduleCode: s.scheduleCode,
|
||||||
|
})),
|
||||||
|
hostedShiftIds: entity.hostedShifts.map((s) => s.id),
|
||||||
|
markerIds: entity.markers.map((m) => m.id),
|
||||||
|
};
|
||||||
|
|
||||||
|
await prisma.$transaction([
|
||||||
|
prisma.trashItem.create({
|
||||||
|
data: {
|
||||||
|
ownerId,
|
||||||
|
bookId,
|
||||||
|
kind: "entity",
|
||||||
|
label: entity.name,
|
||||||
|
detail: entity.kind,
|
||||||
|
payload: snapshot as unknown as Prisma.InputJsonObject,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
prisma.entity.delete({ where: { id: entity.id } }),
|
||||||
|
]);
|
||||||
|
log.info("Post flyttad till papperskorgen", { entityId, bookId, kind: entity.kind });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Återställer en post. Returnerar bokens och postens id, eller null om boken inte längre finns. */
|
||||||
|
export async function restoreEntity(ownerId: string, trashId: string): Promise<{ bookId: string; entityId: string } | null> {
|
||||||
|
const item = await prisma.trashItem.findFirst({ where: { id: trashId, ownerId, kind: "entity" } });
|
||||||
|
const snap = item?.payload as unknown as Snapshot | null;
|
||||||
|
if (!item || !snap) return null;
|
||||||
|
|
||||||
|
const bookId = snap.entity.bookId;
|
||||||
|
const book = await prisma.book.findFirst({ where: { id: bookId, ownerId }, select: { id: true } });
|
||||||
|
if (!book) return null;
|
||||||
|
if (await prisma.entity.findUnique({ where: { id: snap.entity.id }, select: { id: true } })) return null;
|
||||||
|
|
||||||
|
await prisma.$transaction(async (tx) => {
|
||||||
|
// Koden behålls om den är ledig, annars får posten en ny
|
||||||
|
const codeTaken = snap.entity.code ? await tx.entity.findFirst({ where: { bookId, code: snap.entity.code }, select: { id: true } }) : null;
|
||||||
|
const code = snap.entity.code && !codeTaken ? snap.entity.code : await nextEntityCode(bookId, snap.entity.kind, tx);
|
||||||
|
|
||||||
|
await tx.entity.create({
|
||||||
|
data: {
|
||||||
|
id: snap.entity.id,
|
||||||
|
bookId,
|
||||||
|
kind: snap.entity.kind,
|
||||||
|
name: snap.entity.name,
|
||||||
|
code,
|
||||||
|
summary: snap.entity.summary,
|
||||||
|
imageFile: snap.entity.imageFile,
|
||||||
|
tags: snap.entity.tags,
|
||||||
|
data: (snap.entity.data ?? {}) as Prisma.InputJsonObject,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const others = new Set(
|
||||||
|
(await tx.entity.findMany({ where: { bookId }, select: { id: true } })).map((e) => e.id),
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const r of snap.relations) {
|
||||||
|
if (!others.has(r.fromId) || !others.has(r.toId)) continue; // den andra parten är borta
|
||||||
|
if (await tx.relation.findUnique({ where: { id: r.id }, select: { id: true } })) continue;
|
||||||
|
const taken = r.code ? await tx.relation.findFirst({ where: { bookId, code: r.code }, select: { id: true } }) : null;
|
||||||
|
await tx.relation.create({
|
||||||
|
data: {
|
||||||
|
id: r.id,
|
||||||
|
bookId,
|
||||||
|
code: r.code && !taken ? r.code : await nextRelationCode(bookId, tx),
|
||||||
|
fromId: r.fromId,
|
||||||
|
toId: r.toId,
|
||||||
|
type: r.type,
|
||||||
|
description: r.description,
|
||||||
|
data: (r.data ?? {}) as Prisma.InputJsonObject,
|
||||||
|
members: { create: r.members.filter((m) => others.has(m) && m !== r.fromId && m !== r.toId).map((entityId) => ({ entityId })) },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const relationId of snap.memberOf) {
|
||||||
|
const relation = await tx.relation.findUnique({ where: { id: relationId }, select: { fromId: true, toId: true } });
|
||||||
|
if (relation && relation.fromId !== snap.entity.id && relation.toId !== snap.entity.id) {
|
||||||
|
await tx.relationMember.createMany({ data: [{ relationId, entityId: snap.entity.id }], skipDuplicates: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const s of snap.shifts) {
|
||||||
|
await tx.shift.create({
|
||||||
|
data: {
|
||||||
|
bookId,
|
||||||
|
personId: snap.entity.id,
|
||||||
|
workplaceId: s.workplaceId && others.has(s.workplaceId) ? s.workplaceId : null,
|
||||||
|
weekday: s.weekday,
|
||||||
|
startTime: s.startTime,
|
||||||
|
endTime: s.endTime,
|
||||||
|
weeks: s.weeks,
|
||||||
|
label: s.label,
|
||||||
|
scheduleCode: s.scheduleCode,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (snap.hostedShiftIds.length) await tx.shift.updateMany({ where: { id: { in: snap.hostedShiftIds }, bookId }, data: { workplaceId: snap.entity.id } });
|
||||||
|
if (snap.markerIds.length) await tx.marker.updateMany({ where: { id: { in: snap.markerIds }, map: { bookId } }, data: { entityId: snap.entity.id } });
|
||||||
|
|
||||||
|
await tx.trashItem.delete({ where: { id: item.id } });
|
||||||
|
});
|
||||||
|
|
||||||
|
log.info("Post återställd från papperskorgen", { entityId: snap.entity.id, bookId });
|
||||||
|
return { bookId, entityId: snap.entity.id };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Böcker ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** Sparar boken som en zip i papperskorgen och tar sedan bort den. Zip-filen skrivs först, så ett fel förlorar ingenting. */
|
||||||
|
export async function trashBook(ownerId: string, bookId: string) {
|
||||||
|
const { data, files } = await buildExport(bookId, true);
|
||||||
|
|
||||||
|
const entries: Zippable = { "book.json": strToU8(JSON.stringify(data)) };
|
||||||
|
for (const [name, bytes] of files) entries[`files/${name}`] = [bytes, { level: 0 }];
|
||||||
|
|
||||||
|
const item = await prisma.trashItem.create({
|
||||||
|
data: { ownerId, kind: "book", label: data.book.title, detail: String(data.entities.length) },
|
||||||
|
});
|
||||||
|
const file = `${item.id}.zip`;
|
||||||
|
try {
|
||||||
|
await mkdir(TRASH_DIR, { recursive: true });
|
||||||
|
await writeFile(path.join(TRASH_DIR, file), zipSync(entries));
|
||||||
|
await prisma.trashItem.update({ where: { id: item.id }, data: { file } });
|
||||||
|
} catch (error) {
|
||||||
|
await prisma.trashItem.delete({ where: { id: item.id } }).catch(() => undefined);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
const images = [...data.entities.map((e) => e.image), ...data.maps.map((m) => m.image)];
|
||||||
|
// Bilderna finns nu i zip-filen och kan tas bort från uppladdningsmappen
|
||||||
|
const [entityImages, mapImages] = await Promise.all([
|
||||||
|
prisma.entity.findMany({ where: { bookId, imageFile: { not: null } }, select: { imageFile: true } }),
|
||||||
|
prisma.bookMap.findMany({ where: { bookId, imageFile: { not: null } }, select: { imageFile: true } }),
|
||||||
|
]);
|
||||||
|
await prisma.book.delete({ where: { id: bookId } });
|
||||||
|
await Promise.all([...entityImages, ...mapImages].map((row) => deleteImage(row.imageFile)));
|
||||||
|
log.info("Bok flyttad till papperskorgen", { bookId, trashId: item.id, images: images.filter(Boolean).length });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Återställer en bok som en ny bok. Returnerar den nya bokens id. */
|
||||||
|
export async function restoreBook(ownerId: string, trashId: string): Promise<string | null> {
|
||||||
|
const item = await prisma.trashItem.findFirst({ where: { id: trashId, ownerId, kind: "book" } });
|
||||||
|
if (!item?.file) return null;
|
||||||
|
const bytes = await readFile(path.join(TRASH_DIR, item.file));
|
||||||
|
const { data, files } = readImportFile(new Uint8Array(bytes));
|
||||||
|
const result = await importBook(ownerId, data, files);
|
||||||
|
await purge(item);
|
||||||
|
log.info("Bok återställd från papperskorgen", { trashId, bookId: result.bookId });
|
||||||
|
return result.bookId;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Rensning ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async function purge(item: { id: string; kind: string; file: string | null; payload: Prisma.JsonValue }) {
|
||||||
|
if (item.kind === "book" && item.file) {
|
||||||
|
await rm(path.join(TRASH_DIR, item.file), { force: true });
|
||||||
|
} else if (item.kind === "entity") {
|
||||||
|
const snap = item.payload as unknown as Snapshot | null;
|
||||||
|
if (snap) {
|
||||||
|
await deleteImage(snap.entity.imageFile);
|
||||||
|
await prisma.entityVersion.deleteMany({ where: { entityId: snap.entity.id } });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await prisma.trashItem.delete({ where: { id: item.id } });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function purgeTrashItem(ownerId: string, trashId: string) {
|
||||||
|
const item = await prisma.trashItem.findFirst({ where: { id: trashId, ownerId } });
|
||||||
|
if (item) await purge(item);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function emptyBookTrash(ownerId: string, bookId: string) {
|
||||||
|
const items = await prisma.trashItem.findMany({ where: { ownerId, bookId, kind: "entity" } });
|
||||||
|
for (const item of items) await purge(item);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Tar bort allt som legat i papperskorgen längre än TRASH_DAYS. Returnerar antal rensade poster. */
|
||||||
|
export async function purgeExpiredTrash(): Promise<number> {
|
||||||
|
const limit = new Date(Date.now() - TRASH_DAYS * 24 * 60 * 60 * 1000);
|
||||||
|
const items = await prisma.trashItem.findMany({ where: { deletedAt: { lt: limit } } });
|
||||||
|
for (const item of items) {
|
||||||
|
try {
|
||||||
|
await purge(item);
|
||||||
|
} catch (error) {
|
||||||
|
log.error("Kunde inte rensa papperskorgen", { trashId: item.id, error });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return items.length;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
// Version och bygge. Sätts vid bygget av imagen (se Dockerfile: ARG APP_VERSION och APP_COMMIT).
|
||||||
|
export const APP_VERSION = process.env.APP_VERSION || process.env.npm_package_version || "dev";
|
||||||
|
export const APP_COMMIT = (process.env.APP_COMMIT || "").slice(0, 7);
|
||||||
|
export const APP_VERSION_LABEL = APP_COMMIT ? `${APP_VERSION} (${APP_COMMIT})` : APP_VERSION;
|
||||||
+14
-3
@@ -1,9 +1,20 @@
|
|||||||
|
import { NextResponse, type NextFetchEvent, type NextRequest } from "next/server";
|
||||||
import NextAuth from "next-auth";
|
import NextAuth from "next-auth";
|
||||||
import authConfig from "./auth.config";
|
import authConfig from "./auth.config";
|
||||||
|
import { runtimeSecurityHeaders } from "./lib/security";
|
||||||
|
|
||||||
export const { auth: middleware } = NextAuth(authConfig);
|
const { auth } = NextAuth(authConfig);
|
||||||
|
|
||||||
|
// Inloggningskontrollen (authorized i auth.config.ts) körs först. Svaret, vare sig det är en
|
||||||
|
// omdirigering till inloggning eller en vanlig sida, får sedan säkerhetsrubrikerna.
|
||||||
|
export async function middleware(request: NextRequest, event: NextFetchEvent) {
|
||||||
|
const handler = auth as unknown as (req: NextRequest, evt: NextFetchEvent) => Promise<Response | undefined>;
|
||||||
|
const response = (await handler(request, event)) ?? NextResponse.next();
|
||||||
|
for (const [name, value] of Object.entries(runtimeSecurityHeaders())) response.headers.set(name, value);
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
export const config = {
|
export const config = {
|
||||||
// Allt kräver inloggning utom Auth.js egna routes, hälsokontrollen och statiska filer.
|
// Allt kräver inloggning utom Auth.js egna routes, hälsokontrollen, mätvärden (egen token) och statiska filer.
|
||||||
matcher: ["/((?!api/auth|api/health|_next/static|_next/image|favicon.ico).*)"],
|
matcher: ["/((?!api/auth|api/health|api/metrics|_next/static|_next/image|favicon.ico).*)"],
|
||||||
};
|
};
|
||||||
Reference in new issue
Block a user