diff --git a/app-admin/src/lib/server/pb-admin.ts b/app-admin/src/lib/server/pb-admin.ts deleted file mode 100644 index e9a7a46..0000000 --- a/app-admin/src/lib/server/pb-admin.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '$shared/server/pb-admin'; diff --git a/app-public/src/lib/server/basket.ts b/app-public/src/lib/server/basket.ts deleted file mode 100644 index 74bac8c..0000000 --- a/app-public/src/lib/server/basket.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '$shared/server/basket'; diff --git a/app-public/src/lib/server/pb-admin.ts b/app-public/src/lib/server/pb-admin.ts deleted file mode 100644 index e9a7a46..0000000 --- a/app-public/src/lib/server/pb-admin.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '$shared/server/pb-admin'; diff --git a/app-public/src/lib/stripe.server.ts b/app-public/src/lib/stripe.server.ts deleted file mode 100644 index daf707a..0000000 --- a/app-public/src/lib/stripe.server.ts +++ /dev/null @@ -1,17 +0,0 @@ -import Stripe from 'stripe'; -import { env } from '$env/dynamic/private'; - -let stripe: Stripe | null = null; - -export function getStripe(): Stripe { - if (!stripe) { - const key = env.STRIPE_SECRET_KEY; - if (!key) throw new Error('STRIPE_SECRET_KEY is not set'); - stripe = new Stripe(key); - } - return stripe; -} - -export function getCurrency(): string { - return env.STRIPE_CURRENCY || 'eur'; -} diff --git a/packages/shared/src/server/basket.ts b/packages/shared/src/server/basket.ts deleted file mode 100644 index 98b63a7..0000000 --- a/packages/shared/src/server/basket.ts +++ /dev/null @@ -1,187 +0,0 @@ -import type PocketBase from 'pocketbase'; -import type { Basket, BasketLine } from '../types'; -import { getFileUrl } from '../pb'; - -export const BASKET_COOKIE = 'basket_id'; -/** Basket lifetime — refreshed on every basket API call. */ -export const BASKET_TTL_MS = 24 * 60 * 60 * 1000; // 24h -/** How long a slot stays held once added to a basket / after a failed payment. */ -export const SLOT_HOLD_MS = 10 * 60 * 1000; // 10 min -/** Hold extended to this once a payment is in progress, so the slot survives - * the customer entering card details / retrying a declined card. */ -export const SLOT_CHECKOUT_HOLD_MS = 30 * 60 * 1000; // 30 min - -function now() { - return new Date(); -} - -function iso(date: Date) { - return date.toISOString(); -} - -/** - * Release any slots whose hold has expired, removing their basket lines - * and flipping them back to `available`. Also marks expired active - * baskets as `abandoned`. Runs lazily on basket reads / checkout. - * - * The expiry check is done in JS (parsing `heldUntil` as a UTC date) rather - * than via a PocketBase date-string filter, so a slot is never released - * *before* its hold genuinely lapses — regardless of how PocketBase stores / - * compares the date field. A slot is held for the full SLOT_HOLD_MS (or - * SLOT_CHECKOUT_HOLD_MS during payment). - */ -export async function sweepExpiredHolds(pb: PocketBase) { - const nowMs = Date.now(); - - // 1. Release expired slot holds (and drop the lines holding them) - const heldSlots = await pb - .collection('slots') - .getFullList({ filter: `status = 'held'` }) - .catch(() => []); - for (const slot of heldSlots) { - const heldUntilMs = slot.heldUntil ? Date.parse(slot.heldUntil) : NaN; - // Still valid, or no parseable hold to judge by — leave it alone. - if (Number.isNaN(heldUntilMs) || heldUntilMs > nowMs) continue; - - const lines = await pb - .collection('basket_lines') - .getFullList({ filter: `slot = "${slot.id}"` }) - .catch(() => []); - for (const line of lines) { - await pb.collection('basket_lines').delete(line.id).catch(() => {}); - } - await pb - .collection('slots') - .update(slot.id, { status: 'available', heldUntil: null }) - .catch(() => {}); - } - - // 2. Abandon expired active baskets (their slot holds were already - // covered by heldUntil above — same 10-min window < 24h basket TTL) - const nowIso = iso(now()); - await pb - .collection('baskets') - .getFullList({ filter: `status = 'active' && expiresAt < "${nowIso}"` }) - .then(async (expired) => { - for (const basket of expired) { - await pb.collection('baskets').update(basket.id, { status: 'abandoned' }).catch(() => {}); - } - }) - .catch(() => {}); -} - -/** Map raw PB records (with expand) to our Basket type. */ -function mapBasket(record: Record, lines: Record[]): Basket { - const mappedLines: BasketLine[] = lines.map((line) => { - const item = line.expand?.item; - const slot = line.expand?.slot; - const media = item?.expand?.image; - return { - id: line.id, - basket: line.basket, - item: line.item, - slot: line.slot || null, - quantity: line.quantity, - lineType: line.lineType, - itemName: item?.name, - itemPrice: item?.price, - itemImageUrl: media ? getFileUrl('media', media.id, media.file) : undefined, - slotStart: slot?.start, - slotEnd: slot?.end - }; - }); - return { - id: record.id, - status: record.status, - expiresAt: record.expiresAt, - email: record.email || null, - customerDetails: record.customerDetails || null, - stripePaymentIntentId: record.stripePaymentIntentId || null, - lines: mappedLines - }; -} - -/** Load a basket + its lines (with item/slot expand) by basket id. */ -export async function loadBasket(pb: PocketBase, basketId: string): Promise { - try { - const record = await pb.collection('baskets').getOne(basketId); - if (record.status !== 'active') return null; - const lines = await pb - .collection('basket_lines') - .getFullList({ filter: `basket = "${basketId}"`, expand: 'item,slot,item.image' }); - return mapBasket(record, lines); - } catch { - return null; - } -} - -/** Create a fresh active basket. */ -export async function createBasket(pb: PocketBase): Promise { - const record = await pb.collection('baskets').create({ - status: 'active', - expiresAt: iso(new Date(Date.now() + BASKET_TTL_MS)) - }); - return { - id: record.id, - status: 'active', - expiresAt: record.expiresAt, - email: null, - customerDetails: null, - stripePaymentIntentId: null, - lines: [] - }; -} - -/** Touch the basket expiry (rolling TTL). */ -export async function touchBasket(pb: PocketBase, basketId: string) { - await pb - .collection('baskets') - .update(basketId, { expiresAt: iso(new Date(Date.now() + BASKET_TTL_MS)) }) - .catch(() => {}); -} - -/** Release a slot hold for a basket line (slot back to available). */ -export async function releaseLineHold(pb: PocketBase, line: { slot?: string | null }) { - if (!line.slot) return; - await pb - .collection('slots') - .update(line.slot, { status: 'available', heldUntil: null }) - .catch(() => {}); -} - -/** - * Re-reserve (extend) the hold on every slot line in a basket, as long as - * the slot is still in `held` status. Used: - * - at checkout start (create-intent) with SLOT_CHECKOUT_HOLD_MS, so a - * service survives the customer entering card details / retrying a - * declined card; - * - after a failed payment (webhook) with SLOT_HOLD_MS, so the customer - * can retry within a fresh 10-minute window. - * The slot is genuinely still the customer's (nobody else could grab it - * while `held`), so renewing is safe. Slots whose status is no longer - * `held` (e.g. released and re-booked by someone else) are returned so the - * caller can inform the user. - */ -export async function extendBasketHolds( - pb: PocketBase, - basketId: string, - durationMs = SLOT_HOLD_MS -): Promise { - const unheld: string[] = []; - const lines = await pb - .collection('basket_lines') - .getFullList({ filter: `basket = "${basketId}" && lineType = "slot"` }) - .catch(() => []); - const until = iso(new Date(Date.now() + durationMs)); - for (const line of lines) { - const slotId = line.slot; - if (!slotId) continue; - const slot = await pb.collection('slots').getOne(slotId).catch(() => null); - if (slot && slot.status === 'held') { - await pb.collection('slots').update(slotId, { heldUntil: until }).catch(() => {}); - } else { - unheld.push(line.id); - } - } - return unheld; -} diff --git a/packages/shared/src/server/pb-admin.ts b/packages/shared/src/server/pb-admin.ts deleted file mode 100644 index e8e6713..0000000 --- a/packages/shared/src/server/pb-admin.ts +++ /dev/null @@ -1,53 +0,0 @@ -import PocketBase, { ClientResponseError } from 'pocketbase'; -import { env } from '$env/dynamic/private'; - -let adminPb: PocketBase | null = null; -let authPromise: Promise | null = null; - -async function authenticate(): Promise { - const url = env.POCKETBASE_INTERNAL_URL; - const pb = new PocketBase(url); - pb.autoCancellation(false); - - const email = env.POCKETBASE_ADMIN_EMAIL; - const password = env.POCKETBASE_ADMIN_PASSWORD; - if (!email || !password) throw new Error('POCKETBASE_ADMIN_EMAIL and POCKETBASE_ADMIN_PASSWORD must be set'); - - await pb.collection('_superusers').authWithPassword(email, password); - adminPb = pb; - return pb; -} - -/** - * Server-only PocketBase client authenticated as admin. - * Used by basket/checkout/webhook API routes that need to bypass - * collection-level API rules (create baskets, hold slots, create orders). - * - * Concurrent callers share one in-flight auth attempt; if the cached token - * has since been invalidated (401 on first use), we re-authenticate once. - */ -export async function getAdminPb(): Promise { - if (adminPb?.authStore.isValid) return adminPb; - authPromise ??= authenticate().finally(() => { - authPromise = null; - }); - return authPromise; -} - -/** - * Run `fn` with the admin client; on a 401 (stale/invalidated token), - * re-authenticate and retry exactly once. - */ -export async function withAdminPb(fn: (pb: PocketBase) => Promise): Promise { - const pb = await getAdminPb(); - try { - return await fn(pb); - } catch (e) { - if (e instanceof ClientResponseError && e.status === 401) { - pb.authStore.clear(); - adminPb = null; - return fn(await getAdminPb()); - } - throw e; - } -} diff --git a/pb_schema.json b/pb_schema.json index 1c2d4a9..e245d1f 100644 --- a/pb_schema.json +++ b/pb_schema.json @@ -458,9 +458,9 @@ "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_olorder00001", "name": "order", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_orders00001", "cascadeDelete": true, "minSelect": 0, "maxSelect": 1, "displayFields": null }, diff --git a/pocketbase/pb_migrations/1791331200_lock_order_lines.js b/pocketbase/pb_migrations/1791331200_lock_order_lines.js new file mode 100644 index 0000000..d225cbf --- /dev/null +++ b/pocketbase/pb_migrations/1791331200_lock_order_lines.js @@ -0,0 +1,33 @@ +/// + +// order_lines was writable by anyone (create/update/delete rules were empty +// strings = public), so the line items of real orders could be forged or +// deleted through the REST API. Orders are now created by the shop hooks +// (pb_hooks/shop), which bypass API rules, so writes are superuser-only. + +function find(app, name) { + try { + return app.findCollectionByNameOrId(name); + } catch (e) { + return null; // fresh install: pb_schema.json (already fixed) is imported later + } +} + +migrate( + (app) => { + const collection = find(app, 'order_lines'); + if (!collection) return; + collection.createRule = null; + collection.updateRule = null; + collection.deleteRule = null; + app.save(collection); + }, + (app) => { + const collection = find(app, 'order_lines'); + if (!collection) return; + collection.createRule = ''; + collection.updateRule = ''; + collection.deleteRule = ''; + app.save(collection); + } +);