end to end app store screenshot creation using AI
TypeScript agentic-aiappleappstoreautomateclaudecursordesigngenerateiosios-appmarketingscreenshotskillsskills-shswiftswiftuiui
Fix UI, persistence, upload, and export bugs from full bug bash
Parth Jadhav8bd752043f33
diff --git a/BUG_BASH.md b/BUG_BASH.mdnew file mode 100644index 0000000..0acff5e--- /dev/null+++ b/BUG_BASH.md@@ -0,0 +1,39 @@+# Bug bash — 2026-09-29++Covered the editor UI, canvas interactions, persistence, uploads, exports, local APIs, and the documented project migration. Tests ran against disposable project copies in Google Chrome, including a production `next start` server. Existing project files and `promo/` were left untouched.++## Fixed findings++| Reproduction / failure | Fix |+| --- | --- |+| Open two editor tabs and save different changes; a stale tab can replace newer work. | Revision-based conditional saves, serialized compare/write, and a visible conflict message. |+| A save fails, or the page closes before the debounce completes. | Explicit retry, bounded requests, and an unsaved-changes warning. Newer queued edits retain the revision returned by an older in-flight save. |+| Upload truncated PNG/JPEG data with valid magic bytes, malformed base64, or truncated font containers. | Full image decoding, strict base64, font container bounds, and browser font decoding before import. |+| Send oversized or chunked request bodies, malformed project elements, duplicate IDs, or unsupported schemas. | Streaming body limits and stronger project validation before any write. |+| An upload is rejected by the API, but the picker installs the same image as an inline fallback. | Explicit rejections preserve the previous screenshot and display the error. |+| Two imports complete out of order, or an image's dimensions arrive after a replacement. | Request generation checks prevent stale results replacing newer choices. |+| Upload assets after starting a production server; the upload succeeds but the URL returns 404. | Runtime image/font serving routes preserve existing URLs and restrict filenames/extensions. Writes are atomic. |+| A corrupt image returns HTTP 200, or an asset request never completes. | Decode checks, bounded preloading, visible failures, and retry during export. |+| PNG workers throw, cannot deserialize messages, or never respond. | Retire failed workers and finish encoding inline. |+| One screen's PNG encoding rejects while the previous screen is still encoding. | Attach rejection handlers immediately to prevent uncaught errors and incomplete accounting. |+| An imported font never finishes loading during export. | Bounded font loading releases the editor with an actionable error. |+| Narrow viewports shrink the canvas to an unusable strip. | Scrollable stacked panels and a usable canvas height below the desktop breakpoint. Verified at 320, 390, 820, 1024, and 1440 px. |+| Duplicate/delete controls disappear on touch tablets. | Keep slide actions visible without hover. |+| Press Escape while editing an overlay's font size; the canceled value still applies. | Cancel the draft before blur can commit it. |+| Leave the two-device layout and return; the secondary screenshot is lost. | Preserve the chosen secondary screenshot across layout switches. |+| Pan at the default zoom, then click Fit active screen; nothing happens. | Explicitly recenter even when the zoom value does not change. |+| Keyboard focus reaches an image but its inspector stays closed. | Focusing the rotation control selects its element. Added accessible names to related inspector fields. |+| A notification covers Undo; changing fade direction resets a strength of zero. | Move notifications away from toolbar controls and preserve zero fade strength. |+| Run the documented migration on null or duplicate overlays. | Sanitize legacy values and ensure unique overlay IDs without dereferencing null. |++## Verification++- `scripts/bug-bash.cjs`: 35 browser regression groups. Covers real image/font upload → reload → export, concurrent tabs, failure injection, exported PNG dimensions for every device, locale output, connected crops, RTL, history, reset, and export locking.+- `scripts/ui-bug-bash.cjs`: 12 UI interaction groups, including 67 device/layout/orientation combinations; pointer drag/resize, keyboard reorder, rotation, layers, deletion/undo, empty states, backgrounds, themes/fonts, responsive widths, and touch controls.+- `scripts/api-bug-bash.cjs`: 9 API regression groups, including concurrent saves/uploads, origin/content-type checks, chunked limits, asset traversal rejection, real PNG/JPEG/WOFF2 round-trips, and execution of the documented migration.+- Production build (including TypeScript checking) and `git diff --check` passed.+- Reproduction commands are in [CONTRIBUTING.md](CONTRIBUTING.md). Run against a disposable copy; API and upload checks write its project/assets.++## Scope limits++This is a broad regression pass, not proof that every possible failure is eliminated. Browser coverage is Google Chrome; touch checks use Chrome emulation. The local API still assumes one server process. CLI callers that omit `If-Match` retain unconditional replacement behavior. Font API validation checks container structure; full font decoding is additionally checked by the editor's browser.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 73b3bc7..733918f 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -43,10 +43,14 @@ The editor regression harness is `scripts/bug-bash.cjs`. Run it against a **disp```bashPLAYWRIGHT_MODULE=/absolute/path/to/playwright node scripts/bug-bash.cjs http://localhost:3098+PLAYWRIGHT_MODULE=/absolute/path/to/playwright node scripts/ui-bug-bash.cjs http://localhost:3098+node scripts/api-bug-bash.cjs http://localhost:3098```Use an existing Playwright installation or install it outside the repo for this harness. Also run `tsc --noEmit` and the production build in the template. Use the manual checklist below for skill/scaffolding changes.+The API harness checks validation, same-origin writes, concurrent save conflicts, bounded request bodies, and real PNG/JPEG/WOFF2 uploads. Run the harnesses sequentially: the API and export harnesses write the disposable server's project file. The browser harness also covers failed-save recovery, corrupt assets, stalled workers, and narrow screens. The UI harness exercises pointer drag/resize, rotation, layers, keyboard reordering, empty states, themes/fonts, touch controls, responsive layouts, and every device/layout combination. Set `BUG_BASH_FILTER` to run a single browser check by name. Repeat the API and upload/export checks against `next start` to catch production-only asset-serving failures.+### For README-only changes- Confirm installation instructions still make sensediff --git a/README.md b/README.mdindex 53480c8..db87b3f 100644--- a/README.md+++ b/README.md@@ -28,7 +28,7 @@ Example screenshots generated with this skill were accepted for [Bloom Coffee Sh- **Theme picker** - switch palette presets from the toolbar, including one preset per named style.- **Platform switcher** - iOS, Mac, and Android tabs keep every deck side by side while sharing the same editor workflow.- **Device selector** - iPhone, iPad, Apple TV, Apple Watch, and CarPlay under iOS; Android phone, Android tablets, and the feature graphic under Android. The Mac tab is a single 16:10 Mac deck.-- **Autosave** - writes to disk through `/api/project` and mirrors to `localStorage` for instant reloads.+- **Autosave** - writes to disk through `/api/project`, mirrors to `localStorage`, and detects newer disk revisions before overwriting work from another tab or agent. Failed saves can be retried; unsaved edits trigger a warning before leaving.- **Export bundle** - downloads a zip organized by platform, device, resolution, and locale.Tip: when capturing source iPhone screenshots, the 6.1-inch simulator is usually the easiest starting point because it reduces manual image adjustment inside the frames.@@ -270,7 +270,7 @@ For headlines, `skills/app-store-screenshots/copy-ideas.md` has formulas per sli## Requirements-- Node.js 18++- Node.js 20.9+- One of bun, pnpm, yarn, or npm## Contributingdiff --git a/scripts/api-bug-bash.cjs b/scripts/api-bug-bash.cjsnew file mode 100644index 0000000..062276c--- /dev/null+++ b/scripts/api-bug-bash.cjs@@ -0,0 +1,137 @@+// Run only against a disposable template copy; this writes projects and assets.+// node scripts/api-bug-bash.cjs http://localhost:3098+const assert = require('node:assert/strict');+const sharp = require('../skills/app-store-screenshots/template/node_modules/sharp');+const fs = require('node:fs/promises');+const os = require('node:os');+const path = require('node:path');+const {execFileSync} = require('node:child_process');+const {randomBytes} = require('node:crypto');+const base = process.argv[2] || 'http://localhost:3098';+const projectURL = base + '/api/project';+const post = (route, data, headers = {}) => fetch(base + route, {+ method: 'POST', headers: {'content-type': 'application/json', ...headers}, body: JSON.stringify(data),+});+let passed = 0;+async function check(name, run) { await run(); console.log('PASS', name); passed++; }+(async () => {+ const initial = await fetch(projectURL);+ assert.equal(initial.status, 200);+ const {state: original} = await initial.json();+ assert.ok(original, 'Start with a disposable template project');+ try {+ await check('invalid project shapes are rejected without replacing the file', async () => {+ const slide = {id:'a', layout:'no-device', screenshot:'', label:{en:'Test'}, headline:{en:'Test'}};+ const rect = {x:0,y:0,width:10,height:10};+ const invalid = [null, [], {}, {...original,schemaVersion:999}, {...original,connectedCanvas:'false'},+ {...original,slidesByDevice:{typo:[]}}, {...original,locales:['en','en']},+ ...[{headline:{en:[]}}, {transforms:{caption:{...rect,width:-1}}}, {textElements:[null]},+ {imageElements:[{id:'x',src:'a',transform:rect},{id:'x',src:'b',transform:rect}]}]+ .map(patch => ({...original, slidesByDevice:{watchos:[{...slide,...patch}]}}))];+ for (const state of invalid) assert.equal((await post('/api/project',state)).status,400);+ assert.deepEqual((await (await fetch(projectURL)).json()).state, original);+ });+ await check('every write route requires exact JSON content type and same origin', async () => {+ for (const route of ['/api/project','/api/upload','/api/upload-font']) {+ for (const type of ['text/plain','application/json-invalid']) assert.equal((await post(route,{}, {'content-type':type})).status,415);+ for (const origin of ['null','https://evil.example','http://localhost:9999']) assert.equal((await post(route,{}, {origin})).status,403);+ assert.equal((await post(route,{}, {'sec-fetch-site':'cross-site'})).status,403);+ }+ for (const host of ['localhost','127.0.0.1']) {+ const url = new URL(projectURL); url.hostname = host;+ const response = await fetch(url, {method:'POST',headers:{'content-type':'application/json',origin:url.origin,'sec-fetch-site':'same-origin'},body:JSON.stringify(original)});+ assert.equal(response.status,200,host);+ }+ });+ await check('concurrent stale project writes conflict and preserve the winning state', async () => {+ const revision = (await fetch(projectURL)).headers.get('etag');+ assert.ok(revision);+ const candidates = ['tab A','tab B'].map(appName=>({...original,appName}));+ const responses = await Promise.all(candidates.map(data=>post('/api/project',data,{'if-match':revision})));+ assert.deepEqual(responses.map(r=>r.status).sort(),[200,412]);+ const winning = responses.findIndex(r=>r.status===200);+ const current = await fetch(projectURL);+ assert.deepEqual((await current.json()).state,candidates[winning]);+ assert.equal(current.headers.get('etag'),responses[winning].headers.get('etag'));+ assert.equal((await post('/api/project',original,{'if-match':revision})).status,412);+ assert.equal((await post('/api/project',original,{'if-match':current.headers.get('etag')})).status,200);+ });+ await check('truncated, forged, malformed base64 and wrong-type uploads are rejected', async () => {+ for (const data of [null, {}, {dataUrl:'data:image/png;base64,iVBORw0KGgo='}, {dataUrl:'data:image/jpeg;base64,/9j/'},+ {dataUrl:'data:image/png;base64,iVBORw0K!Ggo='}, {dataUrl:'data:text/html;base64,SGk='}]) {+ assert.equal((await post('/api/upload',data)).status,400);+ }+ for (const data of [null,{}, {data:'d09GMg=='},{data:'T1RUTw=='},{data:'AAEAAA=='},{data:'d09GRg=='}]) {+ assert.equal((await post('/api/upload-font',data)).status,400);+ }+ });+ await check('real PNG/JPEG uploads round-trip; identical concurrent uploads stay intact', async () => {+ for (const format of ['png','jpeg']) {+ // Always a new hash, so restarting next start cannot mask missing+ // runtime asset serving by indexing files from a previous test run.+ const bytes = await sharp({create:{width:24,height:30,channels:3,background:'#'+randomBytes(3).toString('hex')}})[format]().toBuffer();+ const responses = await Promise.all(Array.from({length:4},()=>post('/api/upload',{dataUrl:`data:image/${format};base64,${bytes.toString('base64')}`})));+ let path;+ for (const response of responses) {+ assert.equal(response.status,200); const result = await response.json();+ if (path) assert.equal(result.path,path); path = result.path;+ const saved = await fetch(base+path); assert.equal(saved.status,200);+ assert.deepEqual(Buffer.from(await saved.arrayBuffer()),bytes);+ }+ assert.equal((await post('/api/upload',{dataUrl:`data:image/${format==='png'?'jpeg':'png'};base64,${bytes.toString('base64')}`})).status,400);+ }+ });+ await check('oversized request bodies are rejected including chunked bodies', async () => {+ const chunk = new Uint8Array(1024*1024).fill(32);+ const response = await fetch(base+'/api/upload',{method:'POST',headers:{'content-type':'application/json'},duplex:'half',+ body:new ReadableStream({start(controller){for(let i=0;i<13;i++)controller.enqueue(chunk);controller.close();}})});+ assert.equal(response.status,413);+ });+ await check('valid WOFF2 uploads persist and truncated copies are rejected', async () => {+ const html = await (await fetch(base)).text();+ const fontPath = html.match(/\/_next\/static\/media\/[^"\s<>]+\.woff2/)?.[0];+ assert.ok(fontPath,'Expected bundled Next font');+ const bytes = Buffer.from(await (await fetch(base+fontPath)).arrayBuffer());+ // WOFF2's header version is metadata, independent of the glyph stream.+ randomBytes(4).copy(bytes,24);+ const response = await post('/api/upload-font',{data:bytes.toString('base64')});+ assert.equal(response.status,200); const {font}=await response.json();+ assert.equal(font.format,'woff2');+ assert.deepEqual(Buffer.from(await (await fetch(base+font.src)).arrayBuffer()),bytes);+ assert.equal((await post('/api/upload-font',{data:bytes.subarray(0,64).toString('base64')})).status,400);+ });+ await check('runtime asset routes reject missing files and traversal paths', async () => {+ for (const prefix of ['/screenshots/uploaded/','/fonts/imported/']) {+ for (const name of ['not-a-hash.png','0000000000000000.woff2','..%2f..%2fapp-store-screenshots.json']) {+ assert.ok([400,404].includes((await fetch(base+prefix+name)).status));+ }+ }+ });+ await check('documented migration handles null overlays and duplicate element IDs', async () => {+ const skill = await fs.readFile(path.join(__dirname,'../skills/app-store-screenshots/SKILL.md'),'utf8');+ const source = skill.match(/BACKUP_DIR="\$BACKUP_DIR" node <<'NODE'\n([\s\S]*?)\nNODE/)[1];+ const temporary = await fs.mkdtemp(path.join(os.tmpdir(),'screenshot-migration-'));+ const transform = {x:10,y:20,width:0,height:40};+ try {+ const old = {...original, schemaVersion:1, connectedCanvas:undefined, slidesByDevice:{watchos:[{+ id:'legacy', layout:'hero', label:'Label', headline:'Old headline', screenshot:'/old.png',+ textElements:[null,{id:'same',text:'Hello',transform},{id:'same',text:{en:'Copy',de:42},transform,fontSize:-3}],+ imageElements:[null,{id:'same',src:'/a.png',transform},{id:'same',src:'/b.png',transform}],+ }]}};+ await fs.writeFile(path.join(temporary,'app-store-screenshots.json'),JSON.stringify(old));+ execFileSync(process.execPath,['-e',source],{cwd:temporary,env:{...process.env,BACKUP_DIR:temporary}});+ const migrated=JSON.parse(await fs.readFile(path.join(temporary,'app-store-screenshots.json'),'utf8'));+ assert.equal(migrated.connectedCanvas,false);assert.equal(migrated.schemaVersion,2);+ const slide=migrated.slidesByDevice.watchos[0];+ assert.deepEqual(slide.headline,{en:'Old headline'});assert.equal(slide.screenshot,'/old.png');+ assert.equal(slide.textElements.length,2);assert.equal(slide.imageElements.length,2);+ assert.equal(new Set(slide.textElements.map(e=>e.id)).size,2);+ assert.equal(new Set(slide.imageElements.map(e=>e.id)).size,2);+ assert.equal((await post('/api/project',migrated)).status,200);+ } finally { await fs.rm(temporary,{recursive:true,force:true}); }+ });+ console.log(`${passed} API regression groups passed.`);+ } finally {+ assert.equal((await post('/api/project',original)).status,200,'Could not restore disposable project');+ }+})().catch(error=>{console.error(error);process.exitCode=1;});diff --git a/scripts/bug-bash.cjs b/scripts/bug-bash.cjsindex f78d425..30fbf6b 100644--- a/scripts/bug-bash.cjs+++ b/scripts/bug-bash.cjs@@ -288,6 +288,178 @@ const fixture = (extra = {}) => ({schemaVersion:2,appName:'Bug bash',themeId:'clfor(const png of pngs) assert.equal((await png.async('nodebuffer'))[25],2);await context.close();});+ await check('rejected image uploads keep the previous screenshot instead of bypassing validation',async()=>{+ const {page,latest}=await open(fixture({slidesByDevice:{watchos:[slide('upload',{layout:'hero',screenshot:'/previous.png'})]}}));+ const png=await page.evaluate(()=>{const c=document.createElement('canvas');c.width=c.height=10;return c.toDataURL().split(',')[1]});+ await page.route('**/api/upload',route=>route.fulfill({status:400,json:{ok:false,error:'Rejected image'}}));+ await page.locator('input[type=file]').last().setInputFiles({name:'test.png',mimeType:'image/png',buffer:Buffer.from(png,'base64')});+ await page.getByText('Rejected image',{exact:true}).waitFor();+ await pause(800); assert.equal(latest().slidesByDevice.watchos[0].screenshot,'/previous.png');+ await page.close();+ });+ await check('corrupt images and fonts are rejected before upload',async()=>{+ const {page,latest}=await open(fixture({slidesByDevice:{watchos:[slide('upload',{layout:'hero'})]}}));+ let uploads=0;+ await page.route('**/api/upload*',route=>{uploads++;return route.fulfill({status:400,json:{ok:false}})});+ await page.locator('input[type=file]').last().setInputFiles({name:'broken.png',mimeType:'image/png',buffer:Buffer.from('iVBORw0KGgo=','base64')});+ await page.getByText('Image is corrupt or exceeds 64 megapixels',{exact:true}).waitFor();+ await page.locator('input[type=file]').first().setInputFiles({name:'broken.woff2',mimeType:'font/woff2',buffer:Buffer.from('wOF2')});+ await page.getByText('Font import failed',{exact:true}).waitFor();+ assert.equal(uploads,0);assert.equal(latest().slidesByDevice.watchos[0].screenshot,'');+ assert.equal(await page.getByRole('button',{name:'Export bundle',exact:true}).isEnabled(),true);await page.close();+ });+ await check('HTTP 200 with corrupt image bytes blocks export',async()=>{+ const {page}=await open(fixture({slidesByDevice:{watchos:[slide('corrupt',{layout:'hero',screenshot:'/corrupt.png'})]}}));+ await page.route('**/corrupt.png',route=>route.fulfill({contentType:'image/png',body:'not an image'}));+ let downloads=0;page.on('download',()=>downloads++);+ await page.getByRole('button',{name:'Export bundle',exact:true}).click();+ await page.getByText('Export failed',{exact:true}).waitFor();+ assert.equal(downloads,0);assert.equal(await page.locator('[inert]').count(),0);await page.close();+ });+ await check('failed saves can be retried without another edit; dirty edits warn before leaving',async()=>{+ const {page}=await open();+ await pause(800);+ let failing=true,writes=0,latest;+ await page.route('**/api/project',async route=>{+ writes++;latest=route.request().postDataJSON();+ await route.fulfill({status:failing?500:200,json:{ok:!failing,error:failing?'Disk temporarily unavailable':undefined}});+ });+ await page.getByRole('textbox',{name:'App name',exact:true}).fill('Unsaved work');+ const dirty=()=>page.evaluate(()=>{const event=new Event('beforeunload',{cancelable:true});window.dispatchEvent(event);return event.defaultPrevented});+ assert.equal(await dirty(),true);+ await page.getByRole('button',{name:'Retry save',exact:true}).waitFor();+ assert.equal(await dirty(),true); failing=false;+ await page.getByRole('button',{name:'Retry save',exact:true}).click();+ await pause(900);assert.equal(writes,2);assert.equal(latest.appName,'Unsaved work');assert.equal(await dirty(),false);+ await page.close();+ });+ await check('older in-flight save advances the revision for newer queued edits',async()=>{+ const {page}=await open();await pause(800);+ const headers=[];let count=0;+ await page.route('**/api/project',async route=>{+ const n=++count;headers.push(route.request().headers()['if-match']);+ if(n===1)await pause(1600);+ await route.fulfill({headers:{etag:`"revision-${n}"`},json:{ok:true}});+ });+ await page.getByRole('textbox',{name:'App name',exact:true}).fill('older');await pause(800);+ await page.getByRole('textbox',{name:'App name',exact:true}).fill('newer');await pause(2200);+ assert.deepEqual(headers,[undefined,'"revision-1"']);await page.close();+ });+ await check('two real editor tabs cannot silently overwrite each other',async()=>{+ const original=await (await fetch(baseURL+'/api/project')).json();+ const save=state=>fetch(baseURL+'/api/project',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(state)});+ const pages=[];+ try {+ assert.equal((await save(fixture())).status,200);+ for(let i=0;i<2;i++){+ const page=await browser.newPage({viewport:{width:1600,height:1000}});pages.push(page);+ page.on('pageerror',error=>errors.push(error.message));+ await page.goto(baseURL);await page.getByRole('button',{name:'Export bundle',exact:true}).waitFor();await pause(800);+ }+ await pages[0].getByRole('textbox',{name:'App name',exact:true}).fill('Winner');await pause(900);+ await pages[1].getByRole('textbox',{name:'App name',exact:true}).fill('Keep my edits');+ await pages[1].getByText(/Project changed in another tab or on disk/).waitFor();+ assert.equal((await (await fetch(baseURL+'/api/project')).json()).state.appName,'Winner');+ assert.equal(await pages[1].getByRole('textbox',{name:'App name',exact:true}).inputValue(),'Keep my edits');+ } finally {for(const page of pages)await page.close();assert.equal((await save(original.state)).status,200);}+ });+ await check('silent and throwing PNG workers fall back instead of hanging export',async()=>{+ for(const mode of ['silent','throw']) {+ const context=await browser.newContext({viewport:{width:1600,height:1000}});+ await context.addInitScript(mode=>{window.Worker=class extends EventTarget{postMessage(){if(mode==='throw')throw new Error('cannot post')}terminate(){}}},mode);+ const page=await context.newPage();page.on('pageerror',error=>errors.push(error.message));+ await page.route('**/api/project',route=>route.fulfill({json:{ok:true,state:fixture({slidesByDevice:{watchos:[slide('one')]}})}}));+ await page.goto(baseURL);await page.getByRole('button',{name:'Export bundle',exact:true}).waitFor();+ const downloaded=page.waitForEvent('download',{timeout:45000});+ await page.getByRole('button',{name:'Export bundle',exact:true}).click();await downloaded;+ await page.getByRole('button',{name:'Export bundle',exact:true}).waitFor();assert.equal(await page.locator('[inert]').count(),0);+ await context.close();+ }+ });+ await check('a stalled asset cannot keep the editor loading forever',async()=>{+ const page=await browser.newPage({viewport:{width:1600,height:1000}});+ const state=fixture({slidesByDevice:{watchos:[slide('one',{layout:'hero',screenshot:'/stalled.png'})]}});+ page.on('pageerror',error=>errors.push(error.message));+ await page.route('**/api/project',route=>route.fulfill({json:{ok:true,state}}));+ await page.route('**/stalled.png',()=>{});+ await page.goto(baseURL,{waitUntil:'domcontentloaded'});+ await page.getByRole('button',{name:'Export bundle',exact:true}).waitFor({timeout:20000});+ await page.getByText('Image not found at /stalled.png',{exact:true}).waitFor();await page.close();+ });+ await check('a stalled font load releases export controls with an actionable error',async()=>{+ const page=await browser.newPage({viewport:{width:1600,height:1000}});+ page.on('pageerror',error=>errors.push(error.message));+ await page.addInitScript(()=>{+ document.fonts.load=()=>new Promise(()=>{});+ const original=window.setTimeout;+ window.setTimeout=(fn,delay,...args)=>original(fn,delay===15000?250:delay,...args);+ });+ const state=fixture({fontId:'self-hosted',importedFont:{src:'/fonts/imported/0123456789abcdef.woff2',format:'woff2'}});+ await page.route('**/api/project',route=>route.fulfill({json:{ok:true,state}}));+ await page.route('**/fonts/imported/**',route=>route.abort());+ await page.goto(baseURL);+ await page.getByRole('button',{name:'Export bundle',exact:true}).click();+ await page.getByText(/The screenshot font could not be loaded/).waitFor({timeout:5000});+ assert.equal(await page.locator('[inert]').count(),0);await page.close();+ });+ await check('narrow screens retain a usable canvas and scrollable inspector',async()=>{+ const {page}=await open();await page.setViewportSize({width:390,height:844});+ const main=await page.locator('main').boundingBox();assert.ok(main.height>=360);+ assert.equal(await page.locator('main').evaluate(el=>el.parentElement.scrollHeight>el.parentElement.clientHeight),true);+ await page.locator('textarea').first().fill('Mobile edit');assert.equal(await page.locator('textarea').first().inputValue(),'Mobile edit');await page.close();+ });+ await check('encoding failures are handled while a previous screen is still encoding',async()=>{+ const context=await browser.newContext({viewport:{width:1600,height:1000}});+ await context.addInitScript(()=>{+ window.CompressionStream=class{constructor(){throw new Error('encoder unavailable')}};+ window.Worker=class extends EventTarget{postMessage({id}){setTimeout(()=>this.onmessage?.({data:{id,error:'worker failed'}}),id<6?2000:0)}terminate(){}};+ });+ const page=await context.newPage();page.on('pageerror',error=>errors.push(error.message));+ await page.route('**/api/project',route=>route.fulfill({json:{ok:true,state:fixture()}}));+ await page.goto(baseURL);await page.getByRole('button',{name:'Export bundle',exact:true}).waitFor();+ let downloads=0;page.on('download',()=>downloads++);+ await page.getByRole('button',{name:'Export bundle',exact:true}).click();+ await page.getByText('All 12 renders failed',{exact:true}).waitFor();+ assert.equal(downloads,0);assert.equal(await page.locator('[inert]').count(),0);await context.close();+ });+ await check('newest font import wins when responses arrive out of order',async()=>{+ const {page,latest}=await open();+ const fontURL=await page.locator('link[as=font]').first().getAttribute('href');+ const fontBytes=await (await page.request.get(baseURL+fontURL)).body();+ let count=0;+ await page.route('**/api/upload-font',async route=>{const n=++count;await pause(n===1?1200:100);await route.fulfill({json:{ok:true,font:{src:`/fonts/imported/${n}.woff2`,format:'woff2'}}})});+ await page.locator('input[type=file]').first().setInputFiles({name:'Older.woff2',mimeType:'font/woff2',buffer:fontBytes});await pause(200);+ await page.locator('input[type=file]').first().setInputFiles({name:'Newer.woff2',mimeType:'font/woff2',buffer:fontBytes});await pause(2000);+ assert.equal(count,2);assert.equal(latest().importedFont.name,'Newer');assert.equal(latest().importedFont.src,'/fonts/imported/2.woff2');await page.close();+ });+ await check('real image and font uploads survive reload and export',async()=>{+ const original=await (await fetch(baseURL+'/api/project')).json();+ const save=state=>fetch(baseURL+'/api/project',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(state)});+ const page=await browser.newPage({viewport:{width:1600,height:1000}});+ page.on('pageerror',error=>errors.push(error.message));+ try {+ await save(fixture({slidesByDevice:{watchos:[slide('real upload',{layout:'hero'})]}}));+ await page.goto(baseURL);await page.getByRole('button',{name:'Export bundle',exact:true}).waitFor();+ const png=await page.evaluate(()=>{const c=document.createElement('canvas');c.width=80;c.height=120;const x=c.getContext('2d');x.fillStyle='#ee00aa';x.fillRect(0,0,80,120);return c.toDataURL().split(',')[1]});+ const uploaded=page.waitForResponse(r=>r.url().endsWith('/api/upload')&&r.request().method()==='POST');+ await page.locator('input[type=file]').last().setInputFiles({name:'real.png',mimeType:'image/png',buffer:Buffer.from(png,'base64')});+ assert.equal((await uploaded).status(),200);+ const fontURL=await page.locator('link[as=font]').first().getAttribute('href');+ const fontBytes=await (await page.request.get(baseURL+fontURL)).body();+ await page.locator('input[type=file]').first().setInputFiles({name:'Runtimefont.woff2',mimeType:'font/woff2',buffer:fontBytes});+ await page.getByText('Imported Runtimefont',{exact:true}).waitFor();await pause(1000);+ const disk=(await (await fetch(baseURL+'/api/project')).json()).state;+ assert.ok(disk.slidesByDevice.watchos[0].screenshot.startsWith('/screenshots/uploaded/'));+ assert.equal(disk.importedFont.name,'Runtimefont');+ await page.reload();await page.getByRole('button',{name:'Export bundle',exact:true}).waitFor();+ assert.match(await page.getByRole('combobox',{name:'Screenshot font',exact:true}).innerText(),/Runtimefont/);+ const downloaded=page.waitForEvent('download');+ await page.getByRole('button',{name:'Export bundle',exact:true}).click();+ const JSZip=require('../skills/app-store-screenshots/template/node_modules/jszip');+ const zip=await JSZip.loadAsync(await fs.readFile(await (await downloaded).path()));+ assert.equal(Object.values(zip.files).filter(f=>f.name.endsWith('.png')).length,6);+ } finally {await page.close();await save(original.state);}+ });assert.deepEqual(errors,[]);assert.ok(passed>0,'No matching checks');console.log(`${passed} browser regression checks passed in Google Chrome.`);diff --git a/scripts/ui-bug-bash.cjs b/scripts/ui-bug-bash.cjsnew file mode 100644index 0000000..71a3d2d--- /dev/null+++ b/scripts/ui-bug-bash.cjs@@ -0,0 +1,168 @@+// Interaction-focused Chrome bug bash. Uses disposable, mocked project state.+// PLAYWRIGHT_MODULE=/path/to/playwright node scripts/ui-bug-bash.cjs http://localhost:3098+const assert = require('node:assert/strict');+const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');+const baseURL = process.argv[2] || 'http://localhost:3098';+const pause = ms => new Promise(resolve=>setTimeout(resolve,ms));+const slide = (id, extra={})=>({id,layout:'no-device',label:{en:'LABEL'},headline:{en:id},screenshot:'',...extra});+const rect = {x:100,y:200,width:160,height:90,zIndex:6};+const fixture=(extra={})=>({schemaVersion:2,appName:'UI bug bash',themeId:'clean-light',connectedCanvas:true,device:'watchos',orientation:'portrait',locale:'en',locales:['en','de'],slidesByDevice:{watchos:[slide('First'),slide('Second'),slide('Third')],android:[slide('Android')],iphone:[slide('iPhone')]},...extra});+(async()=>{+ const browser=await chromium.launch({channel:'chrome',headless:true});+ const errors=[];let passed=0,failures=0;+ async function open(state=fixture(),viewport={width:1600,height:1000},options={}) {+ const page=await browser.newPage({viewport,...options});let latest=structuredClone(state);+ page.on('pageerror',error=>errors.push(error.message));+ await page.route('**/api/project',async route=>{if(route.request().method()==='POST')latest=route.request().postDataJSON();await route.fulfill({json:{ok:true,state:latest}})});+ await page.goto(baseURL);await page.getByRole('button',{name:'Export bundle',exact:true}).waitFor();+ return {page,latest:()=>latest};+ }+ async function check(name,run) {+ if(process.env.BUG_BASH_FILTER&&!name.includes(process.env.BUG_BASH_FILTER))return;+ try{await run();passed++;console.log('PASS',name)}catch(error){failures++;console.error('FAIL',name,error.message)}+ }+ try {+ await check('Escape cancels a draft text size without changing the canvas',async()=>{+ const {page,latest}=await open(fixture({slidesByDevice:{watchos:[slide('Text',{textElements:[{id:'t',text:{en:'Overlay'},fontSize:26,transform:rect}]})]}}));+ await page.locator('main [contenteditable=plaintext-only]').last().focus();+ const input=page.getByRole('spinbutton',{name:'Text size in pixels',exact:true});+ await input.fill('100');await input.press('Escape');await pause(800);+ assert.equal(latest().slidesByDevice.watchos[0].textElements[0].fontSize,26);+ await page.close();+ });+ await check('exploring layouts keeps the chosen secondary screenshot',async()=>{+ const {page,latest}=await open(fixture({slidesByDevice:{watchos:[slide('Pair',{layout:'two-devices',screenshot:'/front.png',screenshotSecondary:'/back.png'})]}}));+ const layout=page.locator('aside').last().getByRole('combobox').first();+ await layout.click();await page.getByRole('option',{name:'Hero',exact:true}).click();+ await layout.click();await page.getByRole('option',{name:'Two devices',exact:true}).click();await pause(800);+ assert.equal(latest().slidesByDevice.watchos[0].screenshotSecondary,'/back.png');await page.close();+ });+ await check('keyboard reordering preserves selection, content, and undo',async()=>{+ const {page,latest}=await open();+ await page.getByRole('button',{name:/^Screen 2/}).click();+ const handle=page.getByRole('button',{name:/^Reorder screen 2/});+ await handle.focus();await page.keyboard.press('Space');await pause(100);+ await page.keyboard.press('ArrowUp');await page.getByRole('status').filter({hasText:'over droppable area First'}).waitFor();+ await page.keyboard.press('Space');await pause(900);+ assert.deepEqual(latest().slidesByDevice.watchos.map(s=>s.id),['Second','First','Third']);+ assert.equal(await page.locator('textarea').first().inputValue(),'Second');+ await page.getByRole('button',{name:'Undo',exact:true}).click();await pause(800);+ assert.deepEqual(latest().slidesByDevice.watchos.map(s=>s.id),['First','Second','Third']);await page.close();+ });+ await check('deleting the final slide exposes a usable empty state and can be undone',async()=>{+ const {page,latest}=await open(fixture({slidesByDevice:{watchos:[slide('Only')]}}));+ await page.getByRole('button',{name:'Delete screen 1',exact:true}).click();+ await page.getByText('No screens yet',{exact:true}).waitFor();+ await page.getByRole('button',{name:'Export bundle',exact:true}).click();await page.getByText('No screens to export',{exact:true}).waitFor();+ assert.equal(await page.locator('[inert]').count(),0);+ await page.getByRole('button',{name:'Undo',exact:true}).first().click();+ assert.equal(await page.locator('textarea').first().inputValue(),'Only');+ await page.getByRole('button',{name:'Delete screen 1',exact:true}).click();await pause(600);+ await page.getByRole('button',{name:'Add screen',exact:true}).click();await pause(800);+ assert.equal(latest().slidesByDevice.watchos.length,1);assert.notEqual(latest().slidesByDevice.watchos[0].id,'Only');await page.close();+ });+ await check('custom background drafts, typography reset, and locale edits stay independent',async()=>{+ const {page,latest}=await open();const inspector=page.locator('aside').last();+ await inspector.getByRole('combobox').nth(1).click();await page.getByRole('option',{name:'Custom color',exact:true}).click();+ const hex=page.getByRole('textbox',{name:'Custom background hex color',exact:true});+ await hex.fill('#123456');await page.locator('textarea').first().click();+ await hex.fill('#12');await page.locator('textarea').first().click();assert.equal(await hex.inputValue(),'#123456');+ const slider=page.getByRole('slider',{name:'Headline size',exact:true});await slider.fill('150');+ await page.getByRole('button',{name:'Reset headline to 100%',exact:true}).click();assert.equal(await slider.inputValue(),'100');+ await page.getByRole('combobox',{name:'Locale',exact:true}).click();await page.getByRole('option',{name:'DE',exact:true}).click();+ await page.locator('textarea').first().fill('Deutsch');await pause(800);+ assert.deepEqual(latest().slidesByDevice.watchos[0].headline,{en:'First',de:'Deutsch'});+ assert.equal(latest().slidesByDevice.watchos[0].backgroundColor,'#123456');+ assert.equal(latest().slidesByDevice.watchos[0].typography,undefined);await page.close();+ });+ await check('canvas drag, resize, rotation, layer controls, delete, and undo persist',async()=>{+ const {page,latest}=await open(fixture({slidesByDevice:{watchos:[slide('Canvas')]}}));+ await page.getByRole('button',{name:'Image',exact:true}).click();await pause(700);+ const selected=page.locator('main .rnd-selected');const before={...latest().slidesByDevice.watchos[0].imageElements[0].transform};+ const box=await selected.boundingBox();const scale=box.width/before.width;+ await page.mouse.move(box.x+box.width/2,box.y+box.height/2);await page.mouse.down();await page.mouse.move(box.x+box.width/2+40,box.y+box.height/2+30,{steps:8});await page.mouse.up();await pause(750);+ const moved=latest().slidesByDevice.watchos[0].imageElements[0].transform;+ assert.ok(Math.abs(moved.x-before.x-40/scale)<2);assert.ok(Math.abs(moved.y-before.y-30/scale)<2);+ const handle=await selected.locator('div[style*="cursor: se-resize"]').boundingBox();+ await page.mouse.move(handle.x+handle.width/2,handle.y+handle.height/2);await page.mouse.down();await page.mouse.move(handle.x+handle.width/2+35,handle.y+handle.height/2+20,{steps:8});await page.mouse.up();await pause(750);+ const resized=latest().slidesByDevice.watchos[0].imageElements[0].transform;+ assert.ok(resized.width>moved.width+10);assert.ok(resized.height>moved.height+5);+ await page.getByRole('slider',{name:'Image rotation',exact:true}).fill('45');+ await page.getByRole('button',{name:'Send to back',exact:true}).click();await pause(750);+ const changed=latest().slidesByDevice.watchos[0];assert.equal(changed.imageElements[0].transform.rotation,45);+ assert.ok(changed.imageElements[0].transform.zIndex<changed.transforms.caption.zIndex);+ await page.getByRole('combobox',{name:'Image fit',exact:true}).click();await page.getByRole('option',{name:'Whole image',exact:true}).click();+ await page.getByRole('combobox',{name:'Edge fade',exact:true}).click();await page.getByRole('option',{name:'From left',exact:true}).click();+ await page.getByRole('slider',{name:'Fade strength',exact:true}).fill('65');await pause(750);+ assert.equal(latest().slidesByDevice.watchos[0].imageElements[0].fit,'contain');assert.deepEqual(latest().slidesByDevice.watchos[0].imageElements[0].fade,{edge:'left',amount:65});+ await page.getByRole('button',{name:'Delete image element',exact:true}).click();await pause(750);+ assert.equal(latest().slidesByDevice.watchos[0].imageElements,undefined);+ await page.getByRole('button',{name:'Undo',exact:true}).click();await pause(750);assert.equal(latest().slidesByDevice.watchos[0].imageElements.length,1);await page.close();+ });+ await check('all devices and layouts render and remain editable in both tablet orientations',async()=>{+ const devices=['iphone','ipad','tvos','watchos','carplay','mac','android','android-7','android-10','feature-graphic'];+ const layouts=['Hero','Device bottom','Device top','Two devices','No device','Split (landscape)'];+ for(const device of devices) {+ const {page,latest}=await open(fixture({device,slidesByDevice:{[device]:[slide('Layout',{layout:device==='feature-graphic'?'feature-graphic':'hero'})]}}));+ for(const orientation of (device==='android-7'||device==='android-10'?['portrait','landscape']:['portrait'])) {+ if(orientation==='landscape'){await page.getByRole('combobox',{name:'Orientation',exact:true}).click();await page.getByRole('option',{name:'Landscape',exact:true}).click();}+ for(const layout of (device==='feature-graphic'?['Feature graphic']:layouts)) {+ await page.getByRole('combobox',{name:'Layout',exact:true}).click();await page.getByRole('option',{name:layout,exact:true}).click();+ const headline=page.getByRole('textbox',{name:device==='feature-graphic'?'Tagline':'Headline',exact:true});+ await headline.fill(`${device} ${orientation} ${layout}`);+ const canvas=page.locator('main');assert.ok((await canvas.boundingBox()).height>0);+ await page.getByRole('button',{name:'Zoom in',exact:true}).click();await page.getByRole('button',{name:'Fit active screen',exact:true}).click();+ }+ }+ await pause(700);assert.equal(latest().device,device);assert.ok(latest().slidesByDevice[device][0].headline.en.includes(device));await page.close();+ }+ });+ await check('Fit active screen recenters a manually panned canvas at default zoom',async()=>{+ const {page}=await open();const scroller=page.locator('main .overflow-auto');await pause(400);+ await scroller.evaluate(el=>el.scrollTo({left:400,behavior:'instant'}));assert.ok(await scroller.evaluate(el=>el.scrollLeft)>100);+ await page.getByRole('button',{name:'Fit active screen',exact:true}).click();await pause(600);+ assert.ok(await scroller.evaluate(el=>el.scrollLeft)<5);await page.close();+ });+ await check('keyboard focus on an image exposes its inspector controls',async()=>{+ const {page}=await open(fixture({slidesByDevice:{watchos:[slide('Image',{imageElements:[{id:'image',src:'',transform:rect}]})]}}));+ await page.locator('main .rnd-editable').last().getByRole('button',{name:'Rotate element',exact:true}).focus();+ assert.equal(await page.getByRole('combobox',{name:'Image fit',exact:true}).count(),1);await page.close();+ });+ await check('responsive widths keep the canvas and inspector usable without page overflow',async()=>{+ const {page,latest}=await open();+ for(const width of [320,390,820,1024,1440]) {+ await page.setViewportSize({width,height:900});await pause(150);+ assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),`page overflows at ${width}px`);+ const canvas=page.locator('main');await canvas.scrollIntoViewIfNeeded();+ const box=await canvas.boundingBox();assert.ok(box.width>=280&&box.height>=250,`canvas too small at ${width}px: ${JSON.stringify(box)}`);+ const headline=page.getByRole('textbox',{name:'Headline',exact:true});await headline.fill(`Width ${width}`);+ if(process.env.BUG_BASH_ARTIFACTS)await page.screenshot({path:`${process.env.BUG_BASH_ARTIFACTS}/ui-${width}.png`,fullPage:true});+ }+ await pause(750);assert.equal(latest().slidesByDevice.watchos[0].headline.en,'Width 1440');await page.close();+ });+ await check('touch tablets expose slide actions without requiring hover',async()=>{+ const {page,latest}=await open(fixture(),{width:820,height:1180},{hasTouch:true});+ const duplicate=page.getByRole('button',{name:'Duplicate screen 1',exact:true});+ assert.ok(Number(await duplicate.locator('..').evaluate(el=>getComputedStyle(el).opacity))>0,'slide actions are invisible on touch');+ await duplicate.tap();await pause(750);assert.equal(latest().slidesByDevice.watchos.length,4);await page.close();+ });+ await check('theme and font menus apply every built-in option and preserve content',async()=>{+ const {page,latest}=await open();+ for(const label of ['Theme','Screenshot font']) {+ const menu=page.getByRole('combobox',{name:label,exact:true});await menu.click();+ const names=(await page.getByRole('option').allTextContents()).filter(name=>!name.includes('Import font'));+ await page.keyboard.press('Escape');+ for(const name of names) {+ await menu.click();await page.getByRole('option',{name,exact:true}).click();+ assert.ok((await menu.innerText()).includes(name));+ assert.equal(await page.getByRole('textbox',{name:'Headline',exact:true}).inputValue(),'First');+ }+ }+ await pause(750);assert.ok(latest().themeId);assert.ok(latest().fontId);await page.close();+ });+ assert.deepEqual(errors,[],'Uncaught browser errors');+ assert.ok(passed+failures>0,'No matching checks');+ assert.equal(failures,0,`${failures} UI checks failed`);+ console.log(`${passed} UI interaction groups passed in Google Chrome.`);+ } finally {await browser.close()}+})().catch(error=>{console.error(error);process.exitCode=1});diff --git a/skills/app-store-screenshots/SKILL.md b/skills/app-store-screenshots/SKILL.mdindex e0af800..cc6e50b 100644--- a/skills/app-store-screenshots/SKILL.md+++ b/skills/app-store-screenshots/SKILL.md@@ -157,7 +157,7 @@ const templateState =const existingState = readJson(PROJECT_FILE) || {};const hasExplicitConnectedCanvas = typeof existingState.connectedCanvas === "boolean";const existingDecks =- existingState.slidesByDevice && typeof existingState.slidesByDevice === "object"+ existingState.slidesByDevice && typeof existingState.slidesByDevice === "object" && !Array.isArray(existingState.slidesByDevice)? existingState.slidesByDevice: {};const hasExistingDecks = Object.keys(existingDecks).length > 0;@@ -181,7 +181,9 @@ if (legacySlides && !hasExistingDecks) {function localized(value) {if (typeof value === "string") return { [DEFAULT_LOCALE]: value };- if (value && typeof value === "object") return value;+ if (value && typeof value === "object" && !Array.isArray(value)) {+ return Object.fromEntries(Object.entries(value).filter(([, text]) => typeof text === "string"));+ }return {};}@@ -217,22 +219,36 @@ function migrateSlide(slide, used) {const rawTransforms = slide.transforms && typeof slide.transforms === "object" ? slide.transforms : {};for (const [id, transform] of Object.entries(rawTransforms)) {const cleaned = cleanTransform(transform);- if (cleaned) transforms[id] = cleaned;+ if (["caption", "device", "deviceSecondary"].includes(id) && cleaned) transforms[id] = cleaned;}+ const textIds = new Set();const textElements = Array.isArray(slide.textElements)? slide.textElements.map((element) => {+ if (!element || typeof element !== "object" || Array.isArray(element)) return null;const transform = cleanTransform(element.transform);- if (!element || typeof element.id !== "string" || !transform) return null;+ if (!transform) return null;return {...element,+ id: uniqueId(element.id, textIds),text: localized(element.text),transform,+ fontSize: Number.isFinite(element.fontSize) && element.fontSize > 0 ? element.fontSize : undefined,+ fontWeight: Number.isFinite(element.fontWeight) && element.fontWeight > 0 ? element.fontWeight : undefined,};}).filter(Boolean): undefined;+ const imageIds = new Set();+ const imageElements = Array.isArray(slide.imageElements)+ ? slide.imageElements.map((element) => {+ if (!element || typeof element !== "object" || Array.isArray(element) || typeof element.src !== "string") return null;+ const transform = cleanTransform(element.transform);+ return transform ? { ...element, id: uniqueId(element.id, imageIds), transform } : null;+ }).filter(Boolean)+ : undefined;+return {...slide,id: uniqueId(slide.id, used),@@ -241,8 +257,10 @@ function migrateSlide(slide, used) {headline: localized(slide.headline || slide.title || slide.caption || slide.copy),screenshot: firstString(slide.screenshot, slide.image, slide.src, slide.path),screenshotSecondary: typeof slide.screenshotSecondary === "string" ? slide.screenshotSecondary : undefined,+ inverted: typeof slide.inverted === "boolean" ? slide.inverted : undefined,...(Object.keys(transforms).length ? { transforms } : { transforms: undefined }),...(textElements && textElements.length ? { textElements } : { textElements: undefined }),+ ...(imageElements && imageElements.length ? { imageElements } : { imageElements: undefined }),};}@@ -709,6 +727,7 @@ The current template writes `schemaVersion: 2`. Existing projects made by earlie4. Keeps pre-v2 decks in isolated-screen mode by setting `connectedCanvas: false`, so already-clipped phones or captions do not suddenly appear in neighboring exports.5. Lets the user opt into connected crops with the toolbar's Connected/Isolated control when they are ready to use cross-screen placement.6. Saves the upgraded state back to `app-store-screenshots.json` and `localStorage` only after the file endpoint has loaded successfully, so stale browser cache cannot overwrite the canonical project file during dev-server restarts.+7. Detects newer disk revisions before autosaving. If another tab or an agent edits the project, keep unsaved work open and export or copy it before reloading; do not force a stale save over the newer file.There are two migration modes:diff --git a/skills/app-store-screenshots/template/README.md b/skills/app-store-screenshots/template/README.mdindex d356359..a19ea1b 100644--- a/skills/app-store-screenshots/template/README.md+++ b/skills/app-store-screenshots/template/README.md@@ -4,6 +4,8 @@ A pre-built Next.js + ShadCN editor for generating App Store and Google Play scr## Quick start+Requires Node.js 20.9 or newer.+```bashbun install # or pnpm / yarn / npmbun dev # http://localhost:3000@@ -57,7 +59,7 @@ The toolbar **Theme** menu recolours the whole deck (backgrounds, text, accents)The toolbar font menu sets the typeface of the screenshot canvas and exports (not the editor UI). **Inter (default)** is the template font and what projects without a `fontId` use. **System Sans** and **Georgia** are available everywhere; **Avenir Next**, **Helvetica Neue**, **Futura**, **Baskerville**, **Palatino**, **Optima** and **American Typewriter** are macOS system fonts that fall back to similar faces elsewhere, so export on the machine you designed on.-**Import font…** at the bottom of the menu takes a licensed WOFF2, WOFF, TTF or OTF file (16 MB max). `/api/upload-font` checks the file's magic bytes and stores it as `public/fonts/imported/<hash>.<ext>`; the project saves it as `importedFont` with `fontId: "self-hosted"`. That font folder is gitignored (font licences often forbid redistribution); keep the file alongside the project JSON if you move the project, or screenshot text falls back to a generic sans-serif. Once imported, the font is listed in the menu under its file name, and it is loaded and embedded before every export.+**Import font…** at the bottom of the menu takes a licensed WOFF2, WOFF, TTF or OTF file (16 MB max). The browser decodes the font before uploading; `/api/upload-font` checks the container signature, lengths and table bounds before storing it as `public/fonts/imported/<hash>.<ext>`. The project saves it as `importedFont` with `fontId: "self-hosted"`. That font folder is gitignored (font licences often forbid redistribution); keep the file alongside the project JSON if you move the project, or screenshot text falls back to a generic sans-serif. Once imported, the font is listed in the menu under its file name, and it is loaded and embedded before every export.### Image overlays@@ -83,6 +85,19 @@ The toolbar arrows, `⌘Z` / `Ctrl+Z` and `⇧⌘Z` / `Ctrl+Shift+Z` (or `Ctrl+Y- `mockup.png` is the iPhone bezel overlay; replacing it requires re-measuring the `PHONE_SCREEN` constants.- Image preloading converts every static path to a base64 data URI before exports run, and export retries paths that were previously missing. `export-render.ts` then waits for those images to paint in the render (see Exporting).- Reset via the toolbar's circular arrow icon clears in-memory state and reloads the default screens. To wipe disk state too, delete `app-store-screenshots.json`.-- **Persistence model** — the canonical state lives in `app-store-screenshots.json` (git-tracked). On load, the editor reads localStorage first for instant paint, then overwrites with the file contents if present; if the file endpoint is unavailable, autosave is blocked so stale cache cannot overwrite disk. On save, both are written. File saves are serialized, and the server replaces the JSON atomically so overlapping edits cannot leave a partial file. Invalid project shapes are rejected without overwriting the project. If you ever see a conflict, the file always wins.+- **Persistence model** — the canonical state lives in `app-store-screenshots.json` (git-tracked). On load, the editor reads localStorage first, then reconciles with the file; if the file endpoint is unavailable, autosave is blocked so stale cache cannot overwrite disk. File saves are serialized and atomic. Each editor sends the revision it loaded, so a newer save from another tab or an on-disk edit produces a conflict instead of an overwrite. Your unsaved work stays open: export or copy it before reloading. **Retry save** retries transient failures; it does not override conflicts. Leaving with unsaved edits triggers the browser's warning.- **Migration model** — schema v1 projects do not need a manual conversion. On first load, the editor upgrades localized text and transform records, writes `schemaVersion: 2`, preserves all existing screens, and keeps `connectedCanvas: false` so old offscreen/clipped elements export exactly as isolated screens. Turn on **Connected** in the toolbar when you want elements to cross screen edges. Explicit skill migrations preserve an existing `connectedCanvas` choice, otherwise they keep legacy decks isolated too.- **Custom themes** — if a project file references a theme id that is not present in `src/lib/constants.ts`, the editor falls back to `clean-light` and shows a warning. Merge custom `THEMES` entries during in-place upgrades.++## Local API contract++These routes are for a local editor running in one server process. They have no authentication for remote hosting. Browser writes must come from the same origin and use `Content-Type: application/json`; headerless scripts still work.++- `GET /api/project` returns `{ ok, state }` and an `ETag` revision, including when the project file is missing.+- `POST /api/project` accepts project JSON (64 MiB request limit). Send the last `ETag` as `If-Match` to reject stale writes with HTTP 412; success returns a new `ETag`. Scripts that omit `If-Match` intentionally keep unconditional replacement behavior. Unknown schema versions, unknown device decks, duplicate IDs, and malformed element data are rejected with HTTP 400.+- `POST /api/upload` accepts `{ dataUrl }` for PNG/JPEG (8 MiB decoded file, 12 MiB request, 64 megapixels). It decodes the image before storing the original bytes. Rejected files keep the previous selection; unavailable endpoints can still fall back to inline images.+- `POST /api/upload-font` accepts `{ data }` containing base64 font bytes (16 MiB decoded file, 23 MiB request). Server validation checks the font container; the editor's browser additionally validates font decoding.++Uploads are written atomically. Project and upload requests time out after 15 seconds in the editor; image preloads after 10 seconds. Export also stops with a retryable error if font loading takes longer than 15 seconds. Failed preloads can be retried on export, and failed or stalled PNG workers finish through the inline encoder.++The `/screenshots/uploaded/[filename]` and `/fonts/imported/[filename]` routes serve uploads created after server startup, including with `next start`. They accept only the generated hash filenames and supported extensions, preserving the same asset URLs and on-disk locations as the dev server.diff --git a/skills/app-store-screenshots/template/bun.lock b/skills/app-store-screenshots/template/bun.lockindex 8b41fdc..124f4ba 100644--- a/skills/app-store-screenshots/template/bun.lock+++ b/skills/app-store-screenshots/template/bun.lock@@ -25,6 +25,7 @@"react": "^19.2.8","react-dom": "^19.2.8","react-rnd": "^10.5.3",+ "sharp": "0.35.4","sonner": "^1.7.0","tailwind-merge": "^2.5.4","tailwindcss-animate": "^1.0.7",diff --git a/skills/app-store-screenshots/template/package.json b/skills/app-store-screenshots/template/package.jsonindex d6078cb..6cd800a 100644--- a/skills/app-store-screenshots/template/package.json+++ b/skills/app-store-screenshots/template/package.json@@ -2,6 +2,7 @@"name": "app-store-screenshots","version": "0.1.0","private": true,+ "engines": { "node": ">=20.9.0" },"scripts": {"dev": "next dev","build": "next build",@@ -28,6 +29,7 @@"react": "^19.2.8","react-dom": "^19.2.8","react-rnd": "^10.5.3",+ "sharp": "0.35.4","sonner": "^1.7.0","tailwind-merge": "^2.5.4","tailwindcss-animate": "^1.0.7"diff --git a/skills/app-store-screenshots/template/src/app/api/project/route.ts b/skills/app-store-screenshots/template/src/app/api/project/route.tsindex 5acb979..c99d710 100644--- a/skills/app-store-screenshots/template/src/app/api/project/route.ts+++ b/skills/app-store-screenshots/template/src/app/api/project/route.ts@@ -1,9 +1,10 @@import { promises as fs } from "node:fs";import path from "node:path";-import { randomUUID } from "node:crypto";+import { createHash, randomUUID } from "node:crypto";import { NextResponse } from "next/server";import { projectValidationError } from "@/lib/project-validation";import { rejectCrossSiteWrite } from "@/lib/request-guard";+import { readJsonBody } from "@/lib/request-body";export const dynamic = "force-dynamic";@@ -13,17 +14,20 @@ function filePath() {return path.join(process.cwd(), PROJECT_FILE);}+const revision = (raw: string | null) => `"${raw === null ? "missing" : createHash("sha256").update(raw).digest("hex")}"`;+let writes: Promise<unknown> = Promise.resolve();+export async function GET() {try {const raw = await fs.readFile(filePath(), "utf8");const parsed = JSON.parse(raw);const validationError = projectValidationError(parsed);if (validationError) throw new Error(validationError);- return NextResponse.json({ ok: true, state: parsed });+ return NextResponse.json({ ok: true, state: parsed }, { headers: { ETag: revision(raw), "Cache-Control": "no-store" } });} catch (e) {const code = (e as NodeJS.ErrnoException).code;if (code === "ENOENT") {- return NextResponse.json({ ok: true, state: null });+ return NextResponse.json({ ok: true, state: null }, { headers: { ETag: revision(null), "Cache-Control": "no-store" } });}return NextResponse.json({ ok: false, error: e instanceof Error ? e.message : String(e) },@@ -38,23 +42,42 @@ export async function POST(req: Request) {if (blocked) {return NextResponse.json({ ok: false, error: blocked.error }, { status: blocked.status });}- let body: unknown;- try {- body = await req.json();- } catch {- return NextResponse.json({ ok: false, error: "Invalid JSON" }, { status: 400 });- }+ const parsed = await readJsonBody(req, 64 * 1024 * 1024);+ if (parsed.response) return parsed.response;+ const body = parsed.value;const validationError = projectValidationError(body);if (validationError) {return NextResponse.json({ ok: false, error: validationError }, { status: 400 });}+ // Compare and replace in one queue so two tabs cannot both save the same+ // revision. CLI writers may omit If-Match for backwards compatibility.+ const result = writes.then(() => writeProject(body, req.headers.get("if-match")));+ writes = result.catch(() => undefined);+ return result;+}++async function writeProject(body: unknown, expected: string | null) {const temporary = `${filePath()}.${randomUUID()}.tmp`;try {+ if (expected !== null) {+ let current: string | null;+ try { current = await fs.readFile(filePath(), "utf8"); }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;+ current = null;+ }+ if (expected !== revision(current)) {+ return NextResponse.json(+ { ok: false, error: "Project changed in another tab or on disk. Your edits are still open here; export or copy them before reloading." },+ { status: 412 },+ );+ }+ }const pretty = JSON.stringify(body, null, 2) + "\n";// Readers must see either the previous complete project or the next one.await fs.writeFile(temporary, pretty, "utf8");await fs.rename(temporary, filePath());- return NextResponse.json({ ok: true });+ return NextResponse.json({ ok: true }, { headers: { ETag: revision(pretty) } });} catch (e) {return NextResponse.json({ ok: false, error: e instanceof Error ? e.message : String(e) },diff --git a/skills/app-store-screenshots/template/src/app/api/upload-font/route.ts b/skills/app-store-screenshots/template/src/app/api/upload-font/route.tsindex dae2d10..6b7f8b7 100644--- a/skills/app-store-screenshots/template/src/app/api/upload-font/route.ts+++ b/skills/app-store-screenshots/template/src/app/api/upload-font/route.ts@@ -4,6 +4,8 @@ import path from "node:path";import { NextResponse } from "next/server";import { rejectCrossSiteWrite } from "@/lib/request-guard";import type { ImportedFont } from "@/lib/types";+import { decodeBase64, readJsonBody } from "@/lib/request-body";+import { writeAsset } from "@/lib/write-asset";export const dynamic = "force-dynamic";@@ -32,18 +34,42 @@ function sniffFontFormat(bytes: Buffer): ImportedFont["format"] | null {return null;}+// Check container lengths and table bounds before persisting. Glyph validity+// is checked by the browser's FontFace decoder before the UI imports the file.+function hasFontStructure(bytes: Buffer, format: ImportedFont["format"]): boolean {+ const web = format === "woff" || format === "woff2";+ const header = web ? (format === "woff2" ? 48 : 44) : 12;+ if (bytes.length < header) return false;+ const count = bytes.readUInt16BE(web ? 12 : 4);+ if (!count) return false;+ if (web && (bytes.readUInt32BE(8) !== bytes.length || bytes.readUInt16BE(14) !== 0 ||+ bytes.readUInt32BE(16) > 64 * 1024 * 1024)) return false;+ if (format === "woff2") {+ const compressed = bytes.readUInt32BE(20);+ return compressed > 0 && header + count * 2 + compressed <= bytes.length;+ }+ const stride = web ? 20 : 16;+ const directoryEnd = header + count * stride;+ if (directoryEnd > bytes.length) return false;+ for (let i = 0; i < count; i++) {+ const entry = header + i * stride;+ const offset = bytes.readUInt32BE(entry + (web ? 4 : 8));+ const length = bytes.readUInt32BE(entry + (web ? 8 : 12));+ if (offset < directoryEnd || offset + length > bytes.length) return false;+ if (web && length > bytes.readUInt32BE(entry + 12)) return false;+ }+ return true;+}+export async function POST(req: Request) {// This route WRITES A FILE to disk. See lib/request-guard.ts.const blocked = rejectCrossSiteWrite(req);if (blocked) {return NextResponse.json({ ok: false, error: blocked.error }, { status: blocked.status });}- let body: { data?: unknown };- try {- body = (await req.json()) as { data?: unknown };- } catch {- return NextResponse.json({ ok: false, error: "Invalid JSON" }, { status: 400 });- }+ const input = await readJsonBody(req, 23 * 1024 * 1024);+ if (input.response) return input.response;+ const body = input.value as { data?: unknown } | null;if (typeof body?.data !== "string" || !body.data) {return NextResponse.json({ ok: false, error: "Choose a font file first." }, { status: 400 });}@@ -51,12 +77,13 @@ export async function POST(req: Request) {if (body.data.length > Math.ceil(MAX_FONT_BYTES / 3) * 4) {return NextResponse.json({ ok: false, error: "Font file is too large (16MB maximum)." }, { status: 413 });}- const bytes = Buffer.from(body.data, "base64");+ const bytes = decodeBase64(body.data);+ if (!bytes) return NextResponse.json({ ok: false, error: "Invalid base64 font data" }, { status: 400 });if (bytes.byteLength > MAX_FONT_BYTES) {return NextResponse.json({ ok: false, error: "Font file is too large (16MB maximum)." }, { status: 413 });}const format = sniffFontFormat(bytes);- if (!format) {+ if (!format || !hasFontStructure(bytes, format)) {return NextResponse.json({ ok: false, error: "Use a WOFF2, WOFF, TTF, or OTF font file." }, { status: 400 });}@@ -67,11 +94,7 @@ export async function POST(req: Request) {try {await fs.mkdir(absDir, { recursive: true });- try {- await fs.access(absFile);- } catch {- await fs.writeFile(absFile, bytes);- }+ await writeAsset(absFile, bytes);const font: ImportedFont = { src: `${PUBLIC_PREFIX}/${filename}`, format };return NextResponse.json({ ok: true, font });} catch (e) {diff --git a/skills/app-store-screenshots/template/src/app/api/upload/route.ts b/skills/app-store-screenshots/template/src/app/api/upload/route.tsindex 7db849c..f71f041 100644--- a/skills/app-store-screenshots/template/src/app/api/upload/route.ts+++ b/skills/app-store-screenshots/template/src/app/api/upload/route.ts@@ -3,6 +3,9 @@ import { promises as fs } from "node:fs";import path from "node:path";import { NextResponse } from "next/server";import { rejectCrossSiteWrite, sniffImageType } from "@/lib/request-guard";+import sharp from "sharp";+import { decodeBase64, readJsonBody } from "@/lib/request-body";+import { writeAsset } from "@/lib/write-asset";export const dynamic = "force-dynamic";@@ -19,8 +22,8 @@ function parseDataUrl(dataUrl: string): { mime: string; bytes: Buffer } | null {const m = /^data:([^;]+);base64,(.+)$/.exec(dataUrl);if (!m) return null;const mime = m[1].toLowerCase();- const bytes = Buffer.from(m[2], "base64");- return { mime, bytes };+ const bytes = decodeBase64(m[2]);+ return bytes ? { mime, bytes } : null;}export async function POST(req: Request) {@@ -29,12 +32,9 @@ export async function POST(req: Request) {if (blocked) {return NextResponse.json({ ok: false, error: blocked.error }, { status: blocked.status });}- let body: { dataUrl?: string };- try {- body = (await req.json()) as { dataUrl?: string };- } catch {- return NextResponse.json({ ok: false, error: "Invalid JSON" }, { status: 400 });- }+ const input = await readJsonBody(req, 12 * 1024 * 1024);+ if (input.response) return input.response;+ const body = input.value as { dataUrl?: string } | null;if (!body?.dataUrl || typeof body.dataUrl !== "string") {return NextResponse.json({ ok: false, error: "Missing dataUrl" }, { status: 400 });}@@ -62,6 +62,13 @@ export async function POST(req: Request) {return NextResponse.json({ ok: false, error: "Image too large (>8MB)" }, { status: 413 });}+ try {+ // Decode pixels too: valid headers alone still accept truncated images.+ await sharp(parsed.bytes, { limitInputPixels: 64 * 1024 * 1024, failOn: "warning" }).stats();+ } catch {+ return NextResponse.json({ ok: false, error: "Image is corrupt or exceeds 64 megapixels" }, { status: 400 });+ }+const hash = createHash("sha1").update(parsed.bytes).digest("hex").slice(0, 16);const filename = `${hash}.${ext}`;const absDir = path.join(process.cwd(), UPLOAD_DIR_REL);@@ -69,11 +76,7 @@ export async function POST(req: Request) {try {await fs.mkdir(absDir, { recursive: true });- try {- await fs.access(absFile);- } catch {- await fs.writeFile(absFile, parsed.bytes);- }+ await writeAsset(absFile, parsed.bytes);return NextResponse.json({ ok: true, path: `${PUBLIC_PREFIX}/${filename}` });} catch (e) {return NextResponse.json(diff --git a/skills/app-store-screenshots/template/src/app/fonts/imported/[filename]/route.ts b/skills/app-store-screenshots/template/src/app/fonts/imported/[filename]/route.tsnew file mode 100644index 0000000..6fee670--- /dev/null+++ b/skills/app-store-screenshots/template/src/app/fonts/imported/[filename]/route.ts@@ -0,0 +1,8 @@+import { serveAsset } from "@/lib/serve-asset";++export const dynamic = "force-dynamic";++export async function GET(_req: Request, context: { params: Promise<{ filename: string }> }) {+ const { filename } = await context.params;+ return serveAsset("fonts/imported", filename, { woff2: "font/woff2", woff: "font/woff", ttf: "font/ttf", otf: "font/otf" });+}diff --git a/skills/app-store-screenshots/template/src/app/screenshots/uploaded/[filename]/route.ts b/skills/app-store-screenshots/template/src/app/screenshots/uploaded/[filename]/route.tsnew file mode 100644index 0000000..609639c--- /dev/null+++ b/skills/app-store-screenshots/template/src/app/screenshots/uploaded/[filename]/route.ts@@ -0,0 +1,8 @@+import { serveAsset } from "@/lib/serve-asset";++export const dynamic = "force-dynamic";++export async function GET(_req: Request, context: { params: Promise<{ filename: string }> }) {+ const { filename } = await context.params;+ return serveAsset("screenshots/uploaded", filename, { png: "image/png", jpg: "image/jpeg" });+}diff --git a/skills/app-store-screenshots/template/src/components/editor/background-controls.tsx b/skills/app-store-screenshots/template/src/components/editor/background-controls.tsxindex dd7abd5..04942b4 100644--- a/skills/app-store-screenshots/template/src/components/editor/background-controls.tsx+++ b/skills/app-store-screenshots/template/src/components/editor/background-controls.tsx@@ -37,7 +37,7 @@ export function BackgroundControls({ slide, theme, onChange }: Props) {if (nextMode === "custom") onChange({ inverted: false, backgroundColor: customColor });}}>- <SelectTrigger><SelectValue /></SelectTrigger>+ <SelectTrigger aria-label="Background"><SelectValue /></SelectTrigger><SelectContent><SelectItem value="theme">Theme background</SelectItem><SelectItem value="alternate">Theme alternate</SelectItem>diff --git a/skills/app-store-screenshots/template/src/components/editor/font-importer.tsx b/skills/app-store-screenshots/template/src/components/editor/font-importer.tsxindex ad9d2ee..ebb2ea7 100644--- a/skills/app-store-screenshots/template/src/components/editor/font-importer.tsx+++ b/skills/app-store-screenshots/template/src/components/editor/font-importer.tsx@@ -31,32 +31,40 @@ export const FontImporter = React.forwardRef<FontImporterHandle, Props>(functionref,) {const inputRef = React.useRef<HTMLInputElement>(null);+ const requestId = React.useRef(0);+ React.useEffect(() => () => { requestId.current += 1; }, []);React.useImperativeHandle(ref, () => ({ open: () => inputRef.current?.click() }), []);async function importFont(file: File) {+ const request = ++requestId.current;onUploadingChange?.(true);try {if (file.size > MAX_FONT_BYTES) throw new Error("Font file is too large (16MB maximum).");+ await new FontFace("Import validation", await file.arrayBuffer()).load();+ if (request !== requestId.current) return;const response = await fetch("/api/upload-font", {method: "POST",headers: { "content-type": "application/json" },body: JSON.stringify({ data: await fileToBase64(file) }),+ signal: AbortSignal.timeout(15000),});const data = (await response.json().catch(() => ({ ok: false }))) as {ok: boolean;error?: string;font?: ImportedFont;};- if (!data.ok || !data.font) throw new Error(data.error || "Could not import that font.");+ if (request !== requestId.current) return;+ if (!response.ok || !data.ok || !data.font) throw new Error(data.error || "Could not import that font.");const name = cleanFontName(file.name.replace(/\.[^.]+$/, ""));onImported({ ...data.font, ...(name ? { name } : {}) });toast.success(`Imported ${name ?? "font"}`);} catch (caught) {+ if (request !== requestId.current) return;toast.error("Font import failed", {description: caught instanceof Error ? caught.message : "Could not import that font.",});} finally {- onUploadingChange?.(false);+ if (request === requestId.current) onUploadingChange?.(false);}}diff --git a/skills/app-store-screenshots/template/src/components/editor/inspector.tsx b/skills/app-store-screenshots/template/src/components/editor/inspector.tsxindex bfbad41..e3505bb 100644--- a/skills/app-store-screenshots/template/src/components/editor/inspector.tsx+++ b/skills/app-store-screenshots/template/src/components/editor/inspector.tsx@@ -154,11 +154,11 @@ export function Inspector({layout: next,transforms: undefined,screenshotSecondary:- next === "two-devices" ? slide.screenshotSecondary || slide.screenshot : undefined,+ next === "two-devices" ? slide.screenshotSecondary || slide.screenshot : slide.screenshotSecondary,});}}>- <SelectTrigger>+ <SelectTrigger aria-label="Layout"><SelectValue /></SelectTrigger><SelectContent>@@ -177,6 +177,7 @@ export function Inspector({<div className="space-y-1.5"><Label className="text-xs">Label</Label><Input+ aria-label="Label"value={localeLabel}onChange={(e) => setLocaleField("label", e.target.value)}placeholder={labelPlaceholder}@@ -193,6 +194,7 @@ export function Inspector({</div></div><Textarea+ aria-label={isFeatureGraphic ? "Tagline" : "Headline"}value={localeHeadline}onChange={(e) => setLocaleField("headline", e.target.value)}rows={3}@@ -407,8 +409,13 @@ function ElementTransformControls({// The first image picked for an overlay reshapes its frame to the image's// aspect ratio (centred on the old frame), so "Fill frame" doesn't crop a// wide logo into a square. Replacing an image keeps the frame as placed.+ const imageRequests = React.useRef(new Map<string, number>());+ React.useEffect(() => () => imageRequests.current.clear(), []);async function setImageSource(id: string, src: string) {+ const request = (imageRequests.current.get(id) || 0) + 1;+ imageRequests.current.set(id, request);const size = src ? await naturalSize(img(src)) : null;+ if (imageRequests.current.get(id) !== request) return;onUpdate((latest) => ({imageElements: (latest.imageElements || []).map((element) => {if (element.id !== id) return element;@@ -554,6 +561,7 @@ function ElementTransformControls({{activeId ? (<ActiveElementPanel+ key={activeId}activeId={activeId}transform={activeTransform}textElement={activeTextElement || undefined}@@ -727,7 +735,7 @@ function ImageElementPanel({<div className="space-y-1"><Label className="text-[11px] text-muted-foreground">Fit</Label><Select value={element.fit || "cover"} onValueChange={(fit) => onPatch({ fit: fit as ImageElement["fit"] })}>- <SelectTrigger className="h-8 text-xs"><SelectValue /></SelectTrigger>+ <SelectTrigger className="h-8 text-xs" aria-label="Image fit"><SelectValue /></SelectTrigger><SelectContent><SelectItem value="cover">Fill frame</SelectItem><SelectItem value="contain">Whole image</SelectItem>@@ -743,7 +751,7 @@ function ImageElementPanel({fade:edge === "none"? undefined- : { edge: edge as NonNullable<ImageElement["fade"]>["edge"], amount: element.fade?.amount || 35 },+ : { edge: edge as NonNullable<ImageElement["fade"]>["edge"], amount: element.fade?.amount ?? 35 },})}>@@ -811,8 +819,10 @@ function TextElementPanel({// Typing is buffered so intermediate values ("1" on the way to "120") don't// get clamped mid-keystroke; the value is committed on blur / Enter.const [draft, setDraft] = React.useState<string | null>(null);+ const cancelDraft = React.useRef(false);function commitDraft() {+ if (cancelDraft.current) { cancelDraft.current = false; return; }if (draft === null) return;const n = Number(draft);if (draft.trim() !== "" && Number.isFinite(n)) {@@ -865,6 +875,9 @@ function TextElementPanel({onKeyDown={(event) => {if (event.key === "Enter") event.currentTarget.blur();if (event.key === "Escape") {+ event.preventDefault();+ event.stopPropagation();+ cancelDraft.current = true;setDraft(null);event.currentTarget.blur();}@@ -1093,9 +1106,14 @@ function naturalSize(src: string): Promise<{ w: number; h: number } | null> {if (!src) return Promise.resolve(null);return new Promise((resolve) => {const image = new Image();- image.onload = () =>- resolve(image.naturalWidth > 0 && image.naturalHeight > 0 ? { w: image.naturalWidth, h: image.naturalHeight } : null);- image.onerror = () => resolve(null);+ const finish = (size: { w: number; h: number } | null) => {+ clearTimeout(timeout);+ image.onload = image.onerror = null;+ resolve(size);+ };+ const timeout = setTimeout(() => finish(null), 10000);+ image.onload = () => finish(image.naturalWidth > 0 && image.naturalHeight > 0 ? { w: image.naturalWidth, h: image.naturalHeight } : null);+ image.onerror = () => finish(null);image.src = src;});}diff --git a/skills/app-store-screenshots/template/src/components/editor/preview-stage.tsx b/skills/app-store-screenshots/template/src/components/editor/preview-stage.tsxindex 9964a6d..71634d5 100644--- a/skills/app-store-screenshots/template/src/components/editor/preview-stage.tsx+++ b/skills/app-store-screenshots/template/src/components/editor/preview-stage.tsx@@ -86,19 +86,22 @@ export function PreviewStage({setZoom(1);}, [device, orientation]);+ const panToActiveScreen = React.useCallback((nextScale: number) => {+ const scroller = scrollerRef.current;+ if (!scroller || !activeId) return;+ const screenLeft = activeIndex * cW * nextScale;+ const screenWidth = cW * nextScale;+ const targetLeft = Math.max(0, screenLeft - (scroller.clientWidth - screenWidth) / 2);+ scroller.scrollTo({ left: targetLeft, behavior: "smooth" });+ }, [activeIndex, activeId, cW]);+React.useEffect(() => {if (suppressNextActiveScreenPanRef.current) {suppressNextActiveScreenPanRef.current = false;return;}-- const scroller = scrollerRef.current;- if (!scroller || !activeId) return;- const screenLeft = activeIndex * cW * scale;- const screenWidth = cW * scale;- const targetLeft = Math.max(0, screenLeft - (scroller.clientWidth - screenWidth) / 2);- scroller.scrollTo({ left: targetLeft, behavior: "smooth" });- }, [activeIndex, activeId, cW, scale]);+ panToActiveScreen(scale);+ }, [panToActiveScreen, scale]);const handleCanvasActiveSlideChange = React.useCallback((id: string) => {@@ -224,7 +227,10 @@ export function PreviewStage({variant="ghost"size="icon"className="h-6 w-6"- onClick={() => setZoom(1)}+ onClick={() => {+ setZoom(1);+ panToActiveScreen(fitScale);+ }}title="Fit active screen"aria-label="Fit active screen">diff --git a/skills/app-store-screenshots/template/src/components/editor/screenshot-editor.tsx b/skills/app-store-screenshots/template/src/components/editor/screenshot-editor.tsxindex 2fe005d..1f3054c 100644--- a/skills/app-store-screenshots/template/src/components/editor/screenshot-editor.tsx+++ b/skills/app-store-screenshots/template/src/components/editor/screenshot-editor.tsx@@ -36,11 +36,12 @@ import { DeckCanvas, getCanvas } from "./slide-canvas";import { Toolbar } from "./toolbar";export function ScreenshotEditor() {- const { state, setState, hydrated, savedAt, saveError, reset, resetDevice, undo, redo, canUndo, canRedo } = useProject();+ const { state, setState, hydrated, savedAt, saveError, retrySave, reset, resetDevice, undo, redo, canUndo, canRedo } = useProject();const [activeSlideId, setActiveSlideId] = React.useState<string | null>(null);const [selectedElement, setSelectedElement] = React.useState<SelectedElement | null>(null);const [exporting, setExporting] = React.useState<string | null>(null);const [ready, setReady] = React.useState(false);+ const [, refreshAssets] = React.useReducer((version: number) => version + 1, 0);const [exportLocaleOverride, setExportLocaleOverride] = React.useState<string | null>(null);const [exportSlideIndex, setExportSlideIndex] = React.useState(0);const exportInProgress = React.useRef(false);@@ -108,7 +109,11 @@ export function ScreenshotEditor() {React.useEffect(() => {if (!hydrated) return;- preloadImages(assetPaths).finally(() => setReady(true));+ let cancelled = false;+ preloadImages(assetPaths).finally(() => {+ if (!cancelled) { setReady(true); refreshAssets(); }+ });+ return () => { cancelled = true; };// assetPaths is derived from assetSig; depending on the string keeps the// effect from re-firing when slidesByDevice churns without path changes.// eslint-disable-next-line react-hooks/exhaustive-deps@@ -472,13 +477,23 @@ export function ScreenshotEditor() {// Make sure custom fonts are loaded before snapshot so typography in PNG// matches what's on screen.if (typeof document !== "undefined" && document.fonts && document.fonts.ready) {+ let timeout: ReturnType<typeof setTimeout> | undefined;try {- // fonts.ready only covers faces already requested; explicitly load an- // imported font so a not-yet-used face can't export as the fallback.- if (fontId === "self-hosted") await document.fonts.load(`64px ${fontFamily}`);- await document.fonts.ready;+ await Promise.race([+ (async () => {+ // fonts.ready only covers faces already requested; explicitly load an+ // imported font so a not-yet-used face can't export as the fallback.+ if (fontId === "self-hosted") await document.fonts.load(`64px ${fontFamily}`);+ await document.fonts.ready;+ })(),+ new Promise<never>((_, reject) => {+ timeout = setTimeout(() => reject(new Error("Font loading timed out")), 15000);+ }),+ ]);} catch {- throw new Error("The screenshot font could not be loaded. Check the imported font file.");+ throw new Error("The screenshot font could not be loaded. Check the imported font file and connection, then retry.");+ } finally {+ clearTimeout(timeout);}}@@ -534,8 +549,9 @@ export function ScreenshotEditor() {failed += sizes.length;continue;}- await encoding;- encoding = pngs.then(+ // Attach rejection handling now: this screen can fail while the+ // previous screen is still encoding.+ const nextEncoding = pngs.then((files) => {sizes.forEach((size, index) => {zip.file(`${platform}/${state.device}/${size.w}x${size.h}/${locale}/${filename}`, files[index]);@@ -547,6 +563,8 @@ export function ScreenshotEditor() {failed += sizes.length;},);+ await encoding;+ encoding = nextEncoding;}}await encoding;@@ -639,8 +657,8 @@ export function ScreenshotEditor() {const exportCanvas = getCanvas(exportState.device, exportState.orientation);return (- <div className="flex h-screen flex-col overflow-hidden bg-background">- <Toaster position="top-right" richColors closeButton />+ <div className="flex h-dvh flex-col overflow-hidden bg-background">+ <Toaster position="bottom-center" richColors closeButton /><ToolbarappName={state.appName}setAppName={(v) => setState((p) => ({ ...p, appName: v }))}@@ -677,11 +695,12 @@ export function ScreenshotEditor() {exporting={exporting}savedAt={savedAt}saveError={saveError}+ onRetrySave={retrySave}busy={busy}/>- <div inert={busy} aria-busy={busy} className="flex flex-1 overflow-hidden md:flex-row flex-col">- <aside className="md:w-72 w-full shrink-0 border-r bg-card md:max-h-none max-h-64 overflow-hidden">+ <div inert={busy} aria-busy={busy} className="flex min-h-0 flex-1 flex-col overflow-y-auto lg:flex-row lg:overflow-hidden">+ <aside className="lg:w-72 w-full shrink-0 border-r bg-card lg:max-h-none max-h-64 overflow-hidden"><Sidebarslides={currentSlides}activeId={activeSlide?.id || null}@@ -702,7 +721,7 @@ export function ScreenshotEditor() {/></aside>- <main className="flex flex-1 items-stretch overflow-hidden min-h-0">+ <main className="flex h-[26rem] shrink-0 items-stretch overflow-hidden lg:h-auto lg:min-h-0 lg:flex-1">{activeSlide && currentSlides.length > 0 ? (<PreviewStageslides={currentSlides}@@ -731,7 +750,7 @@ export function ScreenshotEditor() {)}</main>- <aside className="md:w-80 w-full shrink-0 border-l bg-card md:max-h-none max-h-96 overflow-hidden">+ <aside className="lg:w-80 w-full shrink-0 border-l bg-card lg:max-h-none max-h-96 overflow-hidden">{activeSlide ? (<Inspectorkey={`${state.device}:${activeSlide.id}`}diff --git a/skills/app-store-screenshots/template/src/components/editor/screenshot-picker.tsx b/skills/app-store-screenshots/template/src/components/editor/screenshot-picker.tsxindex 0777eb7..951e6f8 100644--- a/skills/app-store-screenshots/template/src/components/editor/screenshot-picker.tsx+++ b/skills/app-store-screenshots/template/src/components/editor/screenshot-picker.tsx@@ -13,6 +13,7 @@ type Props = {};const ACCEPTED = ["image/png", "image/jpeg"];+class UploadRejectedError extends Error {}async function fileToDataUrl(file: File): Promise<string> {return new Promise((resolve, reject) => {@@ -29,11 +30,17 @@ async function uploadDataUrl(dataUrl: string): Promise<string | null> {method: "POST",headers: { "content-type": "application/json" },body: JSON.stringify({ dataUrl }),+ signal: AbortSignal.timeout(15000),});+ if (resp.status >= 400 && resp.status < 500 && resp.status !== 404) {+ const error = await resp.json().catch(() => ({}));+ throw new UploadRejectedError(error.error || "Image upload was rejected");+ }if (!resp.ok) return null;const json = (await resp.json()) as { ok: boolean; path?: string };return json.ok && json.path ? json.path : null;- } catch {+ } catch (error) {+ if (error instanceof UploadRejectedError) throw error;return null;}}@@ -70,11 +77,29 @@ export function ScreenshotPicker({ label, value, locale, onChange }: Props) {return;}if (request !== requestId.current) return;+ try {+ const image = new Image();+ image.src = dataUrl;+ await image.decode();+ if (image.naturalWidth * image.naturalHeight > 64 * 1024 * 1024) throw new Error("too large");+ } catch {+ if (request === requestId.current) setError("Image is corrupt or exceeds 64 megapixels");+ return;+ }+ if (request !== requestId.current) return;// Try to persist to disk so the screenshot survives a git clone.// If the upload endpoint is unreachable (e.g. static export), fall back// to the inline data URI — still works in the current session.setUploading(true);- const uploadedPath = await uploadDataUrl(dataUrl);+ let uploadedPath: string | null;+ try { uploadedPath = await uploadDataUrl(dataUrl); }+ catch (error) {+ if (request === requestId.current) {+ setUploading(false);+ setError(error instanceof Error ? error.message : "Image upload failed");+ }+ return;+ }if (request !== requestId.current) return;setUploading(false);if (uploadedPath) {diff --git a/skills/app-store-screenshots/template/src/components/editor/slide-canvas.tsx b/skills/app-store-screenshots/template/src/components/editor/slide-canvas.tsxindex cb093f8..9f70d7e 100644--- a/skills/app-store-screenshots/template/src/components/editor/slide-canvas.tsx+++ b/skills/app-store-screenshots/template/src/components/editor/slide-canvas.tsx@@ -1401,6 +1401,7 @@ function Movable({height: 28 / controlScale,}}onPointerDown={startRotate}+ onFocus={() => onSelect?.()}title="Rotate"aria-label="Rotate element">diff --git a/skills/app-store-screenshots/template/src/components/editor/slide-thumb.tsx b/skills/app-store-screenshots/template/src/components/editor/slide-thumb.tsxindex 87db666..c47f621 100644--- a/skills/app-store-screenshots/template/src/components/editor/slide-thumb.tsx+++ b/skills/app-store-screenshots/template/src/components/editor/slide-thumb.tsx@@ -154,8 +154,8 @@ export function SlideThumb({</div></button>- {/* Always visible on touch (no hover); fades in on hover on desktop. */}- <div className="flex flex-col items-center justify-center gap-0.5 opacity-60 transition-opacity focus-within:opacity-100 group-hover:opacity-100 md:opacity-0">+ {/* Keep actions discoverable on touch tablets as well as phones. */}+ <div className="flex flex-col items-center justify-center gap-0.5 opacity-60 transition-opacity focus-within:opacity-100 group-hover:opacity-100"><Buttontype="button"size="icon"diff --git a/skills/app-store-screenshots/template/src/components/editor/toolbar.tsx b/skills/app-store-screenshots/template/src/components/editor/toolbar.tsxindex 28f0ef8..74edfd1 100644--- a/skills/app-store-screenshots/template/src/components/editor/toolbar.tsx+++ b/skills/app-store-screenshots/template/src/components/editor/toolbar.tsx@@ -62,6 +62,7 @@ type Props = {exporting: string | null;savedAt: number | null;saveError: string | null;+ onRetrySave?: () => void;busy: boolean;};@@ -248,6 +249,9 @@ export function Toolbar(props: Props) {<div className="ml-auto flex shrink-0 items-center gap-2"><SaveStatus savedAt={props.savedAt} saveError={props.saveError} />+ {props.saveError && props.onRetrySave && (+ <Button variant="ghost" size="sm" disabled={props.busy} onClick={props.onRetrySave}>Retry save</Button>+ )}<span aria-hidden className="h-5 w-px bg-border" /><Buttontype="button"diff --git a/skills/app-store-screenshots/template/src/lib/image-cache.ts b/skills/app-store-screenshots/template/src/lib/image-cache.tsindex 8acfddd..dd0022f 100644--- a/skills/app-store-screenshots/template/src/lib/image-cache.ts+++ b/skills/app-store-screenshots/template/src/lib/image-cache.ts@@ -4,18 +4,25 @@const cache = new Map<string, string>();const failed = new Set<string>();+const pending = new Map<string, Promise<void>>();async function fetchAsDataUrl(path: string): Promise<string | null> {try {- const resp = await fetch(path);+ const resp = await fetch(path, { signal: AbortSignal.timeout(10000) });if (!resp.ok) return null;const blob = await resp.blob();- return await new Promise<string>((resolve, reject) => {+ const data = await new Promise<string>((resolve, reject) => {const reader = new FileReader();reader.onloadend = () => resolve(reader.result as string);reader.onerror = reject;reader.readAsDataURL(blob);});+ // A successful HTTP response may still be an HTML error page or corrupt+ // image. Catch that before export silently substitutes an empty device.+ const image = new Image();+ image.src = data;+ await image.decode();+ return data;} catch {return null;}@@ -29,14 +36,17 @@ export async function preloadImages(paths.filter(Boolean).filter((p) => !cache.has(p) && (options.retryFailed || !failed.has(p)))- .map(async (p) => {- const data = await fetchAsDataUrl(p);- if (data) {- cache.set(p, data);- failed.delete(p);- } else {- failed.add(p);- }+ .map((p) => {+ const existing = pending.get(p);+ if (existing) return existing;+ const task = fetchAsDataUrl(p).then((data) => {+ // A newer upload may have populated the same content-addressed URL.+ if (cache.has(p)) return;+ if (data) { cache.set(p, data); failed.delete(p); }+ else failed.add(p);+ }).finally(() => pending.delete(p));+ pending.set(p, task);+ return task;}),);}@@ -55,6 +65,5 @@ export function setImage(path: string, dataUrl: string) {export function didFail(path: string | undefined): boolean {if (!path) return false;- if (path.startsWith("data:")) return false;return failed.has(path);}diff --git a/skills/app-store-screenshots/template/src/lib/png-encode.ts b/skills/app-store-screenshots/template/src/lib/png-encode.tsindex 9964f7a..d389aed 100644--- a/skills/app-store-screenshots/template/src/lib/png-encode.ts+++ b/skills/app-store-screenshots/template/src/lib/png-encode.ts@@ -12,6 +12,7 @@ type Job = {height: number;resolve: (png: Uint8Array) => void;reject: (error: unknown) => void;+ timeout: ReturnType<typeof setTimeout>;};type Result = { id: number; png?: Uint8Array; error?: string };@@ -21,9 +22,20 @@ let nextId = 0;const jobs = new Map<number, Job>();function encodeInline(job: Job) {+ clearTimeout(job.timeout);encodeRgbPixels(job.pixels, job.width, job.height).then(job.resolve, job.reject);}+function retireWorker(worker: Worker) {+ worker.terminate();+ pool = (pool || []).filter((w) => w !== worker);+ for (const [id, job] of jobs) {+ if (job.worker !== worker) continue;+ jobs.delete(id);+ encodeInline(job);+ }+}+function workers(): Worker[] {if (pool) return pool;pool = [];@@ -35,6 +47,7 @@ function workers(): Worker[] {const job = jobs.get(data.id);if (!job) return;jobs.delete(data.id);+ clearTimeout(job.timeout);if (data.png) job.resolve(data.png);else encodeInline(job);};@@ -42,14 +55,9 @@ function workers(): Worker[] {// finish inline instead of leaving the export waiting forever.worker.onerror = (event) => {event.preventDefault();- worker.terminate();- pool = (pool || []).filter((w) => w !== worker);- for (const [id, job] of jobs) {- if (job.worker !== worker) continue;- jobs.delete(id);- encodeInline(job);- }+ retireWorker(worker);};+ worker.onmessageerror = () => retireWorker(worker);pool.push(worker);}} catch {@@ -68,8 +76,10 @@ export function encodeCanvasPng(canvas: HTMLCanvasElement): Promise<Uint8Array>const id = nextId++;const worker = available[nextWorker++ % available.length];return new Promise((resolve, reject) => {- jobs.set(id, { worker, pixels, width, height, resolve, reject });+ const timeout = setTimeout(() => retireWorker(worker), 15000);+ jobs.set(id, { worker, pixels, width, height, resolve, reject, timeout });// Copied, not transferred: the pixels stay here for the inline fallback.- worker.postMessage({ id, pixels, width, height });+ try { worker.postMessage({ id, pixels, width, height }); }+ catch { retireWorker(worker); }});}diff --git a/skills/app-store-screenshots/template/src/lib/project-validation.ts b/skills/app-store-screenshots/template/src/lib/project-validation.tsindex 3fbd6a8..30bb4a5 100644--- a/skills/app-store-screenshots/template/src/lib/project-validation.ts+++ b/skills/app-store-screenshots/template/src/lib/project-validation.ts@@ -3,9 +3,19 @@ import { DEVICE_LABEL, LAYOUT_LABEL } from "./constants";const record = (value: unknown): value is Record<string, unknown> =>!!value && typeof value === "object" && !Array.isArray(value);+const finite = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value);+const localized = (value: unknown) => value === undefined || typeof value === "string" ||+ (record(value) && Object.values(value).every(text => typeof text === "string"));+const transform = (value: unknown) => record(value) &&+ [value.x, value.y, value.width, value.height].every(finite) &&+ (value.width as number) > 0 && (value.height as number) > 0 &&+ [value.rotation, value.zIndex].every(n => n === undefined || finite(n));+/** Reject malformed generated/edited JSON before it can crash or overwrite a deck. */export function projectValidationError(value: unknown): string | null {if (!record(value) || !record(value.slidesByDevice)) return "Project must contain a slidesByDevice object";+ if (value.schemaVersion !== undefined && value.schemaVersion !== 1 && value.schemaVersion !== 2) return "Unsupported project schema version";+ if (value.connectedCanvas !== undefined && typeof value.connectedCanvas !== "boolean") return "connectedCanvas must be a boolean";for (const key of ["appName", "themeId", "locale", "appIcon"]) {if (value[key] !== undefined && typeof value[key] !== "string") return `${key} must be a string`;}@@ -19,6 +29,7 @@ export function projectValidationError(value: unknown): string | null {value.locales.some(locale => typeof locale !== "string" || !/^[a-zA-Z0-9]+(?:[-_][a-zA-Z0-9]+)*$/.test(locale)) ||new Set(value.locales).size !== value.locales.length)) return "locales must be a list of unique locale codes";for (const [device, slides] of Object.entries(value.slidesByDevice)) {+ if (!Object.hasOwn(DEVICE_LABEL, device)) return `Unknown deck device: ${device}`;if (!Array.isArray(slides)) return `${device} deck must be an array`;const ids = new Set<string>();for (const slide of slides) {@@ -30,6 +41,26 @@ export function projectValidationError(value: unknown): string | null {for (const key of ["screenshot", "screenshotSecondary"]) {if (slide[key] !== undefined && typeof slide[key] !== "string") return `${device}: ${key} must be a string`;}+ if (!localized(slide.label) || !localized(slide.headline)) return `${device}: copy must be text or a locale-to-text object`;+ if (slide.inverted !== undefined && typeof slide.inverted !== "boolean") return `${device}: inverted must be a boolean`;+ if (slide.transforms !== undefined && (!record(slide.transforms) || Object.entries(slide.transforms).some(([key, value]) =>+ !["caption", "device", "deviceSecondary"].includes(key) || !transform(value)))) return `${device}: invalid element transform`;+ for (const key of ["textElements", "imageElements"] as const) {+ const elements = slide[key];+ if (elements === undefined) continue;+ if (!Array.isArray(elements)) return `${device}: ${key} must be an array`;+ const elementIds = new Set<string>();+ for (const element of elements) {+ if (!record(element) || typeof element.id !== "string" || !element.id.trim() || elementIds.has(element.id)) {+ return `${device}: ${key} must have unique non-empty ids`;+ }+ elementIds.add(element.id);+ if (!transform(element.transform)) return `${device}: invalid ${key} transform`;+ if (key === "textElements" && (!localized(element.text) ||+ [element.fontSize, element.fontWeight].some(n => n !== undefined && (!finite(n) || n <= 0)))) return `${device}: invalid text element`;+ if (key === "imageElements" && typeof element.src !== "string") return `${device}: image src must be a string`;+ }+ }}}return null;diff --git a/skills/app-store-screenshots/template/src/lib/request-body.ts b/skills/app-store-screenshots/template/src/lib/request-body.tsnew file mode 100644index 0000000..1981401--- /dev/null+++ b/skills/app-store-screenshots/template/src/lib/request-body.ts@@ -0,0 +1,39 @@+import { NextResponse } from "next/server";++/** Bound the stream itself: Content-Length is optional and caller-controlled. */+export async function readJsonBody(req: Request, maxBytes: number): Promise<+ { value: unknown; response?: never } | { value?: never; response: NextResponse }+> {+ // The unread remainder is cancelled. Do not advertise a reusable HTTP/1+ // connection that could reset the client's next (otherwise valid) request.+ const tooLarge = () => NextResponse.json({ ok: false, error: "Request body too large" }, { status: 413, headers: { Connection: "close" } });+ if (Number(req.headers.get("content-length")) > maxBytes) return { response: tooLarge() };+ const reader = req.body?.getReader();+ if (!reader) return { response: NextResponse.json({ ok: false, error: "Invalid JSON" }, { status: 400 }) };+ try {+ const chunks: Uint8Array[] = [];+ let length = 0;+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ length += value.byteLength;+ if (length > maxBytes) {+ void reader.cancel().catch(() => undefined);+ return { response: tooLarge() };+ }+ chunks.push(value);+ }+ return { value: JSON.parse(Buffer.concat(chunks).toString("utf8")) };+ } catch {+ return { response: NextResponse.json({ ok: false, error: "Invalid JSON" }, { status: 400 }) };+ } finally {+ reader.releaseLock();+ }+}++export function decodeBase64(value: string): Buffer | null {+ // Buffer.from silently ignores invalid characters and truncated quartets.+ if (!value || value.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(value)) return null;+ const bytes = Buffer.from(value, "base64");+ return bytes.toString("base64") === value ? bytes : null;+}diff --git a/skills/app-store-screenshots/template/src/lib/request-guard.ts b/skills/app-store-screenshots/template/src/lib/request-guard.tsindex 1174f65..b505c15 100644--- a/skills/app-store-screenshots/template/src/lib/request-guard.ts+++ b/skills/app-store-screenshots/template/src/lib/request-guard.ts@@ -1,52 +1,5 @@-/**- * Guards for the two API routes that WRITE TO DISK.- *- * THE EXPOSURE- * ------------- * `POST /api/upload` writes a file into `public/screenshots/uploaded/`, and- * `POST /api/project` OVERWRITES `app-store-screenshots.json`, which is- * normally git-tracked. Neither had an origin check.- *- * While the dev server is running, any page in any other tab can send a- * cross-origin POST. If that request is a CORS-"simple" request — which- * `Content-Type: text/plain` makes it — the browser sends it WITH NO- * PREFLIGHT. The attacker cannot read the response, and does not need to: the- * write has already happened. `Request.json()` ignores the declared- * Content-Type and parses the body anyway, so a text/plain body containing- * JSON is accepted.- *- * Realistic harm: a malicious page plants files inside the user's repository,- * or blanks the canonical project state, while they have the editor open.- *- * "It only listens on localhost" is NOT a defence. The victim's own browser is- * inside localhost, and it is the browser that makes the request.- *- * THE GUARD- * ---------- * `rejectCrossSiteWrite` applies three checks, in increasing specificity:- *- * 1. Require `Content-Type: application/json`. This is the load-bearing one.- * That header is NOT CORS-simple, so requiring it forces the browser to- * send a preflight, and the preflight fails because these routes send no- * CORS headers. This alone closes the no-preflight hole.- * 2. Reject a non-loopback `Origin`.- * 3. Reject a cross-site `Sec-Fetch-Site`.- *- * Checks 2 and 3 SKIP WHEN THE HEADER IS ABSENT. That is deliberate, and it is- * not a hole: the attack vector here is the victim's browser, and a browser- * cannot be made to omit those headers on a cross-origin request. Skipping on- * absence is what keeps curl, scripts and tests working.- *- * `sniffImageType` closes a separate issue: the stored file extension came- * from the MIME string inside the data URL, which the caller writes by hand,- * so arbitrary bytes could be stored as `<hash>.png`. This is not a path- * traversal — the filename is a content hash plus a whitelisted extension —- * and Next serves `public/` by extension, so it cannot be made to execute.- * The realistic harm is junk that looks like an image getting committed.- */--const LOOPBACK = /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/i;-+/** Disk writes require JSON and the editor's own origin. Headerless CLI+ * requests remain supported; these checks do not provide network authentication. */export type GuardFailure = { error: string; status: number };/**@@ -57,19 +10,23 @@ export function rejectCrossSiteWrite(req: Request): GuardFailure | null {// 1. Content-Type must be application/json. Not CORS-simple, so a// cross-origin caller is forced into a preflight that fails.const contentType = req.headers.get("content-type") || "";- if (!contentType.toLowerCase().split(";")[0].trim().startsWith("application/json")) {+ if (contentType.toLowerCase().split(";")[0].trim() !== "application/json") {return { error: "Content-Type must be application/json", status: 415 };}- // 2. Origin, when present, must be loopback.+ // 2. Another local app (including a different port) is a different origin.const origin = req.headers.get("origin");- if (origin && !LOOPBACK.test(origin)) {+ // Next can canonicalize req.url to localhost even when the browser used+ // 127.0.0.1 or a LAN address. Host is the browser's actual request authority.+ const target = new URL(req.url);+ target.host = req.headers.get("host") || target.host;+ if (origin && origin !== target.origin) {return { error: "Cross-origin write rejected", status: 403 };}// 3. Sec-Fetch-Site, when present, must not be cross-site.const site = req.headers.get("sec-fetch-site");- if (site && site !== "same-origin" && site !== "same-site" && site !== "none") {+ if (site && site !== "same-origin" && site !== "none") {return { error: "Cross-site write rejected", status: 403 };}diff --git a/skills/app-store-screenshots/template/src/lib/serve-asset.ts b/skills/app-store-screenshots/template/src/lib/serve-asset.tsnew file mode 100644index 0000000..908ae57--- /dev/null+++ b/skills/app-store-screenshots/template/src/lib/serve-asset.ts@@ -0,0 +1,21 @@+import { promises as fs } from "node:fs";+import path from "node:path";+import { NextResponse } from "next/server";++/** Next's production public-file index excludes uploads created after startup. */+export async function serveAsset(directory: string, filename: string, types: Record<string, string>) {+ const match = /^[a-f0-9]{16}\.([a-z0-9]+)$/.exec(filename);+ if (!match || !Object.hasOwn(types, match[1])) return new NextResponse(null, { status: 404 });+ try {+ const bytes = await fs.readFile(path.join(process.cwd(), "public", directory, filename));+ return new NextResponse(new Uint8Array(bytes), { headers: {+ "Content-Type": types[match[1]],+ "Content-Length": String(bytes.length),+ "Cache-Control": "public, max-age=31536000, immutable",+ "X-Content-Type-Options": "nosniff",+ } });+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return new NextResponse(null, { status: 404 });+ return NextResponse.json({ ok: false, error: "Asset could not be read" }, { status: 500 });+ }+}diff --git a/skills/app-store-screenshots/template/src/lib/storage.ts b/skills/app-store-screenshots/template/src/lib/storage.tsindex df939c7..64127dc 100644--- a/skills/app-store-screenshots/template/src/lib/storage.ts+++ b/skills/app-store-screenshots/template/src/lib/storage.ts@@ -191,16 +191,16 @@ function loadFromLocalStorage(): ProjectState | null {}async function loadFromFile(): Promise<- { ok: true; state: ProjectState | null } | { ok: false; error: string }+ { ok: true; state: ProjectState | null; revision: string | null } | { ok: false; error: string }> {if (typeof window === "undefined") return { ok: false, error: "Window is not available" };try {- const resp = await fetch("/api/project", { cache: "no-store" });- if (!resp.ok) return { ok: false, error: `HTTP ${resp.status}` };- const json = (await resp.json()) as { ok: boolean; state: Partial<ProjectState> | null };- if (!json.ok) return { ok: false, error: "Project response was not ok" };- if (!json.state) return { ok: true, state: null };- return { ok: true, state: mergeWithDefaults(json.state) };+ const resp = await fetch("/api/project", { cache: "no-store", signal: AbortSignal.timeout(15000) });+ const json = (await resp.json()) as { ok: boolean; state: Partial<ProjectState> | null; error?: string };+ if (!resp.ok || !json.ok) return { ok: false, error: json.error || `HTTP ${resp.status}` };+ const revision = resp.headers.get("etag");+ if (!json.state) return { ok: true, state: null, revision };+ return { ok: true, state: mergeWithDefaults(json.state), revision };} catch (error) {return { ok: false, error: error instanceof Error ? error.message : "Project file could not be loaded" };}@@ -217,20 +217,17 @@ function saveToLocalStorage(state: ProjectState): { ok: true } | { ok: false; er}}-async function saveToFile(state: ProjectState): Promise<{ ok: true } | { ok: false; error: string }> {- if (typeof window === "undefined") return { ok: true };+async function saveToFile(state: ProjectState, revision: string | null): Promise<{ ok: true; revision: string | null } | { ok: false; error: string }> {try {const resp = await fetch("/api/project", {method: "POST",- headers: { "content-type": "application/json" },+ headers: { "content-type": "application/json", ...(revision ? { "if-match": revision } : {}) },body: JSON.stringify(state),+ signal: AbortSignal.timeout(15000),});- if (!resp.ok) {- return { ok: false, error: `HTTP ${resp.status}` };- }const json = (await resp.json()) as { ok: boolean; error?: string };- if (!json.ok) return { ok: false, error: json.error || "Unknown error" };- return { ok: true };+ if (!resp.ok || !json.ok) return { ok: false, error: json.error || `HTTP ${resp.status}` };+ return { ok: true, revision: resp.headers.get("etag") };} catch (e) {return { ok: false, error: e instanceof Error ? e.message : String(e) };}@@ -252,6 +249,9 @@ export function useProject() {const stateRef = useRef(state);const saveQueue = useRef(Promise.resolve());const saveRevision = useRef(0);+ const fileRevision = useRef<string | null>(null);+ const unsaved = useRef(false);+ const [retry, setRetry] = useState(0);// Run updates once, outside React render/updater replay. Async callbacks also// see the latest state before React has committed the next render.@@ -277,6 +277,7 @@ export function useProject() {const fromFile = await loadFromFile();if (cancelled) return;if (fromFile.ok) {+ fileRevision.current = fromFile.revision;if (fromFile.state) {commit(fromFile.state);} else {@@ -298,6 +299,17 @@ export function useProject() {};}, [commit]);+ // A refresh inside the debounce window must not silently discard edits.+ useEffect(() => {+ const warn = (event: BeforeUnloadEvent) => {+ if (!unsaved.current) return;+ event.preventDefault();+ event.returnValue = "";+ };+ window.addEventListener("beforeunload", warn);+ return () => window.removeEventListener("beforeunload", warn);+ }, []);+// Debounced autosave to BOTH localStorage (fast, offline) and file (git-trackable).useEffect(() => {if (!hydrated || !fileReady) return;@@ -309,11 +321,14 @@ export function useProject() {// Serialize requests so a slow older write cannot overwrite a newer edit.saveQueue.current = saveQueue.current.then(async () => {if (revision !== saveRevision.current) return;- const fileResult = await saveToFile(state);+ const fileResult = await saveToFile(state, fileRevision.current);+ // Advance even if another edit arrived while this request was in flight.+ if (fileResult.ok) fileRevision.current = fileResult.revision;if (revision !== saveRevision.current) return;if (!fileResult.ok) {setSaveError(`File save failed: ${fileResult.error}`);} else {+ unsaved.current = false;setSavedAt(Date.now());setSaveError(localResult.ok ? null : localResult.error);}@@ -322,7 +337,7 @@ export function useProject() {return () => {if (timer.current) clearTimeout(timer.current);};- }, [state, hydrated, fileReady]);+ }, [state, hydrated, fileReady, retry]);// `history: false` is for navigation (device, orientation, locale): it isn't// an edit, so it neither takes an undo step nor clears redo. Undo still@@ -332,6 +347,7 @@ export function useProject() {const prev = stateRef.current;const next = applyUpdater(updater, prev);if (next === prev) return;+ unsaved.current = true;if (options?.history === false) {// Navigation is a boundary: edits to another deck must not coalesce.lastPushAt.current = 0;@@ -351,6 +367,7 @@ export function useProject() {const prev = pastRef.current.pop();if (prev === undefined) return;futureRef.current.push(stateRef.current);+ unsaved.current = true;lastPushAt.current = 0;commit(prev);}, [commit]);@@ -359,6 +376,7 @@ export function useProject() {const next = futureRef.current.pop();if (next === undefined) return;pastRef.current.push(stateRef.current);+ unsaved.current = true;lastPushAt.current = 0;commit(next);}, [commit]);@@ -385,6 +403,7 @@ export function useProject() {hydrated,savedAt,saveError,+ retrySave: fileReady ? () => setRetry((value) => value + 1) : undefined,reset,resetDevice,undo,diff --git a/skills/app-store-screenshots/template/src/lib/write-asset.ts b/skills/app-store-screenshots/template/src/lib/write-asset.tsnew file mode 100644index 0000000..7b59e3b--- /dev/null+++ b/skills/app-store-screenshots/template/src/lib/write-asset.ts@@ -0,0 +1,13 @@+import { randomUUID } from "node:crypto";+import { promises as fs } from "node:fs";++/** A concurrent upload/GET must never see a partially written asset. */+export async function writeAsset(filename: string, bytes: Buffer) {+ const temporary = `${filename}.${randomUUID()}.tmp`;+ try {+ await fs.writeFile(temporary, bytes);+ await fs.rename(temporary, filename);+ } finally {+ await fs.unlink(temporary).catch(() => undefined);+ }+}