Lumen & Gesso / website · lumengesso.com / app / api / studio / print / smoke.test.cjs
| 1 | // Run from project root: node app/api/studio/print/smoke.test.cjs |
| 2 | // Simulated customers, SQLite/D1, private R2 objects, and Stripe only. |
| 3 | const { createRequire } = require('node:module'); |
| 4 | const { DatabaseSync } = require('node:sqlite'); |
| 5 | const { readFileSync } = require('node:fs'); |
| 6 | const { strict: assert } = require('node:assert'); |
| 7 | const Module = require('node:module'); |
| 8 | const path = require('node:path'); |
| 9 | const root = path.resolve(__dirname, '../../../..'); |
| 10 | const backend = createRequire(path.join(root, 'package.json')); |
| 11 | const sharp = backend('sharp'); |
| 12 | const sql = new DatabaseSync(':memory:'); |
| 13 | sql.exec(readFileSync(path.join(root, 'd1/migrations/0001_commerce.sql'),'utf8')); |
| 14 | const sha = data => backend('node:crypto').createHash('sha256').update(data).digest('hex'); |
| 15 | const orders = new Map(); |
| 16 | const files = new Map(); |
| 17 | let stripeCalls = 0; |
| 18 | const d1 = { prepare(query) { return {bind(...parameters) { |
| 19 | const statement = sql.prepare(query); |
| 20 | const args = /\?\d/.test(query) |
| 21 | ? [Object.fromEntries(parameters.map((value, i) => [String(i + 1), value]))] : parameters; |
| 22 | return { |
| 23 | first: async () => statement.get(...args) ?? null, |
| 24 | all: async () => ({results: /\bselect\b/i.test(query) || /\breturning\b/i.test(query) |
| 25 | ? statement.all(...args) |
| 26 | : (statement.run(...args), []) }), |
| 27 | }; |
| 28 | }}; }}; |
| 29 | const bucket = { |
| 30 | async put(key, body, opts) { files.set(key, {body: Buffer.from(body), opts}); }, |
| 31 | async get(key) { |
| 32 | const value = files.get(key); |
| 33 | return value ? {body:new Response(new Uint8Array(value.body)).body} : null; |
| 34 | }, |
| 35 | }; |
| 36 | const resources = { COMMERCE_DB: d1, REVIEW_PHOTOS: bucket, EMAIL: {send: async () => {}} }; |
| 37 | const auth = { |
| 38 | authOrigin: () => 'https://lumengesso.test', |
| 39 | getCustomerUser: async () => global.user, |
| 40 | }; |
| 41 | const stripe = () => ({checkout:{sessions:{ |
| 42 | async create(params, options) { |
| 43 | stripeCalls++; |
| 44 | assert.equal(params.client_reference_id, params.metadata.orderId); |
| 45 | assert.equal(params.line_items[0].quantity, 1); |
| 46 | assert.equal(params.line_items[0].price_data.unit_amount, 5800); |
| 47 | assert.equal(params.line_items[0].price_data.currency, 'usd'); |
| 48 | assert.equal(params.adaptive_pricing.enabled, false); |
| 49 | assert.deepEqual(params.shipping_address_collection.allowed_countries,['US']); |
| 50 | assert.equal(params.automatic_tax.enabled,true); |
| 51 | assert.equal(options.idempotencyKey,'lumen-print-checkout-v1-' + params.metadata.orderId); |
| 52 | const saved = { |
| 53 | ...params,id:'cs_test_' + params.metadata.orderId, status:'open', |
| 54 | currency:'usd',amount_subtotal:5800, |
| 55 | url:'https://checkout.stripe.com/c/pay/' + params.metadata.orderId, |
| 56 | }; |
| 57 | orders.set(saved.id,saved); |
| 58 | return saved; |
| 59 | }, |
| 60 | async retrieve(id) { return orders.get(id); }, |
| 61 | }}}); |
| 62 | const selection = {productId:'classic',size:'8x8',orientation:'portrait',frame:'black',matteId:'nomat'}; |
| 63 | function request(action, bytes, extras = {}, origin = auth.authOrigin()) { |
| 64 | const form = new FormData(); |
| 65 | if (bytes) form.set('image',new Blob([bytes], {type:'image/png'}),'artwork.png'); |
| 66 | for (const [key,value] of Object.entries(extras)) form.set(key,value); |
| 67 | return new Request(auth.authOrigin()+'/api/studio/print/'+action, {method:'POST',body:form,headers:{origin}}); |
| 68 | } |
| 69 | (async () => { |
| 70 | const bundle = await backend('esbuild').build({ |
| 71 | stdin:{contents:"export { GET as support, POST as quote } from './app/api/studio/print/quote/route'; export { POST as checkout } from './app/api/studio/print/checkout/route'; export { GET as asset } from './app/api/studio/print/asset/[id]/route'; export { readPrintArtworkForOrder } from './app/api/studio/print/persistence';",resolveDir:root,loader:'ts'}, |
| 72 | absWorkingDir:root,write:false,bundle:true,platform:'node',format:'cjs', |
| 73 | external:['server-only','@opennextjs/cloudflare','@/app/lib/lumen-auth','@/app/lib/stripe','sharp'], |
| 74 | }); |
| 75 | const filename = path.join(root,'.print-route-smoke.cjs'); |
| 76 | const m = new Module(filename,module); |
| 77 | const oldLoad = Module._load; |
| 78 | Module._load = function(specifier, parent, isMain) { |
| 79 | if (specifier === 'server-only') return {}; |
| 80 | if (specifier === '@opennextjs/cloudflare') return {getCloudflareContext:()=>({env:resources})}; |
| 81 | if (specifier === '@/app/lib/lumen-auth') return auth; |
| 82 | if (specifier === '@/app/lib/stripe') return {stripe}; |
| 83 | if (specifier === 'sharp') return sharp; |
| 84 | return oldLoad.apply(this,arguments); |
| 85 | }; |
| 86 | m._compile(bundle.outputFiles[0].text, filename); |
| 87 | const {support,quote,checkout,asset,readPrintArtworkForOrder} = m.exports; |
| 88 | delete process.env.CLOUDFLARE_DEPLOYMENT_ENV; |
| 89 | delete process.env.LUMEN_SELF_SERVICE_PRINT_ENABLED; |
| 90 | global.user={id:'test-customer',email:'creative@example.invalid'}; |
| 91 | assert.deepEqual(await (await support()).json(),{enabled:false,signedIn:true,signupAvailable:false}); |
| 92 | assert.equal((await quote(request('quote'))).status,503); |
| 93 | assert.equal(stripeCalls,0); |
| 94 | Object.assign(process.env,{ |
| 95 | LUMEN_SELF_SERVICE_PRINT_ENABLED:'true', |
| 96 | LUMEN_SELF_SERVICE_PRINT_SECRET:'isolated-fake-print-secret-at-least-32-chars', |
| 97 | LUMEN_STUDIO_AUTH_DAILY_SENDS:'5', |
| 98 | LUMEN_STUDIO_AUTH_IP_DAILY_SENDS:'2', |
| 99 | LUMEN_STUDIO_AUTH_TOTAL_SENDS:'5', |
| 100 | LUMENGESSO_BETTER_AUTH_SECRET:'isolated-fake-better-auth-secret-at-least-32-chars', |
| 101 | STRIPE_SECRET_KEY:'sk_test_fake', |
| 102 | STRIPE_WEBHOOK_SECRET:'whsec_fake', |
| 103 | PRODIGI_API_BASE_URL:'https://api.sandbox.prodigi.com/v4.0/', |
| 104 | PRODIGI_API_KEY_SANDBOX:'fake', |
| 105 | PRODIGI_WEBHOOK_TOKEN:'fake_test_token_1234', |
| 106 | }); |
| 107 | assert.equal((await (await support()).json()).enabled,true); |
| 108 | assert.equal((await (await support()).json()).signupAvailable,true); |
| 109 | process.env.PRODIGI_API_BASE_URL='https://api.prodigi.com/v4.0/'; |
| 110 | assert.equal((await (await support()).json()).enabled,false); |
| 111 | process.env.PRODIGI_API_BASE_URL='https://api.sandbox.prodigi.com/v4.0/'; |
| 112 | global.user=null; |
| 113 | assert.equal((await quote(request('quote'))).status,401); |
| 114 | global.user={id:'test-customer',email:'creative@example.invalid'}; |
| 115 | assert.equal((await quote(request('quote',null,{},'https://foreign.test'))).status,403); |
| 116 | const rgba=(width,height,background)=>sharp({create:{width,height,channels:3,background}}).png().toBuffer(); |
| 117 | const valid=await rgba(1024,1024,'#fff'); |
| 118 | const mismatch=await rgba(1024,1024,'#111'); |
| 119 | const small=await rgba(500,500,'#555'); |
| 120 | const wrongRatio=await rgba(1024,1200,'#888'); |
| 121 | for (const [bytes,code] of [[small,'print_resolution'],[wrongRatio,'print_aspect']]) { |
| 122 | const res=await quote(request('quote',bytes,{selection:JSON.stringify(selection)})); |
| 123 | assert.equal(res.status,400); |
| 124 | assert.equal((await res.json()).code,code); |
| 125 | } |
| 126 | const quoteResponse=await quote(request('quote',valid,{selection:JSON.stringify(selection)})); |
| 127 | assert.equal(quoteResponse.status,200,await quoteResponse.clone().text()); |
| 128 | const quoted=await quoteResponse.json(); |
| 129 | assert.equal(quoted.artworkSha256,sha(valid)); |
| 130 | assert.equal(quoted.amountCents,5800); |
| 131 | assert.equal(files.size,0); |
| 132 | assert.equal(sql.prepare('SELECT count(*) AS n FROM orders').get().n,0); |
| 133 | const body={approved:'true',termsAccepted:'true',quoteToken:quoted.quoteToken}; |
| 134 | assert.equal((await checkout(request('checkout',valid,{...body,approved:'false'}))).status,400); |
| 135 | assert.equal((await checkout(request('checkout',mismatch,body))).status,409); |
| 136 | const savedUser=global.user; |
| 137 | global.user={id:'other-customer',email:'other@example.invalid'}; |
| 138 | assert.equal((await checkout(request('checkout',valid,body))).status,409); |
| 139 | global.user=savedUser; |
| 140 | assert.equal(stripeCalls,0); |
| 141 | const response=await checkout(request('checkout',valid,body)); |
| 142 | assert.equal(response.status,200,await response.clone().text()); |
| 143 | const {orderId,url}=await response.json(); |
| 144 | assert.match(url,/^https:\/\/checkout\.stripe\.com\//); |
| 145 | assert.equal(stripeCalls,1); |
| 146 | const record=sql.prepare('SELECT * FROM orders WHERE id=?').get(orderId); |
| 147 | const approval=JSON.parse(record.config).selfServicePrint; |
| 148 | assert.equal(approval.amountCents,5800); |
| 149 | assert.equal(record.current_generation_id,approval.generationId); |
| 150 | assert.equal(record.stripe_session_id,'cs_test_'+orderId); |
| 151 | assert.equal(files.size,1); |
| 152 | assert.equal(sha(await readPrintArtworkForOrder(orderId,quoted.artworkSha256)),sha(valid)); |
| 153 | const idCtx={params:Promise.resolve({id:orderId})}; |
| 154 | assert.equal((await asset(new Request(approval.cleanUrl),idCtx)).status,404); |
| 155 | assert.equal((await asset(new Request(approval.cleanUrl+'x'),idCtx)).status,404); |
| 156 | const retry=await checkout(request('checkout',valid,body)); |
| 157 | assert.equal(retry.status,200); |
| 158 | assert.deepEqual(await retry.json(),{orderId,url}); |
| 159 | assert.equal(stripeCalls,1); |
| 160 | sql.prepare("UPDATE orders SET stripe_payment_intent_id='pi_test_approved' WHERE id=?").run(orderId); |
| 161 | delete process.env.LUMEN_SELF_SERVICE_PRINT_ENABLED; |
| 162 | const approved=await asset(new Request(approval.cleanUrl),idCtx); |
| 163 | assert.equal(approved.status,200); |
| 164 | assert.equal(sha(Buffer.from(await approved.arrayBuffer())),sha(valid)); |
| 165 | sql.prepare("UPDATE orders SET status='cancelled' WHERE id=?").run(orderId); |
| 166 | assert.equal((await asset(new Request(approval.cleanUrl),idCtx)).status,404); |
| 167 | Module._load=oldLoad; |
| 168 | console.log('PASS default-off/mode-paired readiness, sign-in and origin; inspect-only quote, size and ratio rejection; exact customer approval, cross-account and tamper rejection, one Stripe session on replay, paid-only private immutable print retrieval.'); |
| 169 | })().catch(error=>{console.error(error);process.exitCode=1;}); |