import 'server-only'; import { createHash, createHmac, timingSafeEqual } from 'node:crypto'; import { getCloudflareContext } from '@opennextjs/cloudflare'; import { frameAspect, isSquareAspect, priceCents, PRODUCTS, type Orientation, type ProductId } from '@/app/lib/pricing'; import { imageDimensions } from '@/app/lib/image-processing'; import { boundedBody, imageMime, MAX_PIXELS, MAX_REQUEST_BYTES, rawUpload, StudioError } from '@/app/lib/studio-media'; import { authOrigin, getCustomerUser } from '@/app/lib/lumen-auth'; import { generateOrderId } from '@/app/lib/orders'; export const PRINT_WORKFLOW = 'self_service_print_v1'; export const PRINT_SHIPPING_COUNTRY = 'US'; const QUOTE_TTL_MS = 15 * 60 * 1000; const ORDER_ID = /^lg_[23456789abcdefghjkmnpqrstuvwxyz]{10}$/; const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; const HEX = /^[0-9a-f]{64}$/; export const PRINT_HEADERS = { 'Cache-Control': 'private, no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer' }; export type PrintSelection = { productId: ProductId; size: string; orientation: Orientation; frame: string; matteId?: string; wrap?: string; }; export type PrintMime = 'image/jpeg' | 'image/png'; export type PrintArtwork = { bytes: Buffer; mime: PrintMime; width: number; height: number; sha256: string }; type Quote = { version: 1; user: string; orderId: string; generationId: string; amountCents: number; selection: PrintSelection; configSha256: string; artworkSha256: string; mime: PrintMime; expiresAt: number; shippingCountry: typeof PRINT_SHIPPING_COUNTRY; }; export type PrintApproval = { version: 1; generationId: string; amountCents: number; artworkSha256: string; configSha256: string; cleanUrl: string; approvedAt: string; shippingCountry: typeof PRINT_SHIPPING_COUNTRY; artworkMime: PrintMime; }; function runtimeValue(name: string) { try { const value = (getCloudflareContext().env as Record)[name]; if (typeof value === 'string') return value; } catch { /* Standalone Next/tests have no Workers context. */ } return process.env[name]; } function secret() { const key = runtimeValue('LUMEN_SELF_SERVICE_PRINT_SECRET'); if (!key || key.length < 32) throw unavailable(); return key; } export function printEnabled() { if (runtimeValue('LUMEN_SELF_SERVICE_PRINT_ENABLED') !== 'true' || (runtimeValue('LUMEN_SELF_SERVICE_PRINT_SECRET')?.length ?? 0) < 32 || !process.env.STRIPE_SECRET_KEY || !process.env.STRIPE_WEBHOOK_SECRET || !/^[A-Za-z0-9_-]{16,}$/.test(process.env.PRODIGI_WEBHOOK_TOKEN ?? '')) return false; try { if (new URL(authOrigin()).protocol !== 'https:') return false; const mode = /^(?:sk|rk)_(test|live)_/.exec(process.env.STRIPE_SECRET_KEY)?.[1]; const prodigi = new URL(process.env.PRODIGI_API_BASE_URL || 'https://api.prodigi.com/v4.0/'); if (prodigi.username || prodigi.password || prodigi.search || prodigi.hash || prodigi.port || prodigi.protocol !== 'https:' || !/^\/v4\.0\/?$/.test(prodigi.pathname)) return false; if (mode === 'test' ? prodigi.hostname !== 'api.sandbox.prodigi.com' || !process.env.PRODIGI_API_KEY_SANDBOX : mode !== 'live' || prodigi.hostname !== 'api.prodigi.com' || !process.env.PRODIGI_API_KEY) return false; const resources = getCloudflareContext().env as { COMMERCE_DB?: { prepare?: unknown }; REVIEW_PHOTOS?: { get?: unknown; put?: unknown } }; return typeof resources.COMMERCE_DB?.prepare === 'function' && typeof resources.REVIEW_PHOTOS?.get === 'function' && typeof resources.REVIEW_PHOTOS?.put === 'function'; } catch { return false; } } export function unavailable() { return new StudioError('print_unavailable', 503, 'Physical print checkout is not available right now. Digital downloads are still free.'); } export function printError(error: unknown) { const issue = error instanceof StudioError ? error : unavailable(); return Response.json({ error: issue.message, code: issue.code }, { status: issue.status, headers: PRINT_HEADERS }); } export async function requirePrintCustomer(req: Request) { const origin = authOrigin(); if (req.headers.get('origin') !== origin || new URL(req.url).origin !== origin) { throw new StudioError('invalid_origin', 403, 'Open Studio directly to place a print order.'); } if (!printEnabled()) throw unavailable(); const user = await getCustomerUser().catch(() => null); if (!user?.id || !user.email) throw new StudioError('sign_in', 401, 'Sign in to approve and order a print.'); return { id: user.id, email: user.email }; } const badSelection = () => new StudioError('invalid_selection', 400, 'Choose an available print size, frame and finish.'); export function parsePrintSelection(input: unknown): PrintSelection { if (!input || typeof input !== 'object' || Array.isArray(input)) throw badSelection(); const r = input as Record; if (Object.keys(r).some(key => !['productId','size','orientation','frame','matteId','wrap'].includes(key))) throw badSelection(); const { productId, size, orientation, frame, matteId, wrap } = r; if (typeof productId !== 'string' || !Object.hasOwn(PRODUCTS, productId) || typeof size !== 'string' || (orientation !== 'portrait' && orientation !== 'landscape') || typeof frame !== 'string') throw badSelection(); const id = productId as ProductId; const product = PRODUCTS[id]; const aspect = frameAspect(id, size, orientation); if (!Object.hasOwn(product.sizes, size) || !aspect || (orientation === 'landscape' && isSquareAspect(aspect))) throw badSelection(); const frameNames: readonly string[] = product.availableFrames; if (!frameNames.length ? frame !== 'none' : !frameNames.includes(frame)) throw badSelection(); let matte: string | undefined; let edge: string | undefined; if ('availableMattes' in product) { const choices: readonly string[] = product.availableMattes; if (typeof matteId !== 'string' || !choices.includes(matteId)) throw badSelection(); matte = matteId; } else if (matteId !== undefined) throw badSelection(); if ('availableWraps' in product) { const choices: readonly string[] = product.availableWraps; if (typeof wrap !== 'string' || !choices.includes(wrap)) throw badSelection(); edge = wrap; } else if (wrap !== undefined) throw badSelection(); return { productId: id, size, orientation, frame, ...(matte === undefined ? {} : { matteId: matte }), ...(edge === undefined ? {} : { wrap: edge }), }; } export function printConfigSha256(selection: PrintSelection): string { const { productId, size, orientation, frame, matteId, wrap } = selection; return hash(JSON.stringify([productId, size, orientation, frame, matteId ?? null, wrap ?? null])); } function hash(data: string | Uint8Array) { return createHash('sha256').update(data).digest('hex'); } function sign(domain: string, value: string) { return createHmac('sha256', secret()).update(domain).update('\0').update(value).digest('hex'); } function safeEqual(a: string, b: string) { if (!HEX.test(a) || !HEX.test(b)) return false; return timingSafeEqual(Buffer.from(a, 'hex'), Buffer.from(b, 'hex')); } export async function readPrintForm(req: Request, fields: string[]) { const contentType = req.headers.get('content-type') ?? ''; if (!/^multipart\/form-data;\s*boundary=/i.test(contentType)) { throw new StudioError('invalid_request', 415, 'Send the print request as a multipart form.'); } const large = new StudioError('upload_too_large', 413, 'Choose a JPG or PNG print file under 6 MB.'); const length = req.headers.get('content-length'); if (length && (!/^\d+$/.test(length) || Number(length) > MAX_REQUEST_BYTES)) throw large; const bytes = await boundedBody(req.body, MAX_REQUEST_BYTES, large); let form: FormData; try { form = await new Response(bytes, { headers: { 'content-type': contentType } }).formData(); } catch { throw new StudioError('invalid_request', 400, 'The print form could not be read.'); } if ([...form.keys()].some(key => !fields.includes(key) || form.getAll(key).length !== 1)) { throw new StudioError('invalid_request', 400, 'The print form contains unsupported fields.'); } return form; } export async function printArtwork(value: FormDataEntryValue | null, selection: PrintSelection): Promise { const badImage = () => new StudioError('invalid_image', 400, 'Choose a valid, non-animated JPG or PNG print file under 6 MB.'); try { if (!value || typeof value === 'string') throw badImage(); const bytes = await rawUpload(value); const mime = imageMime(bytes); if (mime !== 'image/jpeg' && mime !== 'image/png') throw badImage(); // APNG animation and EXIF rotation can disagree between the browser and // fulfillment decoder. Require a flattened, upright export without EXIF. if (mime === 'image/png' && hasUnsafePngChunks(bytes)) throw badImage(); if (mime === 'image/jpeg' && hasJpegExif(bytes)) throw badImage(); const { width, height } = await imageDimensions(bytes); if (!width || !height || width * height > MAX_PIXELS || width > 10000 || height > 10000) throw badImage(); const [aspectWidth, aspectHeight] = frameAspect(selection.productId, selection.size, selection.orientation)!.split('/').map(Number); if (Math.abs((width / height) / (aspectWidth / aspectHeight) - 1) > 0.01) { throw new StudioError('print_aspect', 400, 'The artwork does not match this print shape. Export a matching crop and review it before placing the order.'); } const inches = selection.size.split('x').map(Number); if (selection.orientation === 'landscape') inches.reverse(); if (width / inches[0] < 120 || height / inches[1] < 120) { throw new StudioError('print_resolution', 400, 'The artwork is too small for this print. Choose a smaller print or export a higher-resolution file.'); } return { bytes, mime, width, height, sha256: hash(bytes) }; } catch (error) { if (error instanceof StudioError) throw error; throw badImage(); } } // Walk complete PNG chunks; do not confuse image data with metadata markers. function hasUnsafePngChunks(bytes: Buffer) { let offset = 8; let ihdr = false; let data = false; while (offset + 12 <= bytes.length) { const len = bytes.readUInt32BE(offset); if (len > bytes.length - offset - 12) return true; const name = bytes.toString('ascii', offset + 4, offset + 8); if (name === 'IHDR') ihdr = offset === 8 && len === 13; if (name === 'IDAT') data = true; if (name === 'acTL' || name === 'fcTL' || name === 'fdAT' || name === 'eXIf') return true; offset += len + 12; if (name === 'IEND') return !(ihdr && data && len === 0 && offset === bytes.length); } return true; } function hasJpegExif(bytes: Buffer) { let offset = 2; while (offset + 1 < bytes.length) { if (bytes[offset++] !== 0xff) return true; while (bytes[offset] === 0xff) offset++; const marker = bytes[offset++]; if (marker === 0xda) return false; if (marker === 0xd9 || offset + 2 > bytes.length) return true; const length = bytes.readUInt16BE(offset); if (length < 2 || offset + length > bytes.length) return true; if (marker === 0xe1 && bytes.toString('ascii', offset + 2, offset + 8) === 'Exif\0\0') return true; offset += length; } return true; } export function createPrintQuote(user: string, selection: PrintSelection, image: PrintArtwork) { const quote: Quote = { version: 1, user, orderId: generateOrderId(), generationId: crypto.randomUUID(), amountCents: priceCents(selection.productId, selection.size, selection.matteId), selection, configSha256: printConfigSha256(selection), artworkSha256: image.sha256, mime: image.mime, expiresAt: Date.now() + QUOTE_TTL_MS, shippingCountry: PRINT_SHIPPING_COUNTRY, }; const payload = Buffer.from(JSON.stringify(quote)).toString('base64url'); const quoteToken = payload + '.' + sign('quote', payload); return { quoteToken, amountCents: quote.amountCents, currency: 'USD', selection, width: image.width, height: image.height, artworkSha256: image.sha256, expiresAt: quote.expiresAt, shippingCountry: quote.shippingCountry }; } export function verifyPrintQuote(entry: FormDataEntryValue | null, user: string): Quote { const stale = () => new StudioError('quote_expired', 409, 'Review the current print quote again before paying.'); if (typeof entry !== 'string' || entry.length > 4096 || !/^[A-Za-z0-9_-]+\.[a-f0-9]{64}$/.test(entry)) throw stale(); const [payload, signature] = entry.split('.'); if (!safeEqual(signature, sign('quote', payload))) throw stale(); let quote: Quote; try { quote = JSON.parse(Buffer.from(payload, 'base64url').toString()) as Quote; } catch { throw stale(); } if (quote?.version !== 1 || quote.user !== user || !ORDER_ID.test(quote.orderId) || !UUID.test(quote.generationId) || !HEX.test(quote.artworkSha256) || !HEX.test(quote.configSha256) || quote.shippingCountry !== PRINT_SHIPPING_COUNTRY || !Number.isSafeInteger(quote.expiresAt) || quote.expiresAt <= Date.now() || quote.expiresAt > Date.now() + QUOTE_TTL_MS || (quote.mime !== 'image/jpeg' && quote.mime !== 'image/png')) throw stale(); const selection = parsePrintSelection(quote.selection); if (quote.configSha256 !== printConfigSha256(selection) || quote.amountCents !== priceCents(selection.productId, selection.size, selection.matteId)) throw stale(); return { ...quote, selection }; } export function approvePrint(quote: Quote): PrintApproval { return { version: 1, generationId: quote.generationId, amountCents: quote.amountCents, artworkSha256: quote.artworkSha256, configSha256: quote.configSha256, cleanUrl: printAssetURL(quote.orderId, quote.artworkSha256), approvedAt: new Date().toISOString(), shippingCountry: quote.shippingCountry, artworkMime: quote.mime, }; } export function printAssetKey(orderId: string, artworkSha256: string) { if (!ORDER_ID.test(orderId) || !HEX.test(artworkSha256)) throw new Error('Invalid print asset identity.'); return `studio-print/v1/${orderId}/${artworkSha256}`; } export function printAssetURL(orderId: string, artworkSha256: string) { const key = printAssetKey(orderId, artworkSha256); return new URL(`/api/studio/print/asset/${orderId}?key=${artworkSha256}.${sign('asset', key)}`, authOrigin()).href; } export function printAssetMatches(url: string, orderId: string, artworkSha256: string) { try { return url === printAssetURL(orderId, artworkSha256); } catch { return false; } } export function printAssetRequestMatches(url: string, orderId: string) { try { const key = new URL(url).searchParams.get('key'); if (!key || !/^[a-f0-9]{64}\.[a-f0-9]{64}$/.test(key)) return false; return printAssetMatches(url, orderId, key.split('.')[0]); } catch { return false; } } export function validPrintOrder(id: string) { return ORDER_ID.test(id); }