A lightweight design agent built with libfx. Describe a page and an agent writes it as one HTML file.
TypeScript
Protect private asset reads and failed uploads
Esteban Suarez0d3123b4370e
diff --git a/app/api/artifact-image/route.ts b/app/api/artifact-image/route.tsindex 1472d39..f636d75 100644--- a/app/api/artifact-image/route.ts+++ b/app/api/artifact-image/route.ts@@ -1,6 +1,7 @@import { verifyArtifactImage } from '../../../lib/artifact-image'import { assetReference } from '../../../lib/design-artifact'import { readDesignAsset } from '../../../lib/design-assets'+import { readDesignAssets } from '../../../lib/journal'import { cachedRemoteImage } from '../../../lib/remote-image-cache'import { withSessionRoute } from '../../../lib/route-auth'import { log } from '../../../lib/session'@@ -14,10 +15,22 @@ export const GET = withSessionRoute(async (request, { id: sessionId }) => {const params = new URL(request.url).searchParamsconst url = verifyArtifactImage(sessionId, params.get('u'), params.get('sig'))if (!url) return new Response(null, { status: 404, headers: { 'cache-control': 'private, no-store' } })+ const asset = assetReference(url)+ const handle = asset?.slice('fx0-asset:'.length)+ // Handles are immutable. A kept attachment must revalidate through ownership and+ // the manifest, even after logout or deletion, but a 304 needs no Blob download.+ const etag = asset ? `"${asset}"` : null+ const cacheHeaders: Record<string, string> = etag+ ? { 'cache-control': 'private, no-cache', etag }+ : { 'cache-control': 'private, max-age=86400' }let image: { bytes: Buffer; mimeType: string } | nulltry {- const asset = assetReference(url)- if (asset) image = await readDesignAsset(sessionId, asset.slice('fx0-asset:'.length))+ if (handle && etag && request.headers.get('if-none-match') === etag) {+ const known = await readDesignAssets(sessionId, [handle])+ if (!known.has(handle)) return new Response(null, { status: 404, headers: { 'cache-control': 'private, no-store' } })+ return new Response(null, { status: 304, headers: cacheHeaders })+ }+ if (handle) image = await readDesignAsset(sessionId, handle)else {const data = await cachedRemoteImage(url)image = { bytes: Buffer.from(data.slice(data.indexOf(',') + 1), 'base64'), mimeType: data.slice('data:'.length, data.indexOf(';')) }@@ -30,7 +43,7 @@ export const GET = withSessionRoute(async (request, { id: sessionId }) => {return new Response(new Uint8Array(image.bytes), {headers: {'content-type': image.mimeType,- 'cache-control': 'private, max-age=86400',+ ...cacheHeaders,'content-security-policy': "default-src 'none'; sandbox",'x-content-type-options': 'nosniff',},diff --git a/app/api/prompt/route.ts b/app/api/prompt/route.tsindex cc3fe10..571f817 100644--- a/app/api/prompt/route.ts+++ b/app/api/prompt/route.ts@@ -11,7 +11,7 @@ import { trialEnabled, trialIpHash, trialStore, type TrialCredential, type Trialimport { TRIAL_MODEL, usesFreePrompts } from '../../../lib/trial-policy'import { DEFAULT_MODEL, log } from '../../../lib/session'import { validatePromptImages, validatePromptPreviews } from '../../../lib/prompt-images'-import { DesignAssetLimitError, storeDesignAssets } from '../../../lib/design-assets'+import { DesignAssetLimitError, retryDesignAssetCleanup, storeDesignAssets } from '../../../lib/design-assets'import { PROMPT_TEXT_LIMIT_ERROR, PROMPT_TEXT_MAX_BYTES, promptTextBytes } from '../../../lib/prompt-limits'export const maxDuration = 800@@ -110,6 +110,7 @@ export const POST = withPromptRoute(async (request, context) => {// so nothing is stored for a prompt that could not run.let assets: string[] = []if (images) {+ after(() => retryDesignAssetCleanup().catch(() => console.error('[fx0] asset cleanup retry unavailable')))assertPromptFunding(activated.host, funding, 'kind' in session ? undefined : session)assets = await storeDesignAssets(activated.id, user.id, images)}diff --git a/app/api/session/route.ts b/app/api/session/route.tsindex 3a93028..0904009 100644--- a/app/api/session/route.ts+++ b/app/api/session/route.ts@@ -1,5 +1,6 @@import { readTranscript } from '../../../lib/journal'import { deleteDesignSession } from '../../../lib/agent'+import { retryDesignAssetCleanup } from '../../../lib/design-assets'import { removeOwnedSession } from '../../../lib/accounts'import { withSessionRoute } from '../../../lib/route-auth'import { after } from 'next/server.js'@@ -11,6 +12,7 @@ export const GET = withSessionRoute(async (_request, { id }) => {})export const DELETE = withSessionRoute(async (_request, { host, id, user }) => {+ after(() => retryDesignAssetCleanup().catch(() => console.error('[fx0] asset cleanup retry unavailable')))// Runtime owns cancellation, config/agent-start fencing, and durable Redis// deletion. An exception or busy result retains Neon ownership for retry.if (!await deleteDesignSession(host)) {diff --git a/lib/design-assets.ts b/lib/design-assets.tsindex da48c30..0141197 100644--- a/lib/design-assets.ts+++ b/lib/design-assets.ts@@ -1,6 +1,10 @@import { randomBytes } from 'node:crypto'import { del, get, list, put } from '@vercel/blob'-import { MAX_CHAT_ASSETS, MAX_DAILY_ASSETS, readDesignAssets, recordDesignAssets, releaseDesignAssets, reserveDesignAssets } from './journal'+import {+ MAX_CHAT_ASSETS, MAX_DAILY_ASSETS, finishDesignAssetCleanup, pendingDesignAssetCleanups,+ queueDesignAssetCleanup, readDesignAssets, recordDesignAssets, reserveDesignAssets,+ type DesignAssetCleanup,+} from './journal'import type { PromptImage } from './prompt-images'// Images a message attached, kept in fx0's private Blob store so a design can show them@@ -16,13 +20,6 @@ export interface DesignAssetStore {const BLOB: DesignAssetStore = { put, get, del, list }-export interface DesignAssetQuota {- reserve: typeof reserveDesignAssets- release: typeof releaseDesignAssets-}--const QUOTA: DesignAssetQuota = { reserve: reserveDesignAssets, release: releaseDesignAssets }-/** A message that would pass the per-chat or per-day image cap. Nothing was stored. */export class DesignAssetLimitError extends Error {constructor(limit: 'chat' | 'daily') {@@ -38,33 +35,55 @@ const pathname = (sessionId: string, handle: string) => `chats/${sessionId}/${ha* Stores a message's images and records them for the chat, all or none, within the* chat's and the user's caps. Returns their handles in order.*/-export async function storeDesignAssets(sessionId: string, userId: string, images: PromptImage[], store = BLOB, quota = QUOTA): Promise<string[]> {+export async function storeDesignAssets(sessionId: string, userId: string, images: PromptImage[], store = BLOB): Promise<string[]> {if (!images.length) return []- const reserved = await quota.reserve(sessionId, userId, images.length)+ const reservedAt = Date.now()+ const reserved = await reserveDesignAssets(sessionId, userId, images.length, reservedAt)if (reserved !== 'ok') throw new DesignAssetLimitError(reserved)+ const assets = images.map((image) => ({+ handle: randomBytes(18).toString('base64url'),+ mimeType: image.mimeType,+ bytes: Buffer.from(image.data, 'base64'),+ }))+ const handles = assets.map(({ handle }) => handle)try {- return await storeReserved(sessionId, images, store)+ // Wait for every put before rolling back: a sibling can still be in flight when+ // another fails. Delete every attempted path, including an ambiguous timeout.+ const results = await Promise.allSettled(assets.map(({ handle, mimeType, bytes }) =>+ store.put(pathname(sessionId, handle), bytes, { access: 'private', contentType: mimeType, addRandomSuffix: false })))+ if (results.some((result) => result.status === 'rejected')) throw new Error('Unable to store the attached images')+ await recordDesignAssets(sessionId, assets.map(({ handle, mimeType, bytes }) => ({ handle, mimeType, bytes: bytes.length })))+ return handles} catch (error) {- await quota.release(sessionId, userId, images.length).catch(() => {})+ const cleanup = { sessionId, userId, handles, reservedAt }+ try {+ await queueDesignAssetCleanup(cleanup)+ } catch {+ console.error('[fx0] asset cleanup persistence failed', { sessionId })+ }+ try {+ await store.del(handles.map((handle) => pathname(sessionId, handle)))+ // Complete atomically even if the enqueue response was lost. The receipt+ // prevents a delayed enqueue or another worker from refunding this twice.+ await finishDesignAssetCleanup(cleanup)+ } catch {+ console.error('[fx0] asset cleanup pending', { sessionId })+ }throw error}}-async function storeReserved(sessionId: string, images: PromptImage[], store: DesignAssetStore): Promise<string[]> {- const assets = images.map((image) => ({- handle: randomBytes(18).toString('base64url'),- mimeType: image.mimeType,- bytes: Buffer.from(image.data, 'base64'),+/** Retry failed rollbacks without losing their records or refunding quota twice. */+export async function retryDesignAssetCleanup(store = BLOB): Promise<void> {+ const pending = await pendingDesignAssetCleanups()+ await Promise.all(pending.map(async (cleanup: DesignAssetCleanup) => {+ try {+ await store.del(cleanup.handles.map((handle) => pathname(cleanup.sessionId, handle)))+ await finishDesignAssetCleanup(cleanup)+ } catch {+ console.error('[fx0] asset cleanup pending', { sessionId: cleanup.sessionId })+ }}))- const results = await Promise.allSettled(assets.map(({ handle, mimeType, bytes }) =>- store.put(pathname(sessionId, handle), bytes, { access: 'private', contentType: mimeType, addRandomSuffix: false })))- if (results.some((result) => result.status === 'rejected')) {- const stored = assets.filter((_, index) => results[index].status === 'fulfilled').map(({ handle }) => pathname(sessionId, handle))- if (stored.length) await store.del(stored).catch(() => {})- throw new Error('Unable to store the attached images')- }- await recordDesignAssets(sessionId, assets.map(({ handle, mimeType, bytes }) => ({ handle, mimeType, bytes: bytes.length })))- return assets.map(({ handle }) => handle)}/** One of the chat's images, or null when the chat never received that handle. */diff --git a/lib/journal.ts b/lib/journal.tsindex 78514f5..61b5a01 100644--- a/lib/journal.ts+++ b/lib/journal.ts@@ -587,6 +587,7 @@ export const MAX_CHAT_ASSETS = 50export const MAX_DAILY_ASSETS = 100const RESERVE_ASSETS = `+if redis.call('EXISTS', KEYS[3]) == 1 then return 'deleted' endlocal count = tonumber(ARGV[1])local chat = tonumber(redis.call('GET', KEYS[1]) or '0')local daily = tonumber(redis.call('GET', KEYS[2]) or '0')@@ -609,17 +610,79 @@ return 1const dailyAssetKey = (userId: string, now: number) => prefixed(`user:${userId}:assets:${new Date(now).toISOString().slice(0, 10)}`)export async function reserveDesignAssets(sessionId: string, userId: string, count: number, now = Date.now()): Promise<'ok' | 'chat' | 'daily'> {- return redis().eval<string[], 'ok' | 'chat' | 'daily'>(RESERVE_ASSETS,- [key(sessionId, 'asset-count'), dailyAssetKey(userId, now)], [String(count), String(MAX_CHAT_ASSETS), String(MAX_DAILY_ASSETS)])+ const result = await redis().eval<string[], 'ok' | 'chat' | 'daily' | 'deleted'>(RESERVE_ASSETS,+ [key(sessionId, 'asset-count'), dailyAssetKey(userId, now), key(sessionId, 'deleting')], [String(count), String(MAX_CHAT_ASSETS), String(MAX_DAILY_ASSETS)])+ if (result === 'deleted') throw new SessionCleanupError()+ return result}export async function releaseDesignAssets(sessionId: string, userId: string, count: number, now = Date.now()): Promise<void> {await redis().eval<string[], number>(RELEASE_ASSETS, [key(sessionId, 'asset-count'), dailyAssetKey(userId, now)], [String(count)])}+const RECORD_ASSETS = `+if redis.call('EXISTS', KEYS[2]) == 1 then return 0 end+for handle, asset in pairs(cjson.decode(ARGV[1])) do redis.call('HSET', KEYS[1], handle, cjson.encode(asset)) end+return 1+`+export async function recordDesignAssets(sessionId: string, assets: { handle: string; mimeType: string; bytes: number }[]): Promise<void> {if (!assets.length) return- await redis().hset(key(sessionId, 'assets'), Object.fromEntries(assets.map(({ handle, mimeType, bytes }) => [handle, JSON.stringify({ mimeType, bytes })])))+ const recorded = await redis().eval<unknown[], number>(RECORD_ASSETS,+ [key(sessionId, 'assets'), key(sessionId, 'deleting')],+ [JSON.stringify(Object.fromEntries(assets.map(({ handle, mimeType, bytes }) => [handle, { mimeType, bytes }])))])+ if (recorded !== 1) throw new SessionCleanupError()+}++// Failed uploads retain their quota until their files have actually been removed.+// This outbox survives request failures and chat deletion; later asset writes retry+// a bounded batch. Completion removes the manifest entries and refunds exactly once.+export interface DesignAssetCleanup { sessionId: string; userId: string; handles: string[]; reservedAt: number }++const assetCleanupKey = () => prefixed('asset-cleanup')+const assetCleanupReceipt = (cleanup: DesignAssetCleanup) => prefixed(`asset-cleanup-done:${createHash('sha256').update(JSON.stringify(cleanup)).digest('hex')}`)++const QUEUE_ASSET_CLEANUP = `+if redis.call('EXISTS', KEYS[2]) == 1 then return 0 end+redis.call('ZADD', KEYS[1], ARGV[1], ARGV[2])+return 1+`++export async function queueDesignAssetCleanup(cleanup: DesignAssetCleanup): Promise<void> {+ await redis().eval<unknown[], number>(QUEUE_ASSET_CLEANUP,+ [assetCleanupKey(), assetCleanupReceipt(cleanup)], [String(Date.now()), JSON.stringify(cleanup)])+}++const PENDING_ASSET_CLEANUPS = `+local pending = redis.call('ZRANGE', KEYS[1], 0, 9)+for _, job in ipairs(pending) do redis.call('ZADD', KEYS[1], ARGV[1], job) end+return pending+`++export async function pendingDesignAssetCleanups(): Promise<DesignAssetCleanup[]> {+ // Rotate attempted jobs behind newer ones without recreating a completed job+ // after an ambiguous completion response. Overlapping workers are safe below.+ return redis().eval<unknown[], DesignAssetCleanup[]>(PENDING_ASSET_CLEANUPS, [assetCleanupKey()], [String(Date.now())])+}++const FINISH_ASSET_CLEANUP = `+if not redis.call('SET', KEYS[5], '1', 'NX', 'EX', 172800) then return 0 end+redis.call('ZREM', KEYS[4], ARGV[1])+local handles = cjson.decode(ARGV[2])+for _, handle in ipairs(handles) do redis.call('HDEL', KEYS[3], handle) end+local count = #handles+for index = 1, 2 do+ if tonumber(redis.call('GET', KEYS[index]) or '0') >= count then redis.call('DECRBY', KEYS[index], count) end+end+return 1+`++export async function finishDesignAssetCleanup(cleanup: DesignAssetCleanup): Promise<void> {+ // The receipt outlives any request retry. Even an enqueue whose response was+ // lost cannot recreate this job or refund a completed rollback a second time.+ await redis().eval<unknown[], number>(FINISH_ASSET_CLEANUP,+ [key(cleanup.sessionId, 'asset-count'), dailyAssetKey(cleanup.userId, cleanup.reservedAt), key(cleanup.sessionId, 'assets'), assetCleanupKey(), assetCleanupReceipt(cleanup)],+ [JSON.stringify(cleanup), JSON.stringify(cleanup.handles)])}export async function readDesignAssets(sessionId: string, handles?: string[]): Promise<Map<string, DesignAsset>> {diff --git a/tests/design-assets.test.mjs b/tests/design-assets.test.mjsindex d054da9..3e32d71 100644--- a/tests/design-assets.test.mjs+++ b/tests/design-assets.test.mjs@@ -5,18 +5,42 @@ import { registerHooks } from 'node:module'// design-assets keeps its manifest in the chat journal; here that is an in-memory map,// and the Blob store is a fake passed in, so no network or Redis is involved.const manifests = new Map()-globalThis.__assetManifests = manifests+const jobs = new Map()+const completed = new Set()+const calls = []+const journal = { manifests, jobs, completed, calls }+globalThis.__assetJournal = journal+test.beforeEach(() => {+ manifests.clear(); jobs.clear(); completed.clear(); calls.length = 0+ journal.reserve = async (...args) => { calls.push(['reserve', ...args]); return 'ok' }+ journal.record = async (id, assets) => {+ const map = manifests.get(id) ?? new Map()+ for (const a of assets) map.set(a.handle, { mimeType: a.mimeType, bytes: a.bytes })+ manifests.set(id, map)+ }+ journal.queue = async (job) => { if (!completed.has(JSON.stringify(job))) jobs.set(JSON.stringify(job), job) }+})registerHooks({resolve(specifier, context, next) {if (specifier === './journal' && context.parentURL?.endsWith('/lib/design-assets.ts')) {return { url: `data:text/javascript,${encodeURIComponent(`- const m = globalThis.__assetManifests- export async function recordDesignAssets(id, assets) { const map = m.get(id) ?? new Map(); for (const a of assets) map.set(a.handle, { mimeType: a.mimeType, bytes: a.bytes }); m.set(id, map) }- export async function readDesignAssets(id, handles) { const map = m.get(id) ?? new Map(); return new Map([...map].filter(([h]) => !handles || handles.includes(h))) }+ const j = globalThis.__assetJournal+ export const recordDesignAssets = (...args) => j.record(...args)+ export async function readDesignAssets(id, handles) { const map = j.manifests.get(id) ?? new Map(); return new Map([...map].filter(([h]) => !handles || handles.includes(h))) }export const MAX_CHAT_ASSETS = 50export const MAX_DAILY_ASSETS = 100- export async function reserveDesignAssets() { return 'ok' }- export async function releaseDesignAssets() {}+ export const reserveDesignAssets = (...args) => j.reserve(...args)+ export async function releaseDesignAssets(...args) { j.calls.push(['release', ...args]) }+ export const queueDesignAssetCleanup = (...args) => j.queue(...args)+ export async function pendingDesignAssetCleanups() { return [...j.jobs.values()] }+ export async function forgetDesignAssets(id, handles) { for (const h of handles) j.manifests.get(id)?.delete(h) }+ export async function finishDesignAssetCleanup(job) {+ if (j.completed.has(JSON.stringify(job))) return+ j.completed.add(JSON.stringify(job))+ j.jobs.delete(JSON.stringify(job))+ await forgetDesignAssets(job.sessionId, job.handles)+ await releaseDesignAssets(job.sessionId, job.userId, job.handles.length, job.reservedAt)+ }`)}`, shortCircuit: true }}return next(specifier, context)@@ -24,7 +48,7 @@ registerHooks({})process.env.SESSION_SECRET ??= 'deterministic-design-assets-test-secret-32+'-const { storeDesignAssets, readDesignAsset, deleteDesignAssets, DesignAssetLimitError } = await import('../lib/design-assets.ts')+const { storeDesignAssets, readDesignAsset, deleteDesignAssets, retryDesignAssetCleanup, DesignAssetLimitError } = await import('../lib/design-assets.ts')const { validateDesignArtifactHtml, rewriteRemoteImages, BLANK_IMAGE } = await import('../lib/design-artifact.ts')const { markRemoteImages } = await import('../lib/remote-image.ts')const { artifactImageSrc, verifyArtifactImage } = await import('../lib/artifact-image.ts')@@ -32,7 +56,6 @@ const { artifactImageSrc, verifyArtifactImage } = await import('../lib/artifact-const PNG = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='const CHAT = '11111111-1111-4111-8111-111111111111'const USER = 'user_a'-const OPEN = { reserve: async () => 'ok', release: async () => {} }const HANDLE = 'AbCdEfGhIjKlMnOpQrStUvWx'const doc = (body, head = '') => `<!doctype html><html><head>${head}</head><body>${body}</body></html>`@@ -66,7 +89,7 @@ test('a message\'s images are stored privately and recorded for the chat, all ormanifests.clear()const store = fakeStore()const images = [{ type: 'image', data: PNG, mimeType: 'image/png' }, { type: 'image', data: PNG, mimeType: 'image/png' }]- const handles = await storeDesignAssets(CHAT, USER, images, store, OPEN)+ const handles = await storeDesignAssets(CHAT, USER, images, store)assert.equal(handles.length, 2)for (const handle of handles) {assert.match(handle, /^[A-Za-z0-9_-]{24}$/)@@ -76,7 +99,7 @@ test('a message\'s images are stored privately and recorded for the chat, all ormanifests.clear()const failing = fakeStore({ failOn: 1 })- await assert.rejects(storeDesignAssets(CHAT, USER, images, failing, OPEN), /Unable to store/)+ await assert.rejects(storeDesignAssets(CHAT, USER, images, failing), /Unable to store/)assert.equal(failing.files.size, 0, 'the image that was stored is removed again')assert.equal(manifests.size, 0, 'nothing is recorded')})@@ -84,27 +107,25 @@ test('a message\'s images are stored privately and recorded for the chat, all ortest('the chat and daily caps are taken before anything is stored, and given back if storing fails', async () => {manifests.clear()const image = { type: 'image', data: PNG, mimeType: 'image/png' }- const calls = []- const quota = (answer) => ({- reserve: async (...args) => { calls.push(['reserve', ...args]); return answer },- release: async (...args) => { calls.push(['release', ...args]) },- })for (const [limit, message] of [['chat', /already has its 50 attached images/], ['daily', /up to 100 images a day/]]) {const store = fakeStore()calls.length = 0- await assert.rejects(storeDesignAssets(CHAT, USER, [image, image], store, quota(limit)), (error) => error instanceof DesignAssetLimitError && message.test(error.message))+ journal.reserve = async (...args) => { calls.push(['reserve', ...args]); return limit }+ await assert.rejects(storeDesignAssets(CHAT, USER, [image, image], store), (error) => error instanceof DesignAssetLimitError && message.test(error.message))assert.equal(store.files.size, 0, 'nothing stored past a cap')- assert.deepEqual(calls, [['reserve', CHAT, USER, 2]])+ assert.deepEqual(calls.map((call) => call.slice(0, 4)), [['reserve', CHAT, USER, 2]])}calls.length = 0- await assert.rejects(storeDesignAssets(CHAT, USER, [image, image], fakeStore({ failOn: 0 }), quota('ok')), /Unable to store/)- assert.deepEqual(calls, [['reserve', CHAT, USER, 2], ['release', CHAT, USER, 2]])+ journal.reserve = async (...args) => { calls.push(['reserve', ...args]); return 'ok' }+ await assert.rejects(storeDesignAssets(CHAT, USER, [image, image], fakeStore({ failOn: 0 })), /Unable to store/)+ assert.deepEqual(calls.map((call) => call.slice(0, 4)), [['reserve', CHAT, USER, 2], ['release', CHAT, USER, 2]])+ assert.equal(calls[0][4], calls[1][4], 'the refund uses the reservation day')})test('an image is read only for the chat that received it', async () => {manifests.clear()const store = fakeStore()- const [handle] = await storeDesignAssets(CHAT, USER, [{ type: 'image', data: PNG, mimeType: 'image/png' }], store, OPEN)+ const [handle] = await storeDesignAssets(CHAT, USER, [{ type: 'image', data: PNG, mimeType: 'image/png' }], store)const image = await readDesignAsset(CHAT, handle, store)assert.deepEqual({ mimeType: image.mimeType, bytes: image.bytes.toString('base64') }, { mimeType: 'image/png', bytes: PNG })assert.equal(await readDesignAsset('22222222-2222-4222-8222-222222222222', handle, store), null)@@ -115,12 +136,99 @@ test('deleting a chat removes all its files, page by page, and no other chat\'s'manifests.clear()const store = fakeStore()const image = { type: 'image', data: PNG, mimeType: 'image/png' }- await storeDesignAssets(CHAT, USER, [image, image, image, image, image], store, OPEN)- const [other] = await storeDesignAssets('33333333-3333-4333-8333-333333333333', USER, [image], store, OPEN)+ await storeDesignAssets(CHAT, USER, [image, image, image, image, image], store)+ const [other] = await storeDesignAssets('33333333-3333-4333-8333-333333333333', USER, [image], store)await deleteDesignAssets(CHAT, store)assert.deepEqual([...store.files.keys()], [`chats/33333333-3333-4333-8333-333333333333/${other}`])})+test('a failed manifest write rolls back every attempted file and refunds only after removal', async () => {+ const store = fakeStore()+ const record = journal.record+ journal.record = async (...args) => { await record(...args); throw new Error('manifest response lost') }+ const image = { type: 'image', data: PNG, mimeType: 'image/png' }+ await assert.rejects(storeDesignAssets(CHAT, USER, [image, image], store), /manifest response lost/)+ assert.equal(store.files.size, 0)+ assert.equal(manifests.get(CHAT).size, 0, 'an ambiguously committed manifest is removed too')+ assert.equal(jobs.size, 0)+ assert.equal(calls.filter(([name]) => name === 'release').length, 1)+})++test('a put with a lost response is removed along with its successful siblings', async () => {+ const store = fakeStore()+ const put = store.put+ store.put = async (...args) => { await put(...args); throw new Error('put response lost') }+ const image = { type: 'image', data: PNG, mimeType: 'image/png' }+ await assert.rejects(storeDesignAssets(CHAT, USER, [image, image], store), /Unable to store/)+ assert.equal(store.files.size, 0)+ assert.equal(jobs.size, 0)+})++test('a refused late manifest commit removes uploads that completed after chat deletion', async () => {+ const store = fakeStore()+ let finishUpload+ const wait = new Promise((resolve) => { finishUpload = resolve })+ let uploadStarted+ const started = new Promise((resolve) => { uploadStarted = resolve })+ const put = store.put+ store.put = async (...args) => { uploadStarted(); await wait; return put(...args) }+ let deleted = false+ journal.record = async () => { assert.equal(deleted, true); throw new Error('chat deleted') }+ const pending = storeDesignAssets(CHAT, USER, [{ type: 'image', data: PNG, mimeType: 'image/png' }], store)+ const refused = assert.rejects(pending, /chat deleted/)+ await started+ deleted = true+ await deleteDesignAssets(CHAT, store)+ finishUpload()+ await refused+ assert.equal(store.files.size, 0)+ assert.equal(manifests.size, 0)+})++test('failed physical rollback keeps a durable retry and its quota until cleanup succeeds once', async (t) => {+ t.mock.method(console, 'error', () => {})+ const store = fakeStore()+ journal.record = async () => { throw new Error('manifest unavailable') }+ const del = store.del+ store.del = async () => { throw new Error('blob deletion unavailable') }+ const image = { type: 'image', data: PNG, mimeType: 'image/png' }+ await assert.rejects(storeDesignAssets(CHAT, USER, [image], store), /manifest unavailable/)+ assert.equal(store.files.size, 1)+ assert.equal(jobs.size, 1)+ assert.equal(calls.some(([name]) => name === 'release'), false)+ await retryDesignAssetCleanup(store)+ assert.equal(jobs.size, 1, 'an unsuccessful retry does not lose its durable record')+ store.del = del+ await Promise.all([retryDesignAssetCleanup(store), retryDesignAssetCleanup(store)])+ assert.equal(store.files.size, 0)+ assert.equal(jobs.size, 0)+ assert.equal(calls.filter(([name]) => name === 'release').length, 1)+})++test('a Redis outage cannot prevent immediate removal of files after a failed manifest write', async (t) => {+ t.mock.method(console, 'error', () => {})+ const store = fakeStore()+ journal.record = async () => { throw new Error('Redis unavailable') }+ journal.queue = async () => { throw new Error('Redis unavailable') }+ await assert.rejects(storeDesignAssets(CHAT, USER, [{ type: 'image', data: PNG, mimeType: 'image/png' }], store), /Redis unavailable/)+ assert.equal(store.files.size, 0)+ assert.equal(calls.filter(([name]) => name === 'release').length, 1)+})++test('a lost cleanup enqueue response cannot refund a rollback twice', async (t) => {+ t.mock.method(console, 'error', () => {})+ const store = fakeStore()+ journal.record = async () => { throw new Error('manifest unavailable') }+ const queue = journal.queue+ journal.queue = async (job) => { await queue(job); throw new Error('enqueue response lost') }+ await assert.rejects(storeDesignAssets(CHAT, USER, [{ type: 'image', data: PNG, mimeType: 'image/png' }], store), /manifest unavailable/)+ journal.queue = queue+ await retryDesignAssetCleanup(store)+ assert.equal(store.files.size, 0)+ assert.equal(jobs.size, 0)+ assert.equal(calls.filter(([name]) => name === 'release').length, 1)+})+test('a design may name an attached image wherever it may name an image, even with remote images off', () => {for (const body of [`<img src="fx0-asset:${HANDLE}" alt="">`,diff --git a/tests/journal.integration.mjs b/tests/journal.integration.mjsindex ca7de87..9e1a801 100644--- a/tests/journal.integration.mjs+++ b/tests/journal.integration.mjs@@ -227,6 +227,92 @@ test('journal Redis integration uses isolated durable session state', async (t)assert.equal(await journal.getActiveTurn(sessionId), null)})+ await t.test('asset reservations enforce both caps atomically across concurrent requests', async () => {+ const id = 'asset-caps'+ const user = 'asset-caps-user'+ const admitted = await Promise.all(Array.from({ length: 10 }, () => journal.reserveDesignAssets(id, user, 6)))+ assert.equal(admitted.filter((result) => result === 'ok').length, 8)+ assert.equal(admitted.filter((result) => result === 'chat').length, 2)+ assert.equal(await redis.get(key(id, 'asset-count')), 48)+ assert.equal(await journal.reserveDesignAssets('asset-caps-other', user, 50), 'ok')+ assert.equal(await journal.reserveDesignAssets('asset-caps-third', user, 3), 'daily')+ assert.equal(await redis.exists(key('asset-caps-third', 'asset-count')), 0)+ })++ await t.test('asset reservations and manifest commits are fenced throughout and after deletion', async () => {+ const id = 'asset-deletion'+ const user = 'asset-deletion-user'+ const asset = { handle: 'AbCdEfGhIjKlMnOpQrStUvWx', mimeType: 'image/png', bytes: 5 }+ await journal.updateSession(id, {})+ assert.equal(await journal.reserveDesignAssets(id, user, 1), 'ok')+ await journal.recordDesignAssets(id, [asset])+ assert.equal((await journal.readDesignAssets(id)).size, 1)+ const token = randomUUID()+ assert.equal(await journal.claimSessionCleanup(id, token), 'claimed')+ await assert.rejects(journal.reserveDesignAssets(id, user, 1), journal.SessionCleanupError)+ await assert.rejects(journal.recordDesignAssets(id, [asset]), journal.SessionCleanupError)+ assert.equal(await redis.get(key(id, 'asset-count')), 1)+ assert.equal(await journal.finishSessionCleanup(id, token, null), true)+ await assert.rejects(journal.reserveDesignAssets(id, user, 1), journal.SessionCleanupError)+ await assert.rejects(journal.recordDesignAssets(id, [asset]), journal.SessionCleanupError)+ assert.equal(await redis.exists(key(id, 'asset-count'), key(id, 'assets')), 0)+ })++ await t.test('cleanup completion refunds its original UTC day exactly once and preserves unrelated assets', async () => {+ const id = 'asset-cleanup'+ const user = 'asset-cleanup-user'+ const yesterday = Date.UTC(2026, 0, 1, 23, 59)+ const today = yesterday + 120_000+ const a = { handle: 'AbCdEfGhIjKlMnOpQrStUvWx', mimeType: 'image/png', bytes: 5 }+ const b = { ...a, handle: 'ZbCdEfGhIjKlMnOpQrStUvWx' }+ assert.equal(await journal.reserveDesignAssets(id, user, 1, yesterday), 'ok')+ assert.equal(await journal.reserveDesignAssets(id, user, 1, today), 'ok')+ await journal.recordDesignAssets(id, [a, b])+ const job = { sessionId: id, userId: user, handles: [a.handle], reservedAt: yesterday }+ await journal.queueDesignAssetCleanup(job)+ assert.deepEqual(await journal.pendingDesignAssetCleanups(), [job])+ await Promise.all([journal.finishDesignAssetCleanup(job), journal.finishDesignAssetCleanup(job)])+ // A delayed enqueue whose response was lost cannot reintroduce the job.+ await journal.queueDesignAssetCleanup(job)+ await journal.finishDesignAssetCleanup(job)+ assert.equal(await redis.get(`${prefix}:user:${user}:assets:2026-01-01`), 0)+ assert.equal(await redis.get(`${prefix}:user:${user}:assets:2026-01-02`), 1)+ assert.equal(await redis.get(key(id, 'asset-count')), 1)+ assert.deepEqual([...await journal.readDesignAssets(id)], [[b.handle, { mimeType: 'image/png', bytes: 5 }]])+ assert.deepEqual(await journal.pendingDesignAssetCleanups(), [])+ })++ await t.test('rollback completion is idempotent when no retry enqueue was acknowledged', async () => {+ const id = 'asset-cleanup-unqueued'+ const user = 'asset-cleanup-unqueued-user'+ const reservedAt = Date.now()+ await journal.reserveDesignAssets(id, user, 2, reservedAt)+ const job = { sessionId: id, userId: user, handles: ['AbCdEfGhIjKlMnOpQrStUvWx'], reservedAt }+ await journal.finishDesignAssetCleanup(job)+ await journal.queueDesignAssetCleanup(job)+ await journal.finishDesignAssetCleanup(job)+ assert.equal(await redis.get(key(id, 'asset-count')), 1)+ assert.deepEqual(await journal.pendingDesignAssetCleanups(), [])+ })++ await t.test('pending asset rollback survives chat deletion without recreating deleted keys', async () => {+ const id = 'asset-cleanup-deleted'+ const user = 'asset-cleanup-deleted-user'+ const reservedAt = Date.now()+ await journal.updateSession(id, {})+ await journal.reserveDesignAssets(id, user, 1, reservedAt)+ const job = { sessionId: id, userId: user, handles: ['AbCdEfGhIjKlMnOpQrStUvWx'], reservedAt }+ await journal.queueDesignAssetCleanup(job)+ const token = randomUUID()+ assert.equal(await journal.claimSessionCleanup(id, token), 'claimed')+ assert.equal(await journal.finishSessionCleanup(id, token, null), true)+ assert.deepEqual(await journal.pendingDesignAssetCleanups(), [job])+ await journal.finishDesignAssetCleanup(job)+ assert.equal(await redis.exists(key(id, 'asset-count'), key(id, 'assets')), 0)+ assert.equal(await redis.get(`${prefix}:user:${user}:assets:${new Date(reservedAt).toISOString().slice(0, 10)}`), 0)+ assert.deepEqual(await journal.pendingDesignAssetCleanups(), [])+ })+await t.test('deletion waits for a running turn, then removes everything but the tombstone', async () => {const id = 'delete-race'await journal.updateSession(id, { preferredEffort: null })@@ -306,7 +392,7 @@ test('journal Redis integration uses isolated durable session state', async (t)assert.deepEqual(await credentials.dropLoginCredentials('login-laptop'), [{ chatId: 'cred-laptop', turns: 1, latest: 'deleted' }])assert.equal(await credentials.readTurnCredential('cred-laptop'), null)assert.equal((await credentials.readExecutionFunding('cred-laptop', 1)).ok, false)- assert.equal(await redis.hlen(`${prefix}:funding:cred-laptop`), 1, 'sign-out keeps the funding record')+ assert.equal(await redis.hlen(`${prefix}:paid-funding:cred-laptop`), 1, 'sign-out keeps the paid funding record')assert.equal((await credentials.readTurnCredential('cred-phone'))?.accessToken, 'access-phone-secret')await assert.rejects(credentials.saveTurnCredential('cred-expired', { ...session('login-x', 'x'), expiresAt: Date.now() - 1 }, 1), /Sign in again/)assert.equal(await credentials.readTurnCredential('cred-expired'), null, 'an expired token is never stored')diff --git a/tests/route-security.test.mjs b/tests/route-security.test.mjsindex e27d16e..a2fd875 100644--- a/tests/route-security.test.mjs+++ b/tests/route-security.test.mjs@@ -95,11 +95,17 @@ const mocks = {lastActivity: stored.lastActivity, busy: false })).sort((a, b) => b.lastActivity - a.lastActivity).slice(0, 100);}- export async function readDesignAssets() { return new Map(); }+ export async function readDesignAssets(id, handles) {+ const assets = globalThis.securityTest.assets?.get(id) ?? new Map();+ return new Map([...assets].filter(([h]) => !handles || handles.includes(h)));+ }export async function recordDesignAssets() {}export const MAX_CHAT_ASSETS = 50; export const MAX_DAILY_ASSETS = 100;- export async function reserveDesignAssets() { return 'ok'; }+ export async function reserveDesignAssets() { return globalThis.securityTest.assetLimit ?? 'ok'; }export async function releaseDesignAssets() {}+ export async function finishDesignAssetCleanup() {}+ export async function pendingDesignAssetCleanups() { globalThis.securityTest.trace.push('cleanup-retry'); return []; }+ export async function queueDesignAssetCleanup() {}export async function readDesignArtifact(id) { record('artifact', id); return '<!doctype html><html><head><title>private design</title></head><body>private artifact</body></html>'; }export async function readDesignArtifactAt(id) {const s = record('artifact', id);@@ -144,9 +150,13 @@ const mocks = {}`,'components/chat-app.tsx': 'export default function ChatApp() {}',+ 'lib/remote-image-cache.ts': `+ export async function cachedRemoteImage() { return 'data:image/png;base64,aW1hZ2U='; }+ `,}registerHooks({resolve(specifier, context, next) {+ if (specifier === '@vercel/blob') return { url: 'security-test:blob', shortCircuit: true }if (specifier === 'botid/server') return { url: 'security-test:botid', shortCircuit: true }if (specifier === '@neondatabase/serverless') return { url: 'security-test:neon', shortCircuit: true }if (specifier === 'next/headers') return { url: 'security-test:headers', shortCircuit: true }@@ -165,11 +175,20 @@ registerHooks({return next(specifier, context)},load(url, context, next) {+ if (url === 'security-test:blob') return { format: 'module', shortCircuit: true, source: `+ export async function get() {+ const s = globalThis.securityTest; s.blobGets = (s.blobGets ?? 0) + 1;+ return { statusCode: 200, stream: new Blob(['image']).stream() };+ }+ export async function put() { throw new Error('Unexpected Blob upload'); }+ export async function del() {}+ export async function list() { return { blobs: [], hasMore: false }; }+ ` }if (url === 'security-test:neon') return { format: 'module', shortCircuit: true, source: `export function neon() { return { query: async (text, values) => globalThis.securityTest.query(text, values) }; }` }- if (url === 'security-test:connection') return { format: 'module', shortCircuit: true, source: 'export async function connection() {} export function after() {}' }- if (url === 'security-test:next-server') return { format: 'module', shortCircuit: true, source: 'export function after() { globalThis.securityTest.trace.push(\'after\'); }' }+ if (url === 'security-test:connection') return { format: 'module', shortCircuit: true, source: 'export async function connection() {} export function after(work) { globalThis.securityTest.afterTasks.push(work); }' }+ if (url === 'security-test:next-server') return { format: 'module', shortCircuit: true, source: 'export function after(work) { globalThis.securityTest.trace.push(\'after\'); globalThis.securityTest.afterTasks.push(work); }' }if (url === 'security-test:headers') return { format: 'module', shortCircuit: true, source: 'export async function cookies() { return { get() {} }; } export async function headers() { return new Headers(); }' }if (url === 'security-test:botid') return { format: 'module', shortCircuit: true, source: 'export async function checkBotId() { globalThis.securityTest.trace.push("botid"); return { isBot: !!globalThis.securityTest.bot, isHuman: !globalThis.securityTest.bot }; }' }if (url === 'security-test:navigation') return { format: 'module', shortCircuit: true, source: `@@ -197,7 +216,7 @@ const session = (extra = {}) => ({ userId: 'user_a', name: 'Verified Author', emaccessToken: 'user-token', refreshToken: 'secret-refresh', teamId: 'team_a', teamSlug: 'a',loginId: 'a'.repeat(32), loginAt: Date.now(), expiresAt: Date.now() + 3600_000, isLoggedIn: true, ...extra })function reset(extra = {}) {- const state = { session: session(), trace: [], queries: [], redisReads: [], summaryCalls: [],+ const state = { session: session(), trace: [], queries: [], redisReads: [], summaryCalls: [], afterTasks: [],owners: new Map([[own, 'user_a'], [foreign, 'user_b']]),billingTeams: new Map([[own, 'team_a'], [foreign, 'team_b']]),existing: new Set(), records: new Map(), deleteResult: true, ...extra }@@ -503,6 +522,65 @@ test('the wrapper\'s image route serves only URLs artifact-frame signed for this}})+test('private attachments revalidate ownership and the manifest; a 304 never downloads Blob bytes', async () => {+ process.env.SESSION_SECRET ??= 'deterministic-route-security-secret-32+'+ const { artifactImageSrc } = await import('../lib/artifact-image.ts')+ const handle = 'AbCdEfGhIjKlMnOpQrStUvWx'+ const path = artifactImageSrc(own, `fx0-asset:${handle}`)+ const get = (etag) => routes['artifact-image'].GET(new Request(`https://fx0.example${path}`, {+ headers: { origin: process.env.APP_URL, ...(etag ? { 'if-none-match': etag } : {}) },+ }))+ const s = reset({ assets: new Map([[own, new Map([[handle, { mimeType: 'image/png', bytes: 5 }]])]]) })+ const first = await get()+ assert.equal(first.status, 200)+ assert.equal(await first.text(), 'image')+ assert.equal(first.headers.get('cache-control'), 'private, no-cache')+ const etag = first.headers.get('etag')+ assert.ok(etag)+ const kept = await get(etag)+ assert.equal(kept.status, 304)+ assert.equal(await kept.text(), '')+ assert.equal(kept.headers.get('cache-control'), 'private, no-cache')+ assert.equal(kept.headers.get('etag'), etag)+ assert.equal(s.blobGets, 1)+ s.assets.clear()+ const removed = await get(etag)+ assert.equal(removed.status, 404)+ assert.equal(removed.headers.get('cache-control'), 'private, no-store')+ assert.equal(s.blobGets, 1)+ s.session = session({ userId: 'user_b', loginId: 'b'.repeat(32) })+ assert.equal((await get(etag)).status, 404)+ s.session = null+ assert.equal((await get(etag)).status, 401)+ assert.equal(s.blobGets, 1)+})++test('public remote image bytes keep their existing private browser cache policy', async () => {+ reset()+ process.env.SESSION_SECRET ??= 'deterministic-route-security-secret-32+'+ const { artifactImageSrc } = await import('../lib/artifact-image.ts')+ const response = await routes['artifact-image'].GET(new Request(`https://fx0.example${artifactImageSrc(own, 'https://images.example.com/a.png')}`))+ assert.equal(response.status, 200)+ assert.equal(response.headers.get('cache-control'), 'private, max-age=86400')+ assert.equal(await response.text(), 'image')+})++test('a capped attachment still schedules durable cleanup after its refusal; deletion schedules it too', async () => {+ const s = reset({ assetLimit: 'chat' })+ const image = { type: 'image', mimeType: 'image/png', data: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==' }+ const refused = await routes.prompt.POST(request('prompt', 'POST', own, { text: 'Use this image', images: [image] }))+ assert.equal(refused.status, 429)+ assert.equal(s.afterTasks.length, 1)+ assert.equal(s.trace.includes('cleanup-retry'), false, 'cleanup stays outside the acknowledgement path')+ await s.afterTasks[0]()+ assert.equal(s.trace.includes('cleanup-retry'), true)+ const deleting = reset()+ assert.equal((await routes.session.DELETE(request('session', 'DELETE', own))).status, 200)+ assert.equal(deleting.afterTasks.length, 1)+ await deleting.afterTasks[0]()+ assert.equal(deleting.trace.includes('cleanup-retry'), true)+})+test('the artifact preview paints no white of its own before the design does', async () => {reset()const html = await (await routes['artifact-frame'].GET(request('artifact-frame', 'GET', own, undefined, 'null'))).text()diff --git a/tests/runtime.test.mjs b/tests/runtime.test.mjsindex 4ce598d..95966c3 100644--- a/tests/runtime.test.mjs+++ b/tests/runtime.test.mjs@@ -9,7 +9,9 @@ const journalNames = ['answerActiveQuestion', 'appendEvent', 'bindLibfxSession', 'chatOfLibfxSession', 'claimSessionCleanup','clearActiveQuestion', 'currentSeq', 'emitLive', 'finishSessionCleanup', 'finishTurnWork', 'getActiveQuestion','getActiveTurn', 'nextQuestionId', 'projectEvents', 'projectedCursor', 'publishDesignArtifact', 'readDesignArtifact',- 'readDesignAssets', 'readDesignMd', 'readEvents', 'recordDesignAssets', 'releaseDesignAssets', 'reserveDesignAssets', 'readSession', 'readSessionView', 'readTurnWork', 'releaseSessionCleanup', 'renewSessionCleanup',+ 'readDesignAssets', 'readDesignMd', 'readEvents', 'recordDesignAssets', 'releaseDesignAssets', 'reserveDesignAssets',+ 'finishDesignAssetCleanup', 'pendingDesignAssetCleanups', 'queueDesignAssetCleanup',+ 'readSession', 'readSessionView', 'readTurnWork', 'releaseSessionCleanup', 'renewSessionCleanup','setActiveQuestion', 'submitPrompt', 'takeAnswer', 'updateSession',]const dataUrl = (source) => `data:text/javascript,${encodeURIComponent(source)}`