Shop: move commerce logic into PocketBase hooks; public app unprivileged

The public (internet-facing) app logged in as the PocketBase superuser and
held the Stripe secret key, so any bug in it could become full control of
the database. Baskets, slot holds, Stripe PaymentIntents, the webhook that
creates orders, and the payment-result lookup now run in PocketBase JS
hooks (pocketbase/pb_hooks/shop, routes under /api/shop/*, plus a cron
that releases expired holds every minute).

The public app's routes keep their URLs but only proxy to those routes and
manage the basket cookie; it has no PocketBase or Stripe secret. Booking
emails are still rendered and sent by the public app (same renderer as the
admin preview) from order data the webhook hook returns; it records the
outcome via a narrow endpoint guarded by INTERNAL_API_SECRET.

Also: slot add and order creation are now transactional; shop listings
load anonymously (already public via API rules); shop API errors always
reach the browser as JSON; the superuser client and stripe package are
removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KgF3Kf47LjPGHKQHszpUAv
This commit is contained in:
agent 2026-10-06 12:34:58 +00:00
parent 1f929c68ca
commit 773fecc090
14 changed files with 914 additions and 507 deletions

View file

@ -1,54 +1,15 @@
import { json, error, type Cookies } from '@sveltejs/kit';
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { getAdminPb } from '$lib/server/pb-admin';
import {
BASKET_COOKIE,
BASKET_TTL_MS,
SLOT_HOLD_MS,
sweepExpiredHolds,
loadBasket,
createBasket,
touchBasket,
releaseLineHold
} from '$lib/server/basket';
import type PocketBase from 'pocketbase';
import { BASKET_COOKIE, BASKET_COOKIE_MAX_AGE, getBasket, jsonErrors, mapBasket, postJson } from '$lib/server/shop';
function setBasketCookie(cookies: Cookies, basketId: string) {
cookies.set(BASKET_COOKIE, basketId, {
path: '/',
httpOnly: true,
sameSite: 'lax',
maxAge: BASKET_TTL_MS / 1000
});
}
// Basket API for the browser. The logic (stock, slot holds, expiry) is in
// PocketBase — pocketbase/pb_hooks/shop; this route only adds the cookie.
/**
* Resolve the current basket from the cookie. When `create` is true and no
* valid basket exists, a new one is created (and the cookie is set).
*/
async function resolveBasket(pb: PocketBase, cookies: Cookies, create: boolean) {
const id = cookies.get(BASKET_COOKIE);
if (id) {
const basket = await loadBasket(pb, id);
if (basket) return { basket, isNew: false };
}
if (!create) return { basket: null, isNew: false };
const basket = await createBasket(pb);
setBasketCookie(cookies, basket.id);
return { basket, isNew: true };
}
export const GET: RequestHandler = async ({ cookies }) => {
const pb = await getAdminPb();
await sweepExpiredHolds(pb);
const { basket } = await resolveBasket(pb, cookies, false);
return json({ basket });
};
export const POST: RequestHandler = async ({ request, cookies }) => {
const pb = await getAdminPb();
await sweepExpiredHolds(pb);
export const GET: RequestHandler = jsonErrors(async ({ cookies }) => {
return json({ basket: await getBasket(cookies.get(BASKET_COOKIE)) });
});
export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => {
let body: Record<string, unknown>;
try {
body = await request.json();
@ -56,112 +17,17 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
throw error(400, 'Invalid JSON body');
}
const action = String(body.action || '');
const { basket } = await postJson<{ basket: Parameters<typeof mapBasket>[0] }>('/basket', {
action: body.action,
itemId: body.itemId,
slotId: body.slotId,
lineId: body.lineId,
quantity: body.quantity,
basketId: cookies.get(BASKET_COOKIE) || ''
});
// All mutations need a basket — lazily created on first add.
const { basket } = await resolveBasket(pb, cookies, action === 'add_item' || action === 'add_slot');
if (!basket) throw error(400, 'No active basket — add an item first');
switch (action) {
case 'add_item': {
const itemId = String(body.itemId || '');
const quantity = Math.max(1, Number(body.quantity) || 1);
if (!itemId) throw error(400, 'itemId is required');
const item = await pb.collection('items').getOne(itemId).catch(() => null);
if (!item || !item.active) throw error(404, 'Item not found');
if (item.type !== 'item') throw error(400, 'Use add_slot for bookable services');
const existing = basket.lines.find((l) => l.lineType === 'item' && l.item === itemId);
const newQty = (existing?.quantity ?? 0) + quantity;
if (item.stock != null && newQty > item.stock) {
throw error(409, `Only ${item.stock} in stock`);
}
if (existing) {
await pb.collection('basket_lines').update(existing.id, { quantity: newQty });
} else {
await pb.collection('basket_lines').create({
basket: basket.id,
item: itemId,
quantity,
lineType: 'item'
});
}
break;
}
case 'add_slot': {
const slotId = String(body.slotId || '');
if (!slotId) throw error(400, 'slotId is required');
if (basket.lines.some((l) => l.slot === slotId)) {
throw error(409, 'Slot already in your basket');
}
const slot = await pb.collection('slots').getOne(slotId).catch(() => null);
if (!slot) throw error(404, 'Slot not found');
if (slot.status !== 'available') throw error(409, 'Slot is no longer available');
// Atomic guard: basket_lines.slot has a partial UNIQUE index, so two
// concurrent requests cannot both create a line for the same slot.
// The line is created first; whoever loses the race gets a 409.
let line;
try {
line = await pb.collection('basket_lines').create({
basket: basket.id,
item: slot.item,
slot: slotId,
quantity: 1,
lineType: 'slot'
});
} catch {
throw error(409, 'Slot was just reserved by someone else');
}
try {
await pb.collection('slots').update(slotId, {
status: 'held',
heldUntil: new Date(Date.now() + SLOT_HOLD_MS).toISOString()
});
} catch (e) {
// Roll back the line if the hold update failed
await pb.collection('basket_lines').delete(line.id).catch(() => {});
throw error(500, 'Could not reserve the slot — please try again');
}
break;
}
case 'update_quantity': {
const lineId = String(body.lineId || '');
const quantity = Number(body.quantity);
const line = basket.lines.find((l) => l.id === lineId);
if (!line) throw error(404, 'Line not found in your basket');
if (line.lineType === 'slot') throw error(400, 'Slot lines have fixed quantity 1');
if (!Number.isInteger(quantity) || quantity < 1) throw error(400, 'Quantity must be a positive integer');
const item = await pb.collection('items').getOne(line.item).catch(() => null);
if (item?.stock != null && quantity > item.stock) {
throw error(409, `Only ${item.stock} in stock`);
}
await pb.collection('basket_lines').update(lineId, { quantity });
break;
}
case 'remove_line': {
const lineId = String(body.lineId || '');
const line = basket.lines.find((l) => l.id === lineId);
if (!line) throw error(404, 'Line not found in your basket');
await pb.collection('basket_lines').delete(lineId);
await releaseLineHold(pb, line);
break;
}
default:
throw error(400, `Unknown action: ${action}`);
}
await touchBasket(pb, basket.id);
const updated = await loadBasket(pb, basket.id);
return json({ basket: updated });
};
const mapped = mapBasket(basket);
// A basket is created on the first add; (re)set the cookie to keep it alive.
if (mapped) cookies.set(BASKET_COOKIE, mapped.id, { path: '/', httpOnly: true, sameSite: 'lax', maxAge: BASKET_COOKIE_MAX_AGE });
return json({ basket: mapped });
});

