import 'server-only'; import { createHash } from 'node:crypto'; import { commerceDb } from '@/app/lib/commerce-db'; import { reviewPhotoBucket } from '@/app/lib/review-photo-storage'; import { boundedBody, MAX_UPLOAD_BYTES, StudioError } from '@/app/lib/studio-media'; import { studioDatabase } from '@/app/lib/studio-config'; import { approvePrint, parsePrintSelection, PRINT_SHIPPING_COUNTRY, PRINT_WORKFLOW, printAssetKey, printAssetMatches, printConfigSha256, type PrintApproval, type PrintArtwork, type PrintMime, type PrintSelection, unavailable, type verifyPrintQuote } from './protocol'; type Quote = ReturnType; export type StoredPrint = PrintSelection & { workflow: typeof PRINT_WORKFLOW; selfServicePrint: PrintApproval }; const OUTSTANDING_LIMIT = 6; const conflict = () => new StudioError('print_state_changed', 409, 'This print approval cannot be reused. Check your orders before starting again.'); export function readStoredPrint(config: unknown): StoredPrint | null { try { if (!config || typeof config !== 'object' || Array.isArray(config)) return null; const { workflow, selfServicePrint, productId, size, orientation, frame, matteId, wrap } = config as Record; if (!selfServicePrint || typeof selfServicePrint !== 'object' || Array.isArray(selfServicePrint)) return null; const a = selfServicePrint as Partial; if (workflow !== PRINT_WORKFLOW || !a || a.version !== 1 || typeof a.generationId !== 'string' || !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(a.generationId) || typeof a.artworkSha256 !== 'string' || !/^[a-f0-9]{64}$/.test(a.artworkSha256) || typeof a.configSha256 !== 'string' || !/^[a-f0-9]{64}$/.test(a.configSha256) || typeof a.cleanUrl !== 'string' || typeof a.amountCents !== 'number' || !Number.isSafeInteger(a.amountCents) || a.amountCents <= 0 || typeof a.approvedAt !== 'string' || !Number.isFinite(Date.parse(a.approvedAt)) || a.shippingCountry !== PRINT_SHIPPING_COUNTRY || (a.artworkMime !== 'image/jpeg' && a.artworkMime !== 'image/png')) return null; const selection = parsePrintSelection({productId,size,orientation,frame,matteId,wrap}); if (printConfigSha256(selection) !== a.configSha256) return null; return { ...selection, workflow, selfServicePrint: a as PrintApproval }; } catch { return null; } } function validateQuoteMatch(order: { id: string; user_id: string; user_email: string; status: string; config: unknown; price_cents: number; current_generation_id: string | null; }, quote: Quote, expectedEmail: string) { const cfg = readStoredPrint(order.config); const a = cfg?.selfServicePrint; if (order.id !== quote.orderId || order.user_id !== quote.user || order.user_email !== expectedEmail || order.status !== 'pending_payment' || order.price_cents !== quote.amountCents || !a || a.amountCents !== quote.amountCents || a.generationId !== quote.generationId || a.artworkSha256 !== quote.artworkSha256 || a.configSha256 !== quote.configSha256 || a.artworkMime !== quote.mime || !printAssetMatches(a.cleanUrl, quote.orderId, quote.artworkSha256) || (order.current_generation_id && order.current_generation_id !== quote.generationId)) throw conflict(); return a; } export async function stageApprovedPrint(quote: Quote, artwork: PrintArtwork, email: string) { const db = commerceDb(); const selection = quote.selection; const approval = approvePrint(quote); const date = approval.approvedAt; const config: StoredPrint = { ...selection, workflow: PRINT_WORKFLOW, selfServicePrint: approval }; const existing = () => db.from('orders') .select('id, user_id, user_email, status, config, price_cents, current_generation_id, stripe_session_id') .eq('id', quote.orderId).maybeSingle(); let state = await existing(); if (state.error) throw unavailable(); if (!state.data) { // INSERT...SELECT binds the per-member count and reservation in the same // write. It also makes a concurrent retry for this quote harmless. const newOrder = await studioDatabase().prepare(` INSERT INTO orders ( id,user_id,user_email,status,config,price_cents,pet_photo_urls, cart_reminders_sent,created_at,updated_at,terms_accepted_at ) SELECT ?1,?2,?3,'pending_payment',?4,?5,'[]',0,?6,?6,?6 WHERE (SELECT count(*) FROM orders WHERE user_id = ?2 AND status = 'pending_payment' AND json_extract(config,'$.workflow') = ?7 AND julianday(created_at) >= julianday('now','-1 day')) < ?8 ON CONFLICT (id) DO NOTHING RETURNING id`) .bind(quote.orderId, quote.user, email, JSON.stringify(config), quote.amountCents, date, PRINT_WORKFLOW, OUTSTANDING_LIMIT) .first<{ id: string }>(); state = await existing(); if (state.error) throw unavailable(); if (!state.data && !newOrder) throw new StudioError('print_limit', 429, 'Too many print checkouts are open. Complete an existing checkout or wait until it expires.'); if (!state.data) throw unavailable(); } const storedOrder = state.data; const storedApproval = validateQuoteMatch(storedOrder, quote, email); if (!storedOrder.current_generation_id) { const key = printAssetKey(quote.orderId, quote.artworkSha256); // A retry may overwrite only the exact same hash-keyed file. The signed // quote and the byte hash were verified before this step. await reviewPhotoBucket().put(key, new Uint8Array(artwork.bytes), { httpMetadata: { contentType: artwork.mime } }); const attached = await db.from('generations').insert({ id: storedApproval.generationId, order_id: storedOrder.id, prompt: '', model: PRINT_WORKFLOW, clean_url: storedApproval.cleanUrl, watermarked_url: storedApproval.cleanUrl, published: false, }); if (attached.error && attached.error.code !== '23505') throw unavailable(); } // On retry, require the exact same immutable attachment and bytes. Never // repair or charge for a missing/mutated already-approved file. const generation = await db.from('generations') .select('id, order_id, clean_url, model') .eq('id', storedApproval.generationId).maybeSingle(); if (generation.error) throw unavailable(); if (generation.data?.order_id !== storedOrder.id || generation.data?.clean_url !== storedApproval.cleanUrl || generation.data.model !== PRINT_WORKFLOW) throw conflict(); if (!await readPrintArtworkForOrder(storedOrder.id, storedApproval.artworkSha256)) throw conflict(); if (!storedOrder.current_generation_id) { const linked = await db.from('orders').update({ current_generation_id: storedApproval.generationId }) .eq('id', storedOrder.id).eq('status', 'pending_payment').select('current_generation_id').maybeSingle(); if (linked.error || linked.data?.current_generation_id !== storedApproval.generationId) throw conflict(); } return { orderId: storedOrder.id, stripeSessionId: storedOrder.stripe_session_id, approval: storedApproval, selection }; } /** Used by the webhook to validate the exact private bytes before allowing Prodigi submission. */ export async function readPrintArtworkForOrder(orderId: string, hash: string): Promise { const object = await reviewPhotoBucket().get(printAssetKey(orderId, hash)); if (!object?.body) return null; const bytes = await boundedBody(object.body, MAX_UPLOAD_BYTES, unavailable()); return bytes.byteLength && createHash('sha256').update(bytes).digest('hex') === hash ? bytes : null; } export async function paidPrintAsset(orderId: string, requestUrl: string): Promise<{ bytes: Uint8Array; mime: PrintMime } | null> { const record = await commerceDb().from('orders') .select('id, config, current_generation_id, stripe_payment_intent_id, status') .eq('id', orderId).maybeSingle(); if (record.error) throw unavailable(); const order = record.data; if (!order || !order.stripe_payment_intent_id || order.status === 'cancelled') return null; const cfg = readStoredPrint(order.config); const a = cfg?.selfServicePrint; if (!a || a.generationId !== order.current_generation_id || a.cleanUrl !== requestUrl || !printAssetMatches(a.cleanUrl, orderId, a.artworkSha256)) return null; const bytes = await readPrintArtworkForOrder(orderId, a.artworkSha256); return bytes ? { bytes, mime: a.artworkMime } : null; }