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,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 });
};
});