Lumen & Gesso / website / app / api / studio / print / protocol.ts
| 1 | import 'server-only'; |
| 2 | import { createHash, createHmac, timingSafeEqual } from 'node:crypto'; |
| 3 | import { getCloudflareContext } from '@opennextjs/cloudflare'; |
| 4 | import { frameAspect, isSquareAspect, priceCents, PRODUCTS, type Orientation, type ProductId } from '@/app/lib/pricing'; |
| 5 | import { imageDimensions } from '@/app/lib/image-processing'; |
| 6 | import { boundedBody, imageMime, MAX_PIXELS, MAX_REQUEST_BYTES, rawUpload, StudioError } from '@/app/lib/studio-media'; |
| 7 | import { authOrigin, getCustomerUser } from '@/app/lib/lumen-auth'; |
| 8 | import { generateOrderId } from '@/app/lib/orders'; |
| 9 | |
| 10 | export const PRINT_WORKFLOW = 'self_service_print_v1'; |
| 11 | export const PRINT_SHIPPING_COUNTRY = 'US'; |
| 12 | const QUOTE_TTL_MS = 15 * 60 * 1000; |
| 13 | const ORDER_ID = /^lg_[23456789abcdefghjkmnpqrstuvwxyz]{10}$/; |
| 14 | const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; |
| 15 | const HEX = /^[0-9a-f]{64}$/; |
| 16 | export const PRINT_HEADERS = { 'Cache-Control': 'private, no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer' }; |
| 17 | |
| 18 | export type PrintSelection = { |
| 19 | productId: ProductId; size: string; orientation: Orientation; frame: string; matteId?: string; wrap?: string; |
| 20 | }; |
| 21 | export type PrintMime = 'image/jpeg' | 'image/png'; |
| 22 | export type PrintArtwork = { bytes: Buffer; mime: PrintMime; width: number; height: number; sha256: string }; |
| 23 | type Quote = { |
| 24 | version: 1; user: string; orderId: string; generationId: string; amountCents: number; |
| 25 | selection: PrintSelection; configSha256: string; artworkSha256: string; |
| 26 | mime: PrintMime; expiresAt: number; shippingCountry: typeof PRINT_SHIPPING_COUNTRY; |
| 27 | }; |
| 28 | export type PrintApproval = { |
| 29 | version: 1; generationId: string; amountCents: number; artworkSha256: string; configSha256: string; |
| 30 | cleanUrl: string; approvedAt: string; shippingCountry: typeof PRINT_SHIPPING_COUNTRY; artworkMime: PrintMime; |
| 31 | }; |
| 32 | |
| 33 | function runtimeValue(name: string) { |
| 34 | try { |
| 35 | const value = (getCloudflareContext().env as Record<string, unknown>)[name]; |
| 36 | if (typeof value === 'string') return value; |
| 37 | } catch { /* Standalone Next/tests have no Workers context. */ } |
| 38 | return process.env[name]; |
| 39 | } |
| 40 | |
| 41 | function secret() { |
| 42 | const key = runtimeValue('LUMEN_SELF_SERVICE_PRINT_SECRET'); |
| 43 | if (!key || key.length < 32) throw unavailable(); |
| 44 | return key; |
| 45 | } |
| 46 | |
| 47 | export function printEnabled() { |
| 48 | if (runtimeValue('LUMEN_SELF_SERVICE_PRINT_ENABLED') !== 'true' |
| 49 | || (runtimeValue('LUMEN_SELF_SERVICE_PRINT_SECRET')?.length ?? 0) < 32 |
| 50 | || !process.env.STRIPE_SECRET_KEY || !process.env.STRIPE_WEBHOOK_SECRET || !/^[A-Za-z0-9_-]{16,}$/.test(process.env.PRODIGI_WEBHOOK_TOKEN ?? '')) return false; |
| 51 | try { |
| 52 | if (new URL(authOrigin()).protocol !== 'https:') return false; |
| 53 | const mode = /^(?:sk|rk)_(test|live)_/.exec(process.env.STRIPE_SECRET_KEY)?.[1]; |
| 54 | const prodigi = new URL(process.env.PRODIGI_API_BASE_URL || 'https://api.prodigi.com/v4.0/'); |
| 55 | if (prodigi.username || prodigi.password || prodigi.search || prodigi.hash |
| 56 | || prodigi.port || prodigi.protocol !== 'https:' || !/^\/v4\.0\/?$/.test(prodigi.pathname)) return false; |
| 57 | if (mode === 'test' ? prodigi.hostname !== 'api.sandbox.prodigi.com' || !process.env.PRODIGI_API_KEY_SANDBOX |
| 58 | : mode !== 'live' || prodigi.hostname !== 'api.prodigi.com' || !process.env.PRODIGI_API_KEY) return false; |
| 59 | const resources = getCloudflareContext().env as { COMMERCE_DB?: { prepare?: unknown }; REVIEW_PHOTOS?: { get?: unknown; put?: unknown } }; |
| 60 | return typeof resources.COMMERCE_DB?.prepare === 'function' |
| 61 | && typeof resources.REVIEW_PHOTOS?.get === 'function' && typeof resources.REVIEW_PHOTOS?.put === 'function'; |
| 62 | } catch { return false; } |
| 63 | } |
| 64 | |
| 65 | export function unavailable() { |
| 66 | return new StudioError('print_unavailable', 503, 'Physical print checkout is not available right now. Digital downloads are still free.'); |
| 67 | } |
| 68 | |
| 69 | export function printError(error: unknown) { |
| 70 | const issue = error instanceof StudioError ? error : unavailable(); |
| 71 | return Response.json({ error: issue.message, code: issue.code }, { status: issue.status, headers: PRINT_HEADERS }); |
| 72 | } |
| 73 | |
| 74 | export async function requirePrintCustomer(req: Request) { |
| 75 | const origin = authOrigin(); |
| 76 | if (req.headers.get('origin') !== origin || new URL(req.url).origin !== origin) { |
| 77 | throw new StudioError('invalid_origin', 403, 'Open Studio directly to place a print order.'); |
| 78 | } |
| 79 | if (!printEnabled()) throw unavailable(); |
| 80 | const user = await getCustomerUser().catch(() => null); |
| 81 | if (!user?.id || !user.email) throw new StudioError('sign_in', 401, 'Sign in to approve and order a print.'); |
| 82 | return { id: user.id, email: user.email }; |
| 83 | } |
| 84 | |
| 85 | const badSelection = () => new StudioError('invalid_selection', 400, 'Choose an available print size, frame and finish.'); |
| 86 | export function parsePrintSelection(input: unknown): PrintSelection { |
| 87 | if (!input || typeof input !== 'object' || Array.isArray(input)) throw badSelection(); |
| 88 | const r = input as Record<string, unknown>; |
| 89 | if (Object.keys(r).some(key => !['productId','size','orientation','frame','matteId','wrap'].includes(key))) throw badSelection(); |
| 90 | const { productId, size, orientation, frame, matteId, wrap } = r; |
| 91 | if (typeof productId !== 'string' || !Object.hasOwn(PRODUCTS, productId) |
| 92 | || typeof size !== 'string' || (orientation !== 'portrait' && orientation !== 'landscape') |
| 93 | || typeof frame !== 'string') throw badSelection(); |
| 94 | const id = productId as ProductId; |
| 95 | const product = PRODUCTS[id]; |
| 96 | const aspect = frameAspect(id, size, orientation); |
| 97 | if (!Object.hasOwn(product.sizes, size) || !aspect || (orientation === 'landscape' && isSquareAspect(aspect))) throw badSelection(); |
| 98 | const frameNames: readonly string[] = product.availableFrames; |
| 99 | if (!frameNames.length ? frame !== 'none' : !frameNames.includes(frame)) throw badSelection(); |
| 100 | let matte: string | undefined; |
| 101 | let edge: string | undefined; |
| 102 | if ('availableMattes' in product) { |
| 103 | const choices: readonly string[] = product.availableMattes; |
| 104 | if (typeof matteId !== 'string' || !choices.includes(matteId)) throw badSelection(); |
| 105 | matte = matteId; |
| 106 | } else if (matteId !== undefined) throw badSelection(); |
| 107 | if ('availableWraps' in product) { |
| 108 | const choices: readonly string[] = product.availableWraps; |
| 109 | if (typeof wrap !== 'string' || !choices.includes(wrap)) throw badSelection(); |
| 110 | edge = wrap; |
| 111 | } else if (wrap !== undefined) throw badSelection(); |
| 112 | return { |
| 113 | productId: id, size, orientation, frame, |
| 114 | ...(matte === undefined ? {} : { matteId: matte }), |
| 115 | ...(edge === undefined ? {} : { wrap: edge }), |
| 116 | }; |
| 117 | } |
| 118 | |
| 119 | export function printConfigSha256(selection: PrintSelection): string { |
| 120 | const { productId, size, orientation, frame, matteId, wrap } = selection; |
| 121 | return hash(JSON.stringify([productId, size, orientation, frame, matteId ?? null, wrap ?? null])); |
| 122 | } |
| 123 | |
| 124 | function hash(data: string | Uint8Array) { return createHash('sha256').update(data).digest('hex'); } |
| 125 | function sign(domain: string, value: string) { |
| 126 | return createHmac('sha256', secret()).update(domain).update('\0').update(value).digest('hex'); |
| 127 | } |
| 128 | function safeEqual(a: string, b: string) { |
| 129 | if (!HEX.test(a) || !HEX.test(b)) return false; |
| 130 | return timingSafeEqual(Buffer.from(a, 'hex'), Buffer.from(b, 'hex')); |
| 131 | } |
| 132 | |
| 133 | export async function readPrintForm(req: Request, fields: string[]) { |
| 134 | const contentType = req.headers.get('content-type') ?? ''; |
| 135 | if (!/^multipart\/form-data;\s*boundary=/i.test(contentType)) { |
| 136 | throw new StudioError('invalid_request', 415, 'Send the print request as a multipart form.'); |
| 137 | } |
| 138 | const large = new StudioError('upload_too_large', 413, 'Choose a JPG or PNG print file under 6 MB.'); |
| 139 | const length = req.headers.get('content-length'); |
| 140 | if (length && (!/^\d+$/.test(length) || Number(length) > MAX_REQUEST_BYTES)) throw large; |
| 141 | const bytes = await boundedBody(req.body, MAX_REQUEST_BYTES, large); |
| 142 | let form: FormData; |
| 143 | try { form = await new Response(bytes, { headers: { 'content-type': contentType } }).formData(); } |
| 144 | catch { throw new StudioError('invalid_request', 400, 'The print form could not be read.'); } |
| 145 | if ([...form.keys()].some(key => !fields.includes(key) || form.getAll(key).length !== 1)) { |
| 146 | throw new StudioError('invalid_request', 400, 'The print form contains unsupported fields.'); |
| 147 | } |
| 148 | return form; |
| 149 | } |
| 150 | |
| 151 | export async function printArtwork(value: FormDataEntryValue | null, selection: PrintSelection): Promise<PrintArtwork> { |
| 152 | const badImage = () => new StudioError('invalid_image', 400, 'Choose a valid, non-animated JPG or PNG print file under 6 MB.'); |
| 153 | try { |
| 154 | if (!value || typeof value === 'string') throw badImage(); |
| 155 | const bytes = await rawUpload(value); |
| 156 | const mime = imageMime(bytes); |
| 157 | if (mime !== 'image/jpeg' && mime !== 'image/png') throw badImage(); |
| 158 | // APNG animation and EXIF rotation can disagree between the browser and |
| 159 | // fulfillment decoder. Require a flattened, upright export without EXIF. |
| 160 | if (mime === 'image/png' && hasUnsafePngChunks(bytes)) throw badImage(); |
| 161 | if (mime === 'image/jpeg' && hasJpegExif(bytes)) throw badImage(); |
| 162 | const { width, height } = await imageDimensions(bytes); |
| 163 | if (!width || !height || width * height > MAX_PIXELS || width > 10000 || height > 10000) throw badImage(); |
| 164 | const [aspectWidth, aspectHeight] = frameAspect(selection.productId, selection.size, selection.orientation)!.split('/').map(Number); |
| 165 | if (Math.abs((width / height) / (aspectWidth / aspectHeight) - 1) > 0.01) { |
| 166 | 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.'); |
| 167 | } |
| 168 | const inches = selection.size.split('x').map(Number); |
| 169 | if (selection.orientation === 'landscape') inches.reverse(); |
| 170 | if (width / inches[0] < 120 || height / inches[1] < 120) { |
| 171 | throw new StudioError('print_resolution', 400, 'The artwork is too small for this print. Choose a smaller print or export a higher-resolution file.'); |
| 172 | } |
| 173 | return { bytes, mime, width, height, sha256: hash(bytes) }; |
| 174 | } catch (error) { |
| 175 | if (error instanceof StudioError) throw error; |
| 176 | throw badImage(); |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | // Walk complete PNG chunks; do not confuse image data with metadata markers. |
| 181 | function hasUnsafePngChunks(bytes: Buffer) { |
| 182 | let offset = 8; |
| 183 | let ihdr = false; |
| 184 | let data = false; |
| 185 | while (offset + 12 <= bytes.length) { |
| 186 | const len = bytes.readUInt32BE(offset); |
| 187 | if (len > bytes.length - offset - 12) return true; |
| 188 | const name = bytes.toString('ascii', offset + 4, offset + 8); |
| 189 | if (name === 'IHDR') ihdr = offset === 8 && len === 13; |
| 190 | if (name === 'IDAT') data = true; |
| 191 | if (name === 'acTL' || name === 'fcTL' || name === 'fdAT' || name === 'eXIf') return true; |
| 192 | offset += len + 12; |
| 193 | if (name === 'IEND') return !(ihdr && data && len === 0 && offset === bytes.length); |
| 194 | } |
| 195 | return true; |
| 196 | } |
| 197 | function hasJpegExif(bytes: Buffer) { |
| 198 | let offset = 2; |
| 199 | while (offset + 1 < bytes.length) { |
| 200 | if (bytes[offset++] !== 0xff) return true; |
| 201 | while (bytes[offset] === 0xff) offset++; |
| 202 | const marker = bytes[offset++]; |
| 203 | if (marker === 0xda) return false; |
| 204 | if (marker === 0xd9 || offset + 2 > bytes.length) return true; |
| 205 | const length = bytes.readUInt16BE(offset); |
| 206 | if (length < 2 || offset + length > bytes.length) return true; |
| 207 | if (marker === 0xe1 && bytes.toString('ascii', offset + 2, offset + 8) === 'Exif\0\0') return true; |
| 208 | offset += length; |
| 209 | } |
| 210 | return true; |
| 211 | } |
| 212 | |
| 213 | export function createPrintQuote(user: string, selection: PrintSelection, image: PrintArtwork) { |
| 214 | const quote: Quote = { |
| 215 | version: 1, user, orderId: generateOrderId(), generationId: crypto.randomUUID(), |
| 216 | amountCents: priceCents(selection.productId, selection.size, selection.matteId), |
| 217 | selection, configSha256: printConfigSha256(selection), artworkSha256: image.sha256, |
| 218 | mime: image.mime, expiresAt: Date.now() + QUOTE_TTL_MS, shippingCountry: PRINT_SHIPPING_COUNTRY, |
| 219 | }; |
| 220 | const payload = Buffer.from(JSON.stringify(quote)).toString('base64url'); |
| 221 | const quoteToken = payload + '.' + sign('quote', payload); |
| 222 | return { quoteToken, amountCents: quote.amountCents, currency: 'USD', selection, |
| 223 | width: image.width, height: image.height, artworkSha256: image.sha256, |
| 224 | expiresAt: quote.expiresAt, shippingCountry: quote.shippingCountry }; |
| 225 | } |
| 226 | |
| 227 | export function verifyPrintQuote(entry: FormDataEntryValue | null, user: string): Quote { |
| 228 | const stale = () => new StudioError('quote_expired', 409, 'Review the current print quote again before paying.'); |
| 229 | if (typeof entry !== 'string' || entry.length > 4096 || !/^[A-Za-z0-9_-]+\.[a-f0-9]{64}$/.test(entry)) throw stale(); |
| 230 | const [payload, signature] = entry.split('.'); |
| 231 | if (!safeEqual(signature, sign('quote', payload))) throw stale(); |
| 232 | let quote: Quote; |
| 233 | try { quote = JSON.parse(Buffer.from(payload, 'base64url').toString()) as Quote; } |
| 234 | catch { throw stale(); } |
| 235 | if (quote?.version !== 1 || quote.user !== user || !ORDER_ID.test(quote.orderId) || !UUID.test(quote.generationId) |
| 236 | || !HEX.test(quote.artworkSha256) || !HEX.test(quote.configSha256) || quote.shippingCountry !== PRINT_SHIPPING_COUNTRY |
| 237 | || !Number.isSafeInteger(quote.expiresAt) || quote.expiresAt <= Date.now() || quote.expiresAt > Date.now() + QUOTE_TTL_MS |
| 238 | || (quote.mime !== 'image/jpeg' && quote.mime !== 'image/png')) throw stale(); |
| 239 | const selection = parsePrintSelection(quote.selection); |
| 240 | if (quote.configSha256 !== printConfigSha256(selection) |
| 241 | || quote.amountCents !== priceCents(selection.productId, selection.size, selection.matteId)) throw stale(); |
| 242 | return { ...quote, selection }; |
| 243 | } |
| 244 | |
| 245 | export function approvePrint(quote: Quote): PrintApproval { |
| 246 | return { |
| 247 | version: 1, generationId: quote.generationId, amountCents: quote.amountCents, artworkSha256: quote.artworkSha256, |
| 248 | configSha256: quote.configSha256, cleanUrl: printAssetURL(quote.orderId, quote.artworkSha256), |
| 249 | approvedAt: new Date().toISOString(), shippingCountry: quote.shippingCountry, artworkMime: quote.mime, |
| 250 | }; |
| 251 | } |
| 252 | |
| 253 | export function printAssetKey(orderId: string, artworkSha256: string) { |
| 254 | if (!ORDER_ID.test(orderId) || !HEX.test(artworkSha256)) throw new Error('Invalid print asset identity.'); |
| 255 | return `studio-print/v1/${orderId}/${artworkSha256}`; |
| 256 | } |
| 257 | export function printAssetURL(orderId: string, artworkSha256: string) { |
| 258 | const key = printAssetKey(orderId, artworkSha256); |
| 259 | return new URL(`/api/studio/print/asset/${orderId}?key=${artworkSha256}.${sign('asset', key)}`, authOrigin()).href; |
| 260 | } |
| 261 | export function printAssetMatches(url: string, orderId: string, artworkSha256: string) { |
| 262 | try { return url === printAssetURL(orderId, artworkSha256); } catch { return false; } |
| 263 | } |
| 264 | export function printAssetRequestMatches(url: string, orderId: string) { |
| 265 | try { |
| 266 | const key = new URL(url).searchParams.get('key'); |
| 267 | if (!key || !/^[a-f0-9]{64}\.[a-f0-9]{64}$/.test(key)) return false; |
| 268 | return printAssetMatches(url, orderId, key.split('.')[0]); |
| 269 | } catch { return false; } |
| 270 | } |
| 271 | export function validPrintOrder(id: string) { return ORDER_ID.test(id); } |