Lumen & Gesso / website · lumengesso.com / app / api / studio / print / persistence.ts
| 1 | import 'server-only'; |
| 2 | import { createHash } from 'node:crypto'; |
| 3 | import { commerceDb } from '@/app/lib/commerce-db'; |
| 4 | import { reviewPhotoBucket } from '@/app/lib/review-photo-storage'; |
| 5 | import { boundedBody, MAX_UPLOAD_BYTES, StudioError } from '@/app/lib/studio-media'; |
| 6 | import { studioDatabase } from '@/app/lib/studio-config'; |
| 7 | import { approvePrint, parsePrintSelection, PRINT_SHIPPING_COUNTRY, PRINT_WORKFLOW, printAssetKey, printAssetMatches, printConfigSha256, type PrintApproval, type PrintArtwork, type PrintMime, type PrintSelection, unavailable, type verifyPrintQuote } from './protocol'; |
| 8 | |
| 9 | type Quote = ReturnType<typeof verifyPrintQuote>; |
| 10 | |
| 11 | export type StoredPrint = PrintSelection & { workflow: typeof PRINT_WORKFLOW; selfServicePrint: PrintApproval }; |
| 12 | const OUTSTANDING_LIMIT = 6; |
| 13 | const conflict = () => new StudioError('print_state_changed', 409, 'This print approval cannot be reused. Check your orders before starting again.'); |
| 14 | |
| 15 | export function readStoredPrint(config: unknown): StoredPrint | null { |
| 16 | try { |
| 17 | if (!config || typeof config !== 'object' || Array.isArray(config)) return null; |
| 18 | const { workflow, selfServicePrint, productId, size, orientation, frame, matteId, wrap } = config as Record<string, unknown>; |
| 19 | if (!selfServicePrint || typeof selfServicePrint !== 'object' || Array.isArray(selfServicePrint)) return null; |
| 20 | const a = selfServicePrint as Partial<PrintApproval>; |
| 21 | if (workflow !== PRINT_WORKFLOW || !a || a.version !== 1 |
| 22 | || typeof a.generationId !== 'string' || !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(a.generationId) |
| 23 | || typeof a.artworkSha256 !== 'string' || !/^[a-f0-9]{64}$/.test(a.artworkSha256) |
| 24 | || typeof a.configSha256 !== 'string' || !/^[a-f0-9]{64}$/.test(a.configSha256) || typeof a.cleanUrl !== 'string' |
| 25 | || typeof a.amountCents !== 'number' || !Number.isSafeInteger(a.amountCents) || a.amountCents <= 0 |
| 26 | || typeof a.approvedAt !== 'string' || !Number.isFinite(Date.parse(a.approvedAt)) || a.shippingCountry !== PRINT_SHIPPING_COUNTRY |
| 27 | || (a.artworkMime !== 'image/jpeg' && a.artworkMime !== 'image/png')) return null; |
| 28 | const selection = parsePrintSelection({productId,size,orientation,frame,matteId,wrap}); |
| 29 | if (printConfigSha256(selection) !== a.configSha256) return null; |
| 30 | return { ...selection, workflow, selfServicePrint: a as PrintApproval }; |
| 31 | } catch { return null; } |
| 32 | } |
| 33 | |
| 34 | function validateQuoteMatch(order: { |
| 35 | id: string; user_id: string; user_email: string; status: string; |
| 36 | config: unknown; price_cents: number; current_generation_id: string | null; |
| 37 | }, quote: Quote, expectedEmail: string) { |
| 38 | const cfg = readStoredPrint(order.config); |
| 39 | const a = cfg?.selfServicePrint; |
| 40 | if (order.id !== quote.orderId || order.user_id !== quote.user || order.user_email !== expectedEmail || |
| 41 | order.status !== 'pending_payment' || order.price_cents !== quote.amountCents || |
| 42 | !a || a.amountCents !== quote.amountCents || a.generationId !== quote.generationId || |
| 43 | a.artworkSha256 !== quote.artworkSha256 || a.configSha256 !== quote.configSha256 || |
| 44 | a.artworkMime !== quote.mime || !printAssetMatches(a.cleanUrl, quote.orderId, quote.artworkSha256) || |
| 45 | (order.current_generation_id && order.current_generation_id !== quote.generationId)) throw conflict(); |
| 46 | return a; |
| 47 | } |
| 48 | |
| 49 | export async function stageApprovedPrint(quote: Quote, artwork: PrintArtwork, email: string) { |
| 50 | const db = commerceDb(); |
| 51 | const selection = quote.selection; |
| 52 | const approval = approvePrint(quote); |
| 53 | const date = approval.approvedAt; |
| 54 | const config: StoredPrint = { ...selection, workflow: PRINT_WORKFLOW, selfServicePrint: approval }; |
| 55 | const existing = () => db.from('orders') |
| 56 | .select('id, user_id, user_email, status, config, price_cents, current_generation_id, stripe_session_id') |
| 57 | .eq('id', quote.orderId).maybeSingle(); |
| 58 | let state = await existing(); |
| 59 | if (state.error) throw unavailable(); |
| 60 | if (!state.data) { |
| 61 | // INSERT...SELECT binds the per-member count and reservation in the same |
| 62 | // write. It also makes a concurrent retry for this quote harmless. |
| 63 | const newOrder = await studioDatabase().prepare(` |
| 64 | INSERT INTO orders ( |
| 65 | id,user_id,user_email,status,config,price_cents,pet_photo_urls, |
| 66 | cart_reminders_sent,created_at,updated_at,terms_accepted_at |
| 67 | ) |
| 68 | SELECT ?1,?2,?3,'pending_payment',?4,?5,'[]',0,?6,?6,?6 |
| 69 | WHERE (SELECT count(*) FROM orders WHERE user_id = ?2 AND status = 'pending_payment' |
| 70 | AND json_extract(config,'$.workflow') = ?7 AND julianday(created_at) >= julianday('now','-1 day')) < ?8 |
| 71 | ON CONFLICT (id) DO NOTHING RETURNING id`) |
| 72 | .bind(quote.orderId, quote.user, email, JSON.stringify(config), quote.amountCents, date, PRINT_WORKFLOW, OUTSTANDING_LIMIT) |
| 73 | .first<{ id: string }>(); |
| 74 | state = await existing(); |
| 75 | if (state.error) throw unavailable(); |
| 76 | 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.'); |
| 77 | if (!state.data) throw unavailable(); |
| 78 | } |
| 79 | const storedOrder = state.data; |
| 80 | const storedApproval = validateQuoteMatch(storedOrder, quote, email); |
| 81 | if (!storedOrder.current_generation_id) { |
| 82 | const key = printAssetKey(quote.orderId, quote.artworkSha256); |
| 83 | // A retry may overwrite only the exact same hash-keyed file. The signed |
| 84 | // quote and the byte hash were verified before this step. |
| 85 | await reviewPhotoBucket().put(key, new Uint8Array(artwork.bytes), { httpMetadata: { contentType: artwork.mime } }); |
| 86 | const attached = await db.from('generations').insert({ |
| 87 | id: storedApproval.generationId, order_id: storedOrder.id, |
| 88 | prompt: '', model: PRINT_WORKFLOW, clean_url: storedApproval.cleanUrl, |
| 89 | watermarked_url: storedApproval.cleanUrl, published: false, |
| 90 | }); |
| 91 | if (attached.error && attached.error.code !== '23505') throw unavailable(); |
| 92 | } |
| 93 | // On retry, require the exact same immutable attachment and bytes. Never |
| 94 | // repair or charge for a missing/mutated already-approved file. |
| 95 | const generation = await db.from('generations') |
| 96 | .select('id, order_id, clean_url, model') |
| 97 | .eq('id', storedApproval.generationId).maybeSingle(); |
| 98 | if (generation.error) throw unavailable(); |
| 99 | if (generation.data?.order_id !== storedOrder.id || generation.data?.clean_url !== storedApproval.cleanUrl |
| 100 | || generation.data.model !== PRINT_WORKFLOW) throw conflict(); |
| 101 | if (!await readPrintArtworkForOrder(storedOrder.id, storedApproval.artworkSha256)) throw conflict(); |
| 102 | if (!storedOrder.current_generation_id) { |
| 103 | const linked = await db.from('orders').update({ current_generation_id: storedApproval.generationId }) |
| 104 | .eq('id', storedOrder.id).eq('status', 'pending_payment').select('current_generation_id').maybeSingle(); |
| 105 | if (linked.error || linked.data?.current_generation_id !== storedApproval.generationId) throw conflict(); |
| 106 | } |
| 107 | return { orderId: storedOrder.id, stripeSessionId: storedOrder.stripe_session_id, approval: storedApproval, selection }; |
| 108 | } |
| 109 | |
| 110 | /** Used by the webhook to validate the exact private bytes before allowing Prodigi submission. */ |
| 111 | export async function readPrintArtworkForOrder(orderId: string, hash: string): Promise<Uint8Array | null> { |
| 112 | const object = await reviewPhotoBucket().get(printAssetKey(orderId, hash)); |
| 113 | if (!object?.body) return null; |
| 114 | const bytes = await boundedBody(object.body, MAX_UPLOAD_BYTES, unavailable()); |
| 115 | return bytes.byteLength && createHash('sha256').update(bytes).digest('hex') === hash ? bytes : null; |
| 116 | } |
| 117 | |
| 118 | export async function paidPrintAsset(orderId: string, requestUrl: string): Promise<{ bytes: Uint8Array; mime: PrintMime } | null> { |
| 119 | const record = await commerceDb().from('orders') |
| 120 | .select('id, config, current_generation_id, stripe_payment_intent_id, status') |
| 121 | .eq('id', orderId).maybeSingle(); |
| 122 | if (record.error) throw unavailable(); |
| 123 | const order = record.data; |
| 124 | if (!order || !order.stripe_payment_intent_id || order.status === 'cancelled') return null; |
| 125 | const cfg = readStoredPrint(order.config); |
| 126 | const a = cfg?.selfServicePrint; |
| 127 | if (!a || a.generationId !== order.current_generation_id || a.cleanUrl !== requestUrl |
| 128 | || !printAssetMatches(a.cleanUrl, orderId, a.artworkSha256)) return null; |
| 129 | const bytes = await readPrintArtworkForOrder(orderId, a.artworkSha256); |
| 130 | return bytes ? { bytes, mime: a.artworkMime } : null; |
| 131 | } |