View file

@ -1,26 +1,10 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { getAdminPb } from '$lib/server/pb-admin';
import { BASKET_COOKIE, SLOT_CHECKOUT_HOLD_MS, sweepExpiredHolds, loadBasket, extendBasketHolds } from '$lib/server/basket';
import { getStripe, getCurrency } from '$lib/stripe.server';
import type { CustomerDetails } from '$lib/types';
export const POST: RequestHandler = async ({ request, cookies }) => {
const pb = await getAdminPb();
const basketId = cookies.get(BASKET_COOKIE);
// Payment is starting — extend any held slots to the checkout hold (30 min)
// so a booked service survives the customer entering card details or
// retrying a declined card. Extend BEFORE sweeping so a slot whose hold
// just lapsed is rescued rather than released at the moment they try to pay.
if (basketId) await extendBasketHolds(pb, basketId, SLOT_CHECKOUT_HOLD_MS);
await sweepExpiredHolds(pb);
if (!basketId) throw error(400, 'No active basket');
const basket = await loadBasket(pb, basketId);
if (!basket) throw error(400, 'Your session has expired — please re-select your items');
if (!basket.lines.length) throw error(400, 'Your basket is empty — a time slot you selected may have expired. Please pick a slot from the shop and try again.');
import { BASKET_COOKIE, jsonErrors, postJson } from '$lib/server/shop';
// Starts payment: PocketBase re-validates the basket, extends slot holds and
// creates the Stripe PaymentIntent (pocketbase/pb_hooks/shop).
export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => {
let body: Record<string, unknown>;
try {
body = await request.json();
@ -28,75 +12,12 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
throw error(400, 'Invalid JSON body');
}
const customer: CustomerDetails = {
name: String(body.name || '').trim(),
email: String(body.email || '').trim(),
phone: String(body.phone || '').trim(),
notes: String(body.notes || '').trim()
};
if (!customer.name) throw error(400, 'Name is required');
if (!customer.email || !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(customer.email)) {
throw error(400, 'A valid email is required');
}
// Re-validate every line server-side (source of truth for the total).
let totalCents = 0;
for (const line of basket.lines) {
const item = await pb.collection('items').getOne(line.item).catch(() => null);
if (!item || !item.active) throw error(409, `"${line.itemName ?? 'An item'}" is no longer available`);
if (line.lineType === 'slot') {
const slot = await pb.collection('slots').getOne(line.slot!).catch(() => null);
if (!slot || slot.status !== 'held') {
throw error(409, `Your time slot for "${item.name}" has expired — please pick it again`);
}
} else {
if (item.stock != null && item.stock < line.quantity) {
throw error(409, `Only ${item.stock} of "${item.name}" left in stock`);
}
}
totalCents += Math.round(item.price * 100) * line.quantity;
}
if (totalCents <= 0) throw error(400, 'Basket total must be positive');
let paymentIntent;
if (basket.stripePaymentIntentId) {
// Reuse an existing intent when possible (page reload / retry).
try {
const existing = await getStripe().paymentIntents.retrieve(basket.stripePaymentIntentId);
if (existing.status === 'requires_payment_method' || existing.status === 'requires_confirmation') {
paymentIntent = await getStripe().paymentIntents.update(existing.id, {
amount: totalCents,
metadata: { basket_id: basket.id }
});
}
} catch {
// Intent missing/invalid — fall through and create a new one
}
}
if (!paymentIntent) {
paymentIntent = await getStripe().paymentIntents.create({
amount: totalCents,
currency: getCurrency(),
automatic_payment_methods: { enabled: true },
receipt_email: customer.email,
metadata: {
basket_id: basket.id,
line_summary: basket.lines
.map((l) => `${l.quantity}× ${l.itemName ?? l.item}`)
.join('; ')
.slice(0, 450)
}
});
}
await pb.collection('baskets').update(basket.id, {
stripePaymentIntentId: paymentIntent.id,
email: customer.email,
customerDetails: customer
const { clientSecret } = await postJson<{ clientSecret: string }>('/checkout', {
basketId: cookies.get(BASKET_COOKIE) || '',
name: body.name,
email: body.email,
phone: body.phone,
notes: body.notes
});
return json({ clientSecret: paymentIntent.client_secret });
};
return json({ clientSecret });
});

View file

@ -1,128 +1,25 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { env } from '$env/dynamic/private';
import { getStripe } from '$lib/stripe.server';
import { getAdminPb } from '$lib/server/pb-admin';
import { getFileUrl } from '$lib/pb';
import { SLOT_HOLD_MS, extendBasketHolds } from '$lib/server/basket';
import { sendOrderEmails } from '$lib/server/email';
import type PocketBase from 'pocketbase';
import { jsonErrors, sendAndRecordOrderEmails, shopFetch } from '$lib/server/shop';
import type { OrderEmailData } from '$lib/server/email';
async function handlePaymentSucceeded(pb: PocketBase, paymentIntent: any) {
const basketId = paymentIntent.metadata?.basket_id;
if (!basketId) return; // Not one of ours
// Idempotency: if an order already exists for this intent, we're done.
const existing = await pb
.collection('orders')
.getFirstListItem(pb.filter('stripePaymentIntentId = {:id}', { id: paymentIntent.id }))
.catch(() => null);
if (existing) return;
const basket = await pb.collection('baskets').getOne(basketId).catch(() => null);
if (!basket) return;
const lines = await pb
.collection('basket_lines')
.getFullList({ filter: pb.filter('basket = {:basketId}', { basketId }), expand: 'item,slot' });
// Create the order
const order = await pb.collection('orders').create({
basket: basketId,
email: basket.email || paymentIntent.receipt_email || '',
customerDetails: basket.customerDetails || {},
total: paymentIntent.amount / 100,
status: 'paid',
stripePaymentIntentId: paymentIntent.id
});
// Snapshot order lines, flip slots to booked, decrement item stock
for (const line of lines) {
const item = line.expand?.item;
const slot = line.expand?.slot;
await pb.collection('order_lines').create({
order: order.id,
item: line.item,
slot: line.slot || null,
quantity: line.quantity,
lineType: line.lineType,
name: item?.name ?? 'Unknown item',
price: item?.price ?? 0,
start: slot?.start || null
});
if (line.lineType === 'slot' && line.slot) {
await pb
.collection('slots')
.update(line.slot, { status: 'booked', heldUntil: null, order: order.id })
.catch(() => {});
} else if (line.lineType === 'item' && item?.stock != null) {
await pb
.collection('items')
.update(item.id, { stock: Math.max(0, item.stock - line.quantity) })
.catch(() => {});
}
}
// Basket completed — lines can go (order_lines hold the snapshot).
for (const line of lines) {
await pb.collection('basket_lines').delete(line.id).catch(() => {});
}
await pb.collection('baskets').update(basketId, { status: 'completed' }).catch(() => {});
// Confirmation to the customer + alert to the studio. Not awaited: SMTP can
// be slow and Stripe only needs the 2xx. sendOrderEmails never throws and
// records the outcome on the order, so failures can be resent from /orders.
void sendOrderEmails(pb, order.id);
}
async function handlePaymentFailed(pb: PocketBase, paymentIntent: any) {
const basketId = paymentIntent.metadata?.basket_id;
if (!basketId) return;
// The card was refused (or the payment otherwise failed). Keep the slots
// held for the customer so they can retry without re-picking them — just
// reset the hold to the standard 10-minute window. Starting payment again
// (create-intent) will extend it back to 30 min.
await extendBasketHolds(pb, basketId, SLOT_HOLD_MS).catch(() => {});
if (paymentIntent.id) {
await pb
.collection('baskets')
.update(basketId, { stripePaymentIntentId: null })
.catch(() => {});
}
}
export const POST: RequestHandler = async ({ request }) => {
const secret = env.STRIPE_WEBHOOK_SECRET;
if (!secret) throw error(500, 'STRIPE_WEBHOOK_SECRET is not configured');
// Signature verification MUST use the raw request body.
const body = await request.text();
// Stripe webhook endpoint (keeps the URL configured in the Stripe dashboard).
// PocketBase verifies the signature and creates the order; this app only
// sends the booking emails, which it can render (pocketbase/pb_hooks/shop).
export const POST: RequestHandler = jsonErrors(async ({ request }) => {
const signature = request.headers.get('stripe-signature');
if (!signature) throw error(400, 'Missing Stripe-Signature header');
let event;
try {
event = getStripe().webhooks.constructEvent(body, signature, secret);
} catch (e) {
throw error(400, `Webhook signature verification failed: ${e instanceof Error ? e.message : 'unknown'}`);
}
// Forward the exact body: the signature covers the raw bytes.
const result = await shopFetch<{ received: boolean; orderEmail: OrderEmailData | null }>('/stripe-webhook', {
method: 'POST',
headers: { 'Content-Type': request.headers.get('content-type') || 'application/json', 'Stripe-Signature': signature },
body: await request.text()
});
const pb = await getAdminPb();
switch (event.type) {
case 'payment_intent.succeeded':
await handlePaymentSucceeded(pb, event.data.object);
break;
case 'payment_intent.payment_failed':
await handlePaymentFailed(pb, event.data.object);
break;
default:
// Unhandled event types are fine — acknowledge receipt.
break;
}
// Not awaited: SMTP can be slow and Stripe only needs the 2xx. Failures are
// recorded on the order and can be resent from the admin's /orders.
if (result.orderEmail) void sendAndRecordOrderEmails(result.orderEmail);
return json({ received: true });
};
});