From 92642898137601017981fbcc9ad4ba03ae2da9de Mon Sep 17 00:00:00 2001 From: agent Date: Tue, 6 Oct 2026 10:55:12 +0000 Subject: [PATCH] PocketBase: close public sign-up, lock commerce writes, add dates/unique keys Security: - PocketBase's default `users` collection allows anonymous sign-up, and every CMS rule only checks "signed in" (the admin login also accepts `users`). Anyone could register via the public API and edit the site, read orders/customer details, or log into the admin. Sign-up is now superuser-only. - orders.create, baskets.create/update and basket_lines.create/update/ delete were open to anonymous requests, allowing forged "paid" orders in the admin and basket tampering. The public app performs all of these server-side with the admin client, so they are now superuser-only (basket add-item/add-slot verified still working). Data: - created/updated autodate fields on all app collections; orders are now listed newest-first by date (ids are random, '-id' was not chronological). - Unique indexes on pages.slug and globals.key (skipped with a log line if existing data has duplicates, so PocketBase still starts). Delivered as a JS migration in pocketbase/pb_migrations, mounted into the container (the image already passes --migrationsDir=/pb_migrations), so it applies once on the next start. pb_schema.json carries the same changes for fresh installs, where the migration runs before the schema is imported. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KgF3Kf47LjPGHKQHszpUAv --- app-admin/src/routes/orders/+page.server.ts | 8 +- docker-compose.yml | 192 +++++++++--------- pb_schema.json | 64 ++++-- .../1791244800_lock_rules_dates_unique.js | 106 ++++++++++ 4 files changed, 252 insertions(+), 118 deletions(-) create mode 100644 pocketbase/pb_migrations/1791244800_lock_rules_dates_unique.js diff --git a/app-admin/src/routes/orders/+page.server.ts b/app-admin/src/routes/orders/+page.server.ts index 27c8c0e..34df546 100644 --- a/app-admin/src/routes/orders/+page.server.ts +++ b/app-admin/src/routes/orders/+page.server.ts @@ -3,10 +3,10 @@ import { sendOrderEmails, type EmailKind } from '$lib/server/email'; import type { Actions, PageServerLoad } from './$types'; export const load: PageServerLoad = async ({ locals }) => { - // NOTE: there is no `created` field on orders (commerce collections were - // imported without autodate fields) and PocketBase ids are random, so - // '-id' is NOT chronological. See the polish report for the schema fix. - const records = await locals.pb.collection('orders').getFullList({ sort: '-id' }).catch(() => []); + // Newest first. `created` comes from the 1791244800 migration; orders made + // before it have no date and sort last (PocketBase ids are random, so they + // can't be ordered chronologically). + const records = await locals.pb.collection('orders').getFullList({ sort: '-created,-id' }).catch(() => []); // All lines in one request (previously one request per order). const lineRecords = records.length diff --git a/docker-compose.yml b/docker-compose.yml index 1b96633..05bebff 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,95 +1,97 @@ -services: - pocketbase: - image: docker.io/spectado/pocketbase:latest - container_name: massage-pocketbase - restart: unless-stopped - # Internal only — accessed via the caddy reverse proxy - expose: - - "80" - volumes: - - pocketbase:/pb_data - - app-admin: - build: - context: . - dockerfile: app-admin/Dockerfile - container_name: massage-app-admin - restart: unless-stopped - depends_on: - - pocketbase - environment: - PORT: 3001 - POCKETBASE_INTERNAL_URL: http://pocketbase:80 - PUBLIC_POCKETBASE_URL: http://db.${DOMAIN:-localhost}:8080 - ORIGIN: http://admin.${DOMAIN:-localhost}:8080 - PUBLIC_SITE_URL: http://www.${DOMAIN:-localhost}:8080 - BODY_SIZE_LIMIT: 52428800 # 50MB — import payload embeds all images as base64 - # Commerce (reservation & payment system) — set these in a root-level .env - POCKETBASE_ADMIN_EMAIL: ${POCKETBASE_ADMIN_EMAIL:-} - POCKETBASE_ADMIN_PASSWORD: ${POCKETBASE_ADMIN_PASSWORD:-} - STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur} - # Booking emails (Brevo SMTP relay) — admin needs these for resend/test sends - SMTP_HOST: ${SMTP_HOST:-} - SMTP_PORT: ${SMTP_PORT:-587} - SMTP_USER: ${SMTP_USER:-} - SMTP_PASS: ${SMTP_PASS:-} - EMAIL_FROM: ${EMAIL_FROM:-} - EMAIL_FROM_NAME: ${EMAIL_FROM_NAME:-} - SITE_TIMEZONE: ${SITE_TIMEZONE:-Europe/Oslo} - # Internal only — served via the caddy reverse proxy - expose: - - "3001" - - app-public: - build: - context: . - dockerfile: app-public/Dockerfile - container_name: massage-app-public - restart: unless-stopped - depends_on: - - pocketbase - environment: - PORT: 3000 - POCKETBASE_INTERNAL_URL: http://pocketbase:80 - PUBLIC_POCKETBASE_URL: http://db.${DOMAIN:-localhost}:8080 - ORIGIN: http://www.${DOMAIN:-localhost}:8080 - # Commerce (reservation & payment system) — set these in a root-level .env - POCKETBASE_ADMIN_EMAIL: ${POCKETBASE_ADMIN_EMAIL:-} - POCKETBASE_ADMIN_PASSWORD: ${POCKETBASE_ADMIN_PASSWORD:-} - STRIPE_SECRET_KEY: ${STRIPE_SECRET_KEY:-} - STRIPE_WEBHOOK_SECRET: ${STRIPE_WEBHOOK_SECRET:-} - PUBLIC_STRIPE_PUBLISHABLE_KEY: ${PUBLIC_STRIPE_PUBLISHABLE_KEY:-} - STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur} - # Booking emails (Brevo SMTP relay) — sent from the Stripe webhook - SMTP_HOST: ${SMTP_HOST:-} - SMTP_PORT: ${SMTP_PORT:-587} - SMTP_USER: ${SMTP_USER:-} - SMTP_PASS: ${SMTP_PASS:-} - EMAIL_FROM: ${EMAIL_FROM:-} - EMAIL_FROM_NAME: ${EMAIL_FROM_NAME:-} - SITE_TIMEZONE: ${SITE_TIMEZONE:-Europe/Oslo} - # Internal only — served via the caddy reverse proxy - expose: - - "3000" - - caddy: - image: docker.io/library/caddy:2-alpine - container_name: massage-caddy - restart: unless-stopped - ports: - - "8080:8080" - environment: - DOMAIN: ${DOMAIN:-localhost} - # Scheme used in Caddyfile site addresses. "http" = plain HTTP on :8080 - # (matches the ORIGIN vars below). Switch to "https" only if you also - # update ORIGIN/PUBLIC_* URLs and provide a cert issuer. - CADDY_SCHEME: ${CADDY_SCHEME:-http} - volumes: - - ./Caddyfile:/etc/caddy/Caddyfile:ro,Z - depends_on: - - app-admin - - app-public - - pocketbase - -volumes: - pocketbase: +services: + pocketbase: + image: docker.io/spectado/pocketbase:latest + container_name: massage-pocketbase + restart: unless-stopped + # Internal only — accessed via the caddy reverse proxy + expose: + - "80" + volumes: + - pocketbase:/pb_data + # Versioned schema changes; PocketBase applies pending ones on start. + - ./pocketbase/pb_migrations:/pb_migrations:ro,Z + + app-admin: + build: + context: . + dockerfile: app-admin/Dockerfile + container_name: massage-app-admin + restart: unless-stopped + depends_on: + - pocketbase + environment: + PORT: 3001 + POCKETBASE_INTERNAL_URL: http://pocketbase:80 + PUBLIC_POCKETBASE_URL: http://db.${DOMAIN:-localhost}:8080 + ORIGIN: http://admin.${DOMAIN:-localhost}:8080 + PUBLIC_SITE_URL: http://www.${DOMAIN:-localhost}:8080 + BODY_SIZE_LIMIT: 52428800 # 50MB — import payload embeds all images as base64 + # Commerce (reservation & payment system) — set these in a root-level .env + POCKETBASE_ADMIN_EMAIL: ${POCKETBASE_ADMIN_EMAIL:-} + POCKETBASE_ADMIN_PASSWORD: ${POCKETBASE_ADMIN_PASSWORD:-} + STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur} + # Booking emails (Brevo SMTP relay) — admin needs these for resend/test sends + SMTP_HOST: ${SMTP_HOST:-} + SMTP_PORT: ${SMTP_PORT:-587} + SMTP_USER: ${SMTP_USER:-} + SMTP_PASS: ${SMTP_PASS:-} + EMAIL_FROM: ${EMAIL_FROM:-} + EMAIL_FROM_NAME: ${EMAIL_FROM_NAME:-} + SITE_TIMEZONE: ${SITE_TIMEZONE:-Europe/Oslo} + # Internal only — served via the caddy reverse proxy + expose: + - "3001" + + app-public: + build: + context: . + dockerfile: app-public/Dockerfile + container_name: massage-app-public + restart: unless-stopped + depends_on: + - pocketbase + environment: + PORT: 3000 + POCKETBASE_INTERNAL_URL: http://pocketbase:80 + PUBLIC_POCKETBASE_URL: http://db.${DOMAIN:-localhost}:8080 + ORIGIN: http://www.${DOMAIN:-localhost}:8080 + # Commerce (reservation & payment system) — set these in a root-level .env + POCKETBASE_ADMIN_EMAIL: ${POCKETBASE_ADMIN_EMAIL:-} + POCKETBASE_ADMIN_PASSWORD: ${POCKETBASE_ADMIN_PASSWORD:-} + STRIPE_SECRET_KEY: ${STRIPE_SECRET_KEY:-} + STRIPE_WEBHOOK_SECRET: ${STRIPE_WEBHOOK_SECRET:-} + PUBLIC_STRIPE_PUBLISHABLE_KEY: ${PUBLIC_STRIPE_PUBLISHABLE_KEY:-} + STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur} + # Booking emails (Brevo SMTP relay) — sent from the Stripe webhook + SMTP_HOST: ${SMTP_HOST:-} + SMTP_PORT: ${SMTP_PORT:-587} + SMTP_USER: ${SMTP_USER:-} + SMTP_PASS: ${SMTP_PASS:-} + EMAIL_FROM: ${EMAIL_FROM:-} + EMAIL_FROM_NAME: ${EMAIL_FROM_NAME:-} + SITE_TIMEZONE: ${SITE_TIMEZONE:-Europe/Oslo} + # Internal only — served via the caddy reverse proxy + expose: + - "3000" + + caddy: + image: docker.io/library/caddy:2-alpine + container_name: massage-caddy + restart: unless-stopped + ports: + - "8080:8080" + environment: + DOMAIN: ${DOMAIN:-localhost} + # Scheme used in Caddyfile site addresses. "http" = plain HTTP on :8080 + # (matches the ORIGIN vars below). Switch to "https" only if you also + # update ORIGIN/PUBLIC_* URLs and provide a cert issuer. + CADDY_SCHEME: ${CADDY_SCHEME:-http} + volumes: + - ./Caddyfile:/etc/caddy/Caddyfile:ro,Z + depends_on: + - app-admin + - app-public + - pocketbase + +volumes: + pocketbase: diff --git a/pb_schema.json b/pb_schema.json index 3b1f3f0..1c2d4a9 100644 --- a/pb_schema.json +++ b/pb_schema.json @@ -60,9 +60,13 @@ "presentable": false, "unique": false, "options": {} - } + }, + {"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false}, + {"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true} + ], + "indexes": [ + "CREATE UNIQUE INDEX `idx_pages_slug_unique` ON `pages` (`slug`)" ], - "indexes": [], "options": {} }, { @@ -102,9 +106,13 @@ "options": { "maxSize": 1000000 } - } + }, + {"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false}, + {"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true} + ], + "indexes": [ + "CREATE UNIQUE INDEX `idx_globals_key_unique` ON `globals` (`key`)" ], - "indexes": [], "options": {} }, { @@ -162,7 +170,9 @@ "max": 180, "pattern": "" } - } + }, + {"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false}, + {"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true} ], "indexes": [], "options": {} @@ -292,7 +302,9 @@ "presentable": false, "unique": false, "options": {} - } + }, + {"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false}, + {"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true} ], "indexes": [ "CREATE INDEX `idx_events_start` ON `events` (`start`)", @@ -319,7 +331,9 @@ { "id": "sel_itemtype001", "name": "type", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "item_with_time"] }, { "id": "num_itemstock01", "name": "stock", "type": "number", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": 0, "max": null } }, { "id": "num_itemdur0001", "name": "duration", "type": "number", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": 1, "max": null } }, - { "id": "bool_itemactive", "name": "active", "type": "bool", "system": false, "required": false, "presentable": false, "unique": false, "options": {} } + { "id": "bool_itemactive", "name": "active", "type": "bool", "system": false, "required": false, "presentable": false, "unique": false, "options": {} }, + {"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false}, + {"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true} ], "indexes": [], "autodate": true, @@ -343,7 +357,9 @@ { "id": "sel_slotstatus0", "name": "status", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["available", "held", "booked"] }, { "id": "date_slotheldun0", "name": "heldUntil", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } }, { "id": "rel_slotorder01", "name": "order", "type": "relation", "system": false, "required": false, "presentable": false, "unique": false, "collectionId": "pbc_orders00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null }, - { "id": "text_slotnotes0", "name": "notes", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 500, "pattern": "" } } + { "id": "text_slotnotes0", "name": "notes", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 500, "pattern": "" } }, + {"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false}, + {"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true} ], "indexes": [ "CREATE INDEX `idx_slots_item_start` ON `slots` (`item`, `start`)", @@ -359,8 +375,8 @@ "system": false, "listRule": "@request.auth.id != ''", "viewRule": "@request.auth.id != ''", - "createRule": "", - "updateRule": "", + "createRule": null, + "updateRule": null, "deleteRule": "@request.auth.id != ''", "fields": [ { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, @@ -368,7 +384,9 @@ { "id": "date_basketexp0", "name": "expiresAt", "type": "date", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": "", "max": "" } }, { "id": "text_basketemai", "name": "email", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 254, "pattern": "" } }, { "id": "json_basketcust", "name": "customerDetails", "type": "json", "system": false, "required": false, "presentable": false, "unique": false, "options": { "maxSize": 100000 } }, - { "id": "text_basketstrip", "name": "stripePaymentIntentId", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 200, "pattern": "" } } + { "id": "text_basketstrip", "name": "stripePaymentIntentId", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 200, "pattern": "" } }, + {"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false}, + {"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true} ], "indexes": [ "CREATE INDEX `idx_baskets_status` ON `baskets` (`status`)" @@ -383,16 +401,18 @@ "system": false, "listRule": "@request.auth.id != ''", "viewRule": "@request.auth.id != ''", - "createRule": "", - "updateRule": "", - "deleteRule": "", + "createRule": null, + "updateRule": null, + "deleteRule": null, "fields": [ { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, { "id": "rel_blbasket0001", "name": "basket", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_baskets0001", "cascadeDelete": true, "minSelect": 0, "maxSelect": 1, "displayFields": null }, { "id": "rel_blitem000001", "name": "item", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_items00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null }, { "id": "rel_blslot000001", "name": "slot", "type": "relation", "system": false, "required": false, "presentable": false, "unique": false, "collectionId": "pbc_slots00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null }, { "id": "num_blquantity01", "name": "quantity", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 1, "max": null } }, - { "id": "sel_bllinetype01", "name": "lineType", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "slot"] } + { "id": "sel_bllinetype01", "name": "lineType", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "slot"] }, + {"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false}, + {"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true} ], "indexes": [ "CREATE INDEX `idx_basket_lines_basket` ON `basket_lines` (`basket`)", @@ -408,7 +428,7 @@ "system": false, "listRule": "@request.auth.id != ''", "viewRule": "@request.auth.id != ''", - "createRule": "", + "createRule": null, "updateRule": "@request.auth.id != ''", "deleteRule": "@request.auth.id != ''", "fields": [ @@ -421,7 +441,9 @@ { "id": "text_orderstripe0", "name": "stripePaymentIntentId", "type": "text", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": null, "max": 200, "pattern": "" } }, { "id": "date_ordcustmail", "name": "customerEmailSentAt", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } }, { "id": "date_ordclntmail", "name": "clientEmailSentAt", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } }, - { "id": "text_ordmailerr0", "name": "emailError", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 2000, "pattern": "" } } + { "id": "text_ordmailerr0", "name": "emailError", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 2000, "pattern": "" } }, + {"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false}, + {"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true} ], "indexes": [ "CREATE INDEX `idx_orders_basket` ON `orders` (`basket`)" @@ -448,7 +470,9 @@ { "id": "sel_ollinetype01", "name": "lineType", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "slot"] }, { "id": "text_olname00001", "name": "name", "type": "text", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": null, "max": 180, "pattern": "" } }, { "id": "num_olprice00001", "name": "price", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 0, "max": null } }, - { "id": "date_olstart0001", "name": "start", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } } + { "id": "date_olstart0001", "name": "start", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } }, + {"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false}, + {"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true} ], "indexes": [ "CREATE INDEX `idx_order_lines_order` ON `order_lines` (`order`)" @@ -472,7 +496,9 @@ { "id": "text_etplsubject", "name": "subject", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 300, "pattern": "" } }, { "id": "json_etplblocks0", "name": "blocks", "type": "json", "system": false, "required": false, "presentable": false, "unique": false, "options": { "maxSize": 2000000 } }, { "id": "text_etplrecips0", "name": "recipients", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 500, "pattern": "" } }, - { "id": "bool_etplenabled", "name": "enabled", "type": "bool", "system": false, "required": false, "presentable": false, "unique": false, "options": {} } + { "id": "bool_etplenabled", "name": "enabled", "type": "bool", "system": false, "required": false, "presentable": false, "unique": false, "options": {} }, + {"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false}, + {"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true} ], "indexes": [ "CREATE UNIQUE INDEX `idx_email_templates_key` ON `email_templates` (`key`)" diff --git a/pocketbase/pb_migrations/1791244800_lock_rules_dates_unique.js b/pocketbase/pb_migrations/1791244800_lock_rules_dates_unique.js new file mode 100644 index 0000000..a367e0a --- /dev/null +++ b/pocketbase/pb_migrations/1791244800_lock_rules_dates_unique.js @@ -0,0 +1,106 @@ +/// + +// Security + data-integrity fixes (2026-10-06 admin polish review). +// Runs automatically when PocketBase starts (docker-compose mounts this +// directory at /pb_migrations); PocketBase records it so it runs once. +// +// 1. users: no public sign-up. PocketBase's default `users` collection lets +// anyone register, and every CMS rule only checks "signed in" — so a +// stranger could create an account and edit the site / read orders. +// 2. Commerce collections: writes are superuser-only. The public app does +// all basket/order writes server-side with the admin client, so open +// rules only allowed forging orders or tampering with baskets via the API. +// 3. `created`/`updated` autodate fields on content + commerce collections +// (orders had no date and no chronological order). +// 4. Unique indexes on pages.slug and globals.key (skipped, with a log +// line, if duplicates exist). + +const AUTODATE_COLLECTIONS = ['pages', 'globals', 'media', 'events', 'items', 'slots', 'baskets', 'basket_lines', 'orders', 'order_lines', 'email_templates']; + +// Missing collections are skipped: on a fresh install this runs before +// pb_schema.json is imported (that file already contains these changes). +function find(app, name) { + try { + return app.findCollectionByNameOrId(name); + } catch (e) { + return null; + } +} + +function update(app, name, change) { + const collection = find(app, name); + if (!collection) return; + change(collection); + app.save(collection); +} + +const UNIQUE_INDEXES = [ + { collection: 'pages', field: 'slug', name: 'idx_pages_slug_unique' }, + { collection: 'globals', field: 'key', name: 'idx_globals_key_unique' } +]; + +migrate( + (app) => { + // 1. Close public sign-up. + update(app, 'users', (c) => (c.createRule = null)); + + // 2. Commerce writes: superuser only (null = superusers only). + update(app, 'baskets', (c) => { + c.createRule = null; + c.updateRule = null; + }); + update(app, 'basket_lines', (c) => { + c.createRule = null; + c.updateRule = null; + c.deleteRule = null; + }); + update(app, 'orders', (c) => (c.createRule = null)); + + // 3. Autodate fields (existing records keep an empty date). + for (const name of AUTODATE_COLLECTIONS) { + update(app, name, (c) => { + if (!c.fields.getByName('created')) c.fields.add(new AutodateField({ name: 'created', onCreate: true, onUpdate: false })); + if (!c.fields.getByName('updated')) c.fields.add(new AutodateField({ name: 'updated', onCreate: true, onUpdate: true })); + }); + } + + // 4. Unique indexes. If duplicates already exist, skip the index and + // log why — failing here would stop PocketBase (and the site) from + // starting. The admin app also refuses new duplicates. + for (const { collection: name, field, name: indexName } of UNIQUE_INDEXES) { + const collection = find(app, name); + if (!collection || collection.indexes.some((index) => index.includes(indexName))) continue; + const seen = {}; + const duplicates = []; + for (const record of app.findAllRecords(name)) { + const value = record.get(field); + if (seen[value]) duplicates.push(value); + seen[value] = true; + } + if (duplicates.length) { + console.log(`[migration] ${name}.${field} has duplicates ${JSON.stringify(duplicates)} — unique index NOT created. Fix them and add it in the dashboard.`); + continue; + } + collection.indexes = [...collection.indexes, `CREATE UNIQUE INDEX \`${indexName}\` ON \`${name}\` (\`${field}\`)`]; + app.save(collection); + } + }, + (app) => { + // Revert: restore the previous rules and drop the unique indexes. + // Autodate fields are left in place (dropping them loses data). + update(app, 'users', (c) => (c.createRule = '')); + update(app, 'baskets', (c) => { + c.createRule = ''; + c.updateRule = ''; + }); + update(app, 'basket_lines', (c) => { + c.createRule = ''; + c.updateRule = ''; + c.deleteRule = ''; + }); + update(app, 'orders', (c) => (c.createRule = '')); + for (const { collection: name, name: indexName } of UNIQUE_INDEXES) { + update(app, name, (c) => (c.indexes = c.indexes.filter((index) => !index.includes(indexName)))); + } + } +);