From 1ed6145b52edc9739f6e386690564c6a831741e5 Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 10 Nov 2026 21:38:03 +1100 Subject: [PATCH 01/15] feat: add authenticated generation history adapter and recovery --- src/generationHistory.js | 119 ++++++++++++++++++++++++++++ src/generationHistory.test.js | 40 ++++++++++ src/generationHistoryConfig.js | 11 +++ src/generationHistoryConfig.test.js | 7 ++ 4 files changed, 177 insertions(+) create mode 100644 src/generationHistory.js create mode 100644 src/generationHistory.test.js create mode 100644 src/generationHistoryConfig.js create mode 100644 src/generationHistoryConfig.test.js diff --git a/src/generationHistory.js b/src/generationHistory.js new file mode 100644 index 0000000..b703793 --- /dev/null +++ b/src/generationHistory.js @@ -0,0 +1,119 @@ +import { normalizeArtifactBundle, parseJsonLike } from './artifactBundle.js'; +import { buildBundleDeployPlan } from './bundleDeployPlanner.js'; + +const object = v => v && typeof v === 'object' && !Array.isArray(v); +const text = v => typeof v === 'string' && v.trim().length > 0; +const abortError = () => new DOMException('History request invalidated', 'AbortError'); + +/** getSession returns {token, key}; key must change on logout/account switch. + * Call invalidate immediately on session changes or selection changes. Each call + * performs one bounded server page, including empty continuation pages. */ +export function createGenerationHistoryClient({ endpoint, getSession, fetchImpl = globalThis.fetch }) { + const url = new URL(endpoint); + if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || !['/service/generation-history', '/staging/service/generation-history'].includes(url.pathname)) throw new Error('Invalid history endpoint'); + let epoch = 0; + const pending = new Set(); + function invalidate() { epoch++; for (const c of pending) c.abort(); pending.clear(); } + async function request(body, { signal } = {}) { + const session = getSession(); + if (!text(session?.token) || !text(session?.key)) throw new Error('Authenticated session required'); + const { token, key } = session; + const started = epoch; + const controller = new AbortController(); + const cancel = () => controller.abort(); + signal?.addEventListener('abort', cancel, { once: true }); + if (signal?.aborted) cancel(); + pending.add(controller); + const check = () => { + const now = getSession(); + if (controller.signal.aborted || epoch !== started || now?.key !== key || now?.token !== token) throw abortError(); + }; + try { + check(); + const response = await fetchImpl(url.href, { method: 'POST', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify(body), signal: controller.signal }); + const data = await response.json(); + check(); + if (!response.ok) { + const error = new Error('History request failed'); + error.status = response.status; + error.code = data?.error?.code || 'INVALID_RESPONSE'; + throw error; + } + return data; + } finally { pending.delete(controller); signal?.removeEventListener('abort', cancel); } + } + const validId = id => { if (!text(id) || id.length > 1500 || id.includes('/')) throw new Error('Invalid history id'); }; + return { + invalidate, + async list({ cursor, signal } = {}) { + if (cursor !== undefined && (!text(cursor) || cursor.length > 8192)) throw new Error('Invalid cursor'); + const data = await request({ action: 'list', ...(cursor === undefined ? {} : { cursor }) }, { signal }); + if (!Array.isArray(data?.items) || data.items.length > 20 || !(data.nextCursor === null || (text(data.nextCursor) && data.nextCursor.length <= 8192)) || (cursor && cursor === data.nextCursor)) throw new Error('Invalid history page'); + return data; + }, + async detail(id, options) { validId(id); const data = await request({ action: 'detail', id }, options); if (!object(data?.generation)) throw new Error('Invalid history detail'); return data; }, + async delete(id, options) { validId(id); const data = await request({ action: 'delete', id }, options); if (data?.deleted !== true || data.id !== id) throw new Error('Invalid deletion response'); return data; }, + }; +} + +function completeStage(stage, field) { + const value = stage?.[`${field}_text`]; + return text(value) && stage[`${field}_truncated`] !== true && stage.status !== 'error' && stage.status !== 'failed' + && !['length', 'max_tokens', 'content_filter'].includes(stage.finish_reason) + && !(Number.isFinite(stage[`${field}_chars`]) && stage[`${field}_chars`] > value.length); +} +function validatedBundle(raw) { + if (!object(raw) || !['artifact-bundle/v1'].includes(raw.schemaVersion) || !Array.isArray(raw.artifacts) || !raw.artifacts.length) return null; + const types = ['CustomAction', 'CustomWidget', 'CustomFunction', 'CustomClass', 'CodeFile']; + if (raw.artifacts.some(a => !object(a) || !text(a.id) || !types.includes(a.artifactType) || !text(a.artifactName) || !/^[\w-]+\.dart$/.test(a.fileName) || !text(a.code) || (a.deployPath && (a.deployPath.includes('..') || !a.deployPath.startsWith('lib/'))))) return null; + const bundle = normalizeArtifactBundle(raw); + if (new Set(bundle.artifacts.map(a => a.id)).size !== bundle.artifacts.length) return null; + if (bundle.deployOrder.length !== bundle.artifacts.length || new Set(bundle.deployOrder).size !== bundle.artifacts.length || bundle.deployOrder.some(id => !bundle.artifacts.some(a => a.id === id))) return null; + const plan = buildBundleDeployPlan(bundle); + if (plan.errors.length) return null; + const files = plan.fileEntries; + // Validate actual deploy targets as well as supplied paths. + if (files && new Set(files.map(f => f.path)).size !== files.length) return null; + const paths = bundle.artifacts.map(a => a.deployPath || `${a.codeType}/${a.fileName}`); + if (new Set(paths).size !== paths.length) return null; + return bundle; +} + +/** Pure recovery, never generation, deployment, or approval. Raw stage text is + * returned for text-only display. UI must retain existing deployment gates. */ +export function recoverGenerationHistory(detail) { + const g = detail?.generation || {}; + const stages = object(g.stages) ? g.stages : {}; + const result = { availability: 'unavailable', source: null, artifactBundle: null, bundleReview: null, review: null, reviewAvailable: false, originalPrompt: null, bundleSpec: null, stages, metadata: Object.fromEntries(['id', 'request_id', 'created_at', 'updated_at', 'stage', 'status', 'is_test', 'models', 'totals'].map(k => [k, g[k] ?? null])) }; + if (detail?.identityMismatch || !text(g.id) || g.id !== g.request_id) return result; + const architect = stages.architect, generator = stages.generator, review = stages.review; + if (completeStage(architect, 'input')) result.originalPrompt = parseJsonLike(architect.input_text)?.userRequest ?? null; + if (typeof result.originalPrompt !== 'string') result.originalPrompt = null; + result.bundleSpec = completeStage(architect, 'output') ? parseJsonLike(architect.output_text) : null; + if (!result.bundleSpec && completeStage(generator, 'input')) result.bundleSpec = parseJsonLike(generator.input_text)?.bundleSpec ?? null; + let bundle = completeStage(generator, 'output') ? validatedBundle(parseJsonLike(generator.output_text)) : null; + if (bundle) result.source = 'generator-output'; + if (!bundle && completeStage(review, 'input')) { + bundle = validatedBundle(parseJsonLike(review.input_text)?.generatedBundle); + if (bundle) result.source = 'review-input'; + } + if (!bundle) return result; + result.artifactBundle = bundle; + result.availability = 'pre-review'; + const rawReview = completeStage(review, 'output') ? parseJsonLike(review.output_text) : null; + if (!object(rawReview) || !['artifact-bundle/v1'].includes(rawReview.schemaVersion) || !Array.isArray(rawReview.artifacts)) return result; + const summary = rawReview.bundleReview; + if (!object(summary) || !['pass', 'warn', 'fail'].includes(summary.status) || !Number.isInteger(summary.score) || summary.score < 0 || summary.score > 100 || !text(summary.summary)) return result; + if (rawReview.artifacts.some(a => !object(a) || !text(a.id) || !['pass', 'warn', 'fail'].includes(a.review?.status))) return result; + const normalized = normalizeArtifactBundle(rawReview); + const reviews = new Map(normalized.artifacts.map(a => [a.id, a.review])); + if (reviews.size !== bundle.artifacts.length || normalized.artifacts.length !== reviews.size || bundle.artifacts.some(a => !object(reviews.get(a.id)))) return result; + result.review = rawReview; + result.reviewAvailable = true; + result.availability = 'reviewed'; + result.bundleReview = { ...bundle, artifacts: bundle.artifacts.map(a => { + const stored = reviews.get(a.id); + return { ...a, review: stored, ...(text(stored.fixedSource) ? { fixedCode: stored.fixedSource.trim() } : {}) }; + }) }; + return result; +} diff --git a/src/generationHistory.test.js b/src/generationHistory.test.js new file mode 100644 index 0000000..cb87253 --- /dev/null +++ b/src/generationHistory.test.js @@ -0,0 +1,40 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { recoverGenerationHistory as recover, createGenerationHistoryClient as client } from './generationHistory.js'; +const bundle = () => ({schemaVersion:'artifact-bundle/v1',artifacts:[{id:'one',artifactType:'CodeFile',artifactName:'One',fileName:'one.dart',code:'class One {}'}]}); +const detail = stages => ({generation:{id:'synthetic',request_id:'synthetic',stages}}); +const output = value => ({output_text:JSON.stringify(value)}); +test('complete output and actual review preserve original and fixed source', () => { + const value = recover(detail({generator:output(bundle()),review:output({schemaVersion:'artifact-bundle/v1',bundleReview:{status:'pass',score:95,summary:'Synthetic review'},artifacts:[{id:'one',review:{status:'pass',fixedSource:'class One { }'}}]})})); + assert.equal(value.availability,'reviewed'); assert.equal(value.artifactBundle.artifacts[0].code,'class One {}'); assert.equal(value.bundleReview.artifacts[0].fixedCode,'class One { }'); +}); +test('review input recovery is explicitly pre-review and prompt is recovered', () => { + const value = recover(detail({architect:{input_text:JSON.stringify({userRequest:'Synthetic prompt'})},review:{input_text:JSON.stringify({generatedBundle:bundle()})}})); + assert.equal(value.source,'review-input'); assert.equal(value.reviewAvailable,false); assert.equal(value.originalPrompt,'Synthetic prompt'); assert.equal(value.metadata.status,null); +}); +test('missing, unsupported, truncated, duplicate and mismatched data cannot replay', () => { + for (const generator of [{}, {...output(bundle()),output_truncated:true}, {...output(bundle()),finish_reason:'length'}, {...output(bundle()),output_chars:99999}, output({...bundle(),schemaVersion:'future'}), output({...bundle(),artifacts:[...bundle().artifacts,...bundle().artifacts]})]) assert.equal(recover(detail({generator})).availability,'unavailable'); + assert.equal(recover({...detail({generator:output(bundle())}),identityMismatch:true}).availability,'unavailable'); +}); +test('bounded page allows empty continuation and sends no owner fields', async () => { + let body; + const c = client({endpoint:'https://example.test/service/generation-history',getSession:()=>({token:'synthetic',key:'a'}),fetchImpl:async (_,opts)=>{body=JSON.parse(opts.body);return {ok:true,json:async()=>({items:[],nextCursor:'next'})};}}); + assert.equal((await c.list({user_id:'forged'})).nextCursor,'next'); assert.deepEqual(body,{action:'list'}); + await assert.rejects(c.list({cursor:'next'}),/Invalid history page/); +}); +test('session changes and invalidation suppress late responses even if fetch ignores abort', async () => { + for (const mode of ['session','invalidate','signal']) { + let session={token:'token',key:'a'}, release; + const signal=new AbortController(); + const c=client({endpoint:'https://example.test/service/generation-history',getSession:()=>session,fetchImpl:()=>new Promise(resolve=>{release=()=>resolve({ok:true,json:async()=>({items:[],nextCursor:null})});})}); + const pending=c.list({signal:signal.signal}); + if(mode==='session')session={token:'token2',key:'b'}; else if(mode==='invalidate')c.invalidate(); else signal.abort(); + release(); await assert.rejects(pending,{name:'AbortError'}); + } +}); +test('detail/delete and structured HTTP errors',async()=>{ + let response={generation:{id:'a'}}; + const c=client({endpoint:'https://example.test/service/generation-history',getSession:()=>({token:'t',key:'a'}),fetchImpl:async()=>({ok:true,json:async()=>response})}); + assert.equal((await c.detail('a')).generation.id,'a'); response={deleted:true,id:'a'}; assert.equal((await c.delete('a')).deleted,true); + await assert.rejects(c.detail('../bad')); +}); diff --git a/src/generationHistoryConfig.js b/src/generationHistoryConfig.js new file mode 100644 index 0000000..0edbdce --- /dev/null +++ b/src/generationHistoryConfig.js @@ -0,0 +1,11 @@ +/** Public URLs only. No implicit production fallback, including in staging. */ +export function resolveGenerationHistoryEndpoint({ target, stagingEndpoint, productionEndpoint } = {}) { + if (!['staging', 'production'].includes(target)) throw new Error('Explicit history target required'); + const value = target === 'staging' ? stagingEndpoint : productionEndpoint; + const url = new URL(value); + const path = target === 'staging' ? '/staging/service/generation-history' : '/service/generation-history'; + if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || url.pathname !== path) { + throw new Error('Invalid public history endpoint for target'); + } + return url.href; +} diff --git a/src/generationHistoryConfig.test.js b/src/generationHistoryConfig.test.js new file mode 100644 index 0000000..e3620a0 --- /dev/null +++ b/src/generationHistoryConfig.test.js @@ -0,0 +1,7 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { resolveGenerationHistoryEndpoint as resolve } from './generationHistoryConfig.js'; +test('explicit isolated public endpoints', () => { + assert.equal(resolve({target:'staging',stagingEndpoint:'https://example.test/staging/service/generation-history'}),'https://example.test/staging/service/generation-history'); + for (const config of [{}, {target:'staging',productionEndpoint:'https://example.test/service/generation-history'}, {target:'staging',stagingEndpoint:'https://example.test/service/generation-history'}, {target:'production',productionEndpoint:'https://secret@example.test/service/generation-history'}]) assert.throws(() => resolve(config)); +}); From fa05bb793abb0e13715d2ff6c10f6a4a4ffced2a Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 10 Nov 2026 21:42:40 +1100 Subject: [PATCH 02/15] fix: address generation history adapter review findings --- src/generationHistory.js | 17 +++++++------ src/generationHistory.test.js | 46 +++++++++++++++++++++++++++++++++-- 2 files changed, 54 insertions(+), 9 deletions(-) diff --git a/src/generationHistory.js b/src/generationHistory.js index b703793..b37e9a5 100644 --- a/src/generationHistory.js +++ b/src/generationHistory.js @@ -58,14 +58,18 @@ export function createGenerationHistoryClient({ endpoint, getSession, fetchImpl function completeStage(stage, field) { const value = stage?.[`${field}_text`]; - return text(value) && stage[`${field}_truncated`] !== true && stage.status !== 'error' && stage.status !== 'failed' - && !['length', 'max_tokens', 'content_filter'].includes(stage.finish_reason) - && !(Number.isFinite(stage[`${field}_chars`]) && stage[`${field}_chars`] > value.length); + return text(value) && stage[`${field}_truncated`] === false && stage.status === 'success' + && (field === 'input' || ['stop', 'end_turn'].includes(stage.finish_reason)) + && Number.isInteger(stage[`${field}_chars`]) && stage[`${field}_chars`] === value.length; } function validatedBundle(raw) { if (!object(raw) || !['artifact-bundle/v1'].includes(raw.schemaVersion) || !Array.isArray(raw.artifacts) || !raw.artifacts.length) return null; const types = ['CustomAction', 'CustomWidget', 'CustomFunction', 'CustomClass', 'CodeFile']; - if (raw.artifacts.some(a => !object(a) || !text(a.id) || !types.includes(a.artifactType) || !text(a.artifactName) || !/^[\w-]+\.dart$/.test(a.fileName) || !text(a.code) || (a.deployPath && (a.deployPath.includes('..') || !a.deployPath.startsWith('lib/'))))) return null; + if (raw.artifacts.some(a => !object(a) || !text(a.id) || !types.includes(a.artifactType) || !text(a.artifactName) || (typeof a.fileName !== 'string' || !/^[\w-]+\.dart$/.test(a.fileName)) || !text(a.code) || (a.deployPath !== undefined && (typeof a.deployPath !== 'string' || !/^lib\/(?:[\w-]+\/)*[\w-]+\.dart$/.test(a.deployPath))))) return null; + if (Object.hasOwn(raw, 'deployOrder') && (!Array.isArray(raw.deployOrder) + || raw.deployOrder.length !== raw.artifacts.length + || new Set(raw.deployOrder).size !== raw.artifacts.length + || raw.deployOrder.some(id => typeof id !== 'string' || !raw.artifacts.some(a => a.id === id)))) return null; const bundle = normalizeArtifactBundle(raw); if (new Set(bundle.artifacts.map(a => a.id)).size !== bundle.artifacts.length) return null; if (bundle.deployOrder.length !== bundle.artifacts.length || new Set(bundle.deployOrder).size !== bundle.artifacts.length || bundle.deployOrder.some(id => !bundle.artifacts.some(a => a.id === id))) return null; @@ -74,8 +78,7 @@ function validatedBundle(raw) { const files = plan.fileEntries; // Validate actual deploy targets as well as supplied paths. if (files && new Set(files.map(f => f.path)).size !== files.length) return null; - const paths = bundle.artifacts.map(a => a.deployPath || `${a.codeType}/${a.fileName}`); - if (new Set(paths).size !== paths.length) return null; + return bundle; } @@ -101,7 +104,7 @@ export function recoverGenerationHistory(detail) { result.artifactBundle = bundle; result.availability = 'pre-review'; const rawReview = completeStage(review, 'output') ? parseJsonLike(review.output_text) : null; - if (!object(rawReview) || !['artifact-bundle/v1'].includes(rawReview.schemaVersion) || !Array.isArray(rawReview.artifacts)) return result; + if (!object(rawReview) || (rawReview.schemaVersion !== undefined && rawReview.schemaVersion !== 'artifact-bundle/v1') || !Array.isArray(rawReview.artifacts)) return result; const summary = rawReview.bundleReview; if (!object(summary) || !['pass', 'warn', 'fail'].includes(summary.status) || !Number.isInteger(summary.score) || summary.score < 0 || summary.score > 100 || !text(summary.summary)) return result; if (rawReview.artifacts.some(a => !object(a) || !text(a.id) || !['pass', 'warn', 'fail'].includes(a.review?.status))) return result; diff --git a/src/generationHistory.test.js b/src/generationHistory.test.js index cb87253..71f861a 100644 --- a/src/generationHistory.test.js +++ b/src/generationHistory.test.js @@ -3,13 +3,14 @@ import assert from 'node:assert/strict'; import { recoverGenerationHistory as recover, createGenerationHistoryClient as client } from './generationHistory.js'; const bundle = () => ({schemaVersion:'artifact-bundle/v1',artifacts:[{id:'one',artifactType:'CodeFile',artifactName:'One',fileName:'one.dart',code:'class One {}'}]}); const detail = stages => ({generation:{id:'synthetic',request_id:'synthetic',stages}}); -const output = value => ({output_text:JSON.stringify(value)}); +const stage = (value, field) => ({status:'success',finish_reason:'stop',[`${field}_text`]:JSON.stringify(value),[`${field}_chars`]:JSON.stringify(value).length,[`${field}_truncated`]:false}); +const output = value => stage(value, 'output'); test('complete output and actual review preserve original and fixed source', () => { const value = recover(detail({generator:output(bundle()),review:output({schemaVersion:'artifact-bundle/v1',bundleReview:{status:'pass',score:95,summary:'Synthetic review'},artifacts:[{id:'one',review:{status:'pass',fixedSource:'class One { }'}}]})})); assert.equal(value.availability,'reviewed'); assert.equal(value.artifactBundle.artifacts[0].code,'class One {}'); assert.equal(value.bundleReview.artifacts[0].fixedCode,'class One { }'); }); test('review input recovery is explicitly pre-review and prompt is recovered', () => { - const value = recover(detail({architect:{input_text:JSON.stringify({userRequest:'Synthetic prompt'})},review:{input_text:JSON.stringify({generatedBundle:bundle()})}})); + const value = recover(detail({architect:stage({userRequest:'Synthetic prompt'}, 'input'),review:stage({generatedBundle:bundle()}, 'input')})); assert.equal(value.source,'review-input'); assert.equal(value.reviewAvailable,false); assert.equal(value.originalPrompt,'Synthetic prompt'); assert.equal(value.metadata.status,null); }); test('missing, unsupported, truncated, duplicate and mismatched data cannot replay', () => { @@ -38,3 +39,44 @@ test('detail/delete and structured HTTP errors',async()=>{ assert.equal((await c.detail('a')).generation.id,'a'); response={deleted:true,id:'a'}; assert.equal((await c.delete('a')).deleted,true); await assert.rejects(c.detail('../bad')); }); + +const reviewer = () => ({bundleReview:{status:'pass',score:95,summary:'Reviewed'},artifacts:[{id:'one',review:{status:'pass',findings:[]}}]}); +test('missing completeness metadata never grants replay or review', () => { + for (const field of ['status','output_truncated','output_chars','finish_reason']) { + const generator = output(bundle()); delete generator[field]; + assert.equal(recover(detail({generator})).availability,'unavailable', field); + const review = output(reviewer()); delete review[field]; + assert.equal(recover(detail({generator:output(bundle()),review})).availability,'pre-review', field); + } + for (const field of ['status','input_truncated','input_chars']) { + const review = stage({generatedBundle:bundle()},'input'); delete review[field]; + assert.equal(recover(detail({review})).availability,'unavailable',field); + } +}); +test('actual reviewer envelope works with optional fixedSource and no schemaVersion', () => { + for (const fixedSource of [undefined,'class One { int x = 1; }']) { + const review = reviewer(); review.artifacts[0].review.fixedSource = fixedSource; + const result = recover(detail({generator:output(bundle()),review:output(review)})); + assert.equal(result.availability,'reviewed'); + assert.equal(result.bundleReview.artifacts[0].fixedCode,fixedSource); + assert.equal(result.artifactBundle.artifacts[0].code,'class One {}'); + } +}); +test('planner-supported shared functions replay but unrelated collisions do not', () => { + const artifacts = ['one','two'].map(id => ({id,artifactType:'CustomFunction',artifactName:id,fileName:'custom_functions.dart',deployPath:'lib/flutter_flow/custom_functions.dart',code:`int ${id}() => 1;`})); + assert.equal(recover(detail({generator:output({...bundle(),artifacts})})).availability,'pre-review'); + artifacts[1].artifactType='CodeFile'; + assert.equal(recover(detail({generator:output({...bundle(),artifacts})})).availability,'unavailable'); +}); +test('supplied malformed deployOrder is rejected before normalization', () => { + for (const deployOrder of ['one',null,{},[],['one','one'],['missing'],[42]]) { + assert.equal(recover(detail({generator:output({...bundle(),deployOrder})})).availability,'unavailable'); + } + assert.equal(recover(detail({generator:output({...bundle(),deployOrder:['one']})})).availability,'pre-review'); +}); +test('nonstring and malformed stored paths are unavailable without throwing', () => { + for (const deployPath of [42,null,{},[],false,'','lib/../one.dart','lib//one.dart','lib/./one.dart','lib/one.dart?x','lib/one\\bad.dart','lib/one\u0000.dart']) { + const raw = bundle(); raw.artifacts[0].deployPath=deployPath; + assert.equal(recover(detail({generator:output(raw)})).availability,'unavailable',JSON.stringify(deployPath)); + } +}); From f3ec925efea16ffa82de39e304de6b93caafb68c Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 10 Nov 2026 21:45:01 +1100 Subject: [PATCH 03/15] fix: isolate stored review fields from artifact metadata --- src/generationHistory.js | 4 +++- src/generationHistory.test.js | 10 ++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/generationHistory.js b/src/generationHistory.js index b37e9a5..e1aba47 100644 --- a/src/generationHistory.js +++ b/src/generationHistory.js @@ -108,7 +108,9 @@ export function recoverGenerationHistory(detail) { const summary = rawReview.bundleReview; if (!object(summary) || !['pass', 'warn', 'fail'].includes(summary.status) || !Number.isInteger(summary.score) || summary.score < 0 || summary.score > 100 || !text(summary.summary)) return result; if (rawReview.artifacts.some(a => !object(a) || !text(a.id) || !['pass', 'warn', 'fail'].includes(a.review?.status))) return result; - const normalized = normalizeArtifactBundle(rawReview); + const normalized = normalizeArtifactBundle({ ...bundle, artifacts: rawReview.artifacts.map(a => ({ + ...bundle.artifacts.find(original => original.id === a.id), id: a.id, review: a.review, + })) }); const reviews = new Map(normalized.artifacts.map(a => [a.id, a.review])); if (reviews.size !== bundle.artifacts.length || normalized.artifacts.length !== reviews.size || bundle.artifacts.some(a => !object(reviews.get(a.id)))) return result; result.review = rawReview; diff --git a/src/generationHistory.test.js b/src/generationHistory.test.js index 71f861a..af6a9e0 100644 --- a/src/generationHistory.test.js +++ b/src/generationHistory.test.js @@ -80,3 +80,13 @@ test('nonstring and malformed stored paths are unavailable without throwing', () assert.equal(recover(detail({generator:output(raw)})).availability,'unavailable',JSON.stringify(deployPath)); } }); + +test('reviewer artifact metadata cannot override validated generator metadata or crash recovery', () => { + for (const extra of [{fileName:42},{artifactName:{}},{deployPath:42},{code:{}},{artifactType:[]}]) { + const review = reviewer(); Object.assign(review.artifacts[0], extra); + const value = recover(detail({generator:output(bundle()),review:output(review)})); + assert.equal(value.availability,'reviewed'); + assert.equal(value.bundleReview.artifacts[0].fileName,'one.dart'); + assert.equal(value.bundleReview.artifacts[0].code,'class One {}'); + } +}); From f0488c306224e22d0e32890b6adda3fe496b4327 Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 10 Nov 2026 21:54:38 +1100 Subject: [PATCH 04/15] feat: add authenticated generation history and Results recovery --- app.js | 139 +++++++++++++++++++++++++++++++++ e2e/generation-history.spec.js | 83 ++++++++++++++++++++ index.html | 11 ++- 3 files changed, 229 insertions(+), 4 deletions(-) create mode 100644 e2e/generation-history.spec.js diff --git a/app.js b/app.js index 20d3ee5..a585c48 100644 --- a/app.js +++ b/app.js @@ -1,3 +1,5 @@ +import { createGenerationHistoryClient, recoverGenerationHistory } from './src/generationHistory.js'; +import { resolveGenerationHistoryEndpoint } from './src/generationHistoryConfig.js'; import posthog from "posthog-js"; import { closeModal, @@ -2199,6 +2201,7 @@ let pipelineState = { }; function resetPipelineResults() { + document.getElementById("history-review-notice")?.remove(); pipelineState.step1Result = null; pipelineState.step2Result = null; pipelineState.step3Result = null; @@ -6083,6 +6086,7 @@ async function refreshSession(sessionToken) { } function saveSession(email, sessionToken) { + resetHistory(); const storedSession = getStoredSession() const sessionChanged = (authState.email || storedSession.email) !== email authState.email = email @@ -6094,6 +6098,7 @@ function saveSession(email, sessionToken) { } function clearSession() { + resetHistory(); authState.email = null authState.sessionToken = null authState.isVerified = false @@ -6258,6 +6263,7 @@ async function handleMagicLinkRequest() { } function handleSignOut() { + resetHistory(); // Reset in-memory auth/subscription state first so the immediate re-render // below reflects a signed-out identity/plan. authState.email = null @@ -10106,3 +10112,136 @@ window.editPipelinePrompt = editPipelinePrompt; window.retryPipelineRun = retryPipelineRun; window.openCreditsModal = openCreditsModal; window.closeCreditsModal = closeCreditsModal; + +// History requests use the application session, never a caller-supplied owner. +const historyClient = createGenerationHistoryClient({ + endpoint: resolveGenerationHistoryEndpoint({ + target: import.meta.env.VITE_HISTORY_TARGET || 'production', + productionEndpoint: `${BUILDSHIP_BASE_URL}/service/generation-history`, + stagingEndpoint: `${BUILDSHIP_BASE_URL}/staging/service/generation-history`, + }), + getSession: () => ({ token: authState.sessionToken, key: authState.isVerified ? authState.email : null }), +}); +let historyCursor = null; +let historyEpoch = 0; +let historyRecovery = null; +let historyResultsBundle = null; +const historyEl = id => document.getElementById(`history-${id}`); +function resetHistory() { + if (historyResultsBundle && pipelineState.artifactBundle === historyResultsBundle) { + resetPipelineResults(); + pipelineState.submittedPrompt = ""; + document.getElementById("results-view")?.classList.remove("visible"); + document.body.classList.remove("results-fullscreen", "results-with-sidebar"); + } + historyResultsBundle = null; + historyEpoch++; + historyClient.invalidate(); + historyCursor = null; + historyRecovery = null; + if (historyEl('panel')) historyEl('panel').setAttribute('aria-busy', 'false'); + historyEl('list')?.replaceChildren(); + historyEl('detail')?.replaceChildren(); + if (historyEl('status')) historyEl('status').textContent = 'Refresh to load your saved generations.'; + if (historyEl('next')) historyEl('next').disabled = true; +} +function historyButton(label, action) { + const button = document.createElement('button'); + button.type = 'button'; button.className = 'btn-action ghost sm'; + button.textContent = label; button.addEventListener('click', action); + return button; +} +async function historyTask(action) { + const epoch = ++historyEpoch; + historyClient.invalidate(); + historyEl('status').textContent = 'Loading history…'; + historyEl('panel').setAttribute('aria-busy', 'true'); + try { await action(() => epoch === historyEpoch); } + catch (error) { + if (epoch === historyEpoch && error.name !== 'AbortError') historyEl('status').textContent = + error.status === 401 ? 'Session expired. Sign in again, then refresh.' : + error.status === 404 ? 'This entry is no longer available. Refresh the list.' : 'History could not be loaded or changed. Try again.'; + } finally { if (epoch === historyEpoch) historyEl('panel').setAttribute('aria-busy', 'false'); } +} +function loadHistory(next = false) { + historyRecovery = null; + const cursor = next ? historyCursor : null; + return historyTask(async current => { + const page = await historyClient.list(cursor ? { cursor } : {}); + if (!current()) return; + historyCursor = page.nextCursor; + historyEl('list').replaceChildren(); historyEl('detail').replaceChildren(); + historyEl('next').disabled = !historyCursor; + historyEl('status').textContent = page.items.length ? 'Saved generations' : + historyCursor ? 'No entries on this page. Continue to the next page.' : 'No saved generations on this page.'; + for (const item of page.items) { + if (!item || typeof item.id !== 'string' || !item.id || item.id.includes('/')) continue; + const row = document.createElement('li'); + row.append(historyButton(item.id, () => openHistory(item.id))); + const status = document.createElement('span'); + status.textContent = ` — ${typeof item.status === 'string' ? item.status : 'Status unknown'}`; + row.append(status); historyEl('list').append(row); + } + }); +} +function openHistory(id) { + if (pipelineState.isRunning) { historyEl('status').textContent = 'Wait for generation to finish before opening history.'; return; } + historyRecovery = null; + historyEl('detail').replaceChildren(); + return historyTask(async current => { + const detail = await historyClient.detail(id); + if (!current()) return; + if (detail.generation.id !== id) throw new Error('Mismatched history detail'); + const recovered = recoverGenerationHistory(detail); + historyRecovery = recovered; + const panel = historyEl('detail'); panel.replaceChildren(); + const message = document.createElement('p'); + message.textContent = recovered.artifactBundle ? + recovered.reviewAvailable ? 'Stored artifacts and review available.' : 'Review unavailable. Recovered code has not acquired review approval.' : + 'Replay unavailable: this record is incomplete or cannot be validated. Available text is shown below.'; + panel.append(message); + for (const [name, stage] of Object.entries(recovered.stages)) { + for (const field of ['input_text', 'output_text']) { + if (typeof stage?.[field] !== 'string') continue; + const section = document.createElement('details'); const title = document.createElement('summary'); + title.textContent = `${name} ${field}`; const pre = document.createElement('pre'); + pre.style.whiteSpace = 'pre-wrap'; pre.textContent = stage[field]; section.append(title, pre); panel.append(section); + } + } + if (recovered.artifactBundle) panel.append(historyButton('Open in Results', () => { + if (pipelineState.isRunning) { historyEl('status').textContent = 'Wait for generation to finish before opening history.'; return; } + if (historyRecovery !== recovered || !authState.isVerified) return; + resetPipelineResults(); + Object.assign(pipelineState, { artifactBundle: recovered.artifactBundle, bundleSpec: recovered.bundleSpec, + step1Result: recovered.bundleSpec ? JSON.stringify(recovered.bundleSpec) : null, + step2Result: JSON.stringify(recovered.artifactBundle), step3Result: recovered.review ? JSON.stringify(recovered.review) : null, + bundleReview: recovered.bundleReview, submittedPrompt: recovered.originalPrompt || '', submittedImages: [], + selectedArtifactId: recovered.artifactBundle.artifacts[0].id, requestId: id }); + historyResultsBundle = recovered.artifactBundle; + // The adapter merges stored review by validated artifact ID and preserves original code. + switchView('home'); + showResultsView(getSelectedArtifactCode(), recovered.reviewAvailable ? renderMarkdownAudit(pipelineState.step3Result) : '

Review unavailable for this saved generation.

'); + if (!recovered.reviewAvailable) { + const notice = document.createElement('p'); notice.id = 'history-review-notice'; notice.setAttribute('role', 'status'); + notice.textContent = 'Review unavailable for this saved generation. Existing deployment checks still apply.'; + document.getElementById('results-view')?.prepend(notice); + } + })); + panel.append(historyButton('Delete this generation', () => { + const confirm = document.createElement('div'); confirm.setAttribute('role', 'group'); confirm.setAttribute('aria-label', 'Confirm deletion'); + const warning = document.createElement('p'); warning.textContent = 'Delete this generation permanently? Generation content will be removed; an internal marker prevents late writes from restoring it.'; + confirm.append(warning, historyButton('Cancel', () => confirm.remove()), historyButton('Confirm delete', () => historyTask(async current => { + await historyClient.delete(id); if (!current()) return; + historyRecovery = null; panel.replaceChildren(); historyEl('status').textContent = 'Generation deleted. Refresh to update the list.'; + }))); + panel.append(confirm); + })); + historyEl('status').textContent = 'Generation details loaded.'; + }); +} +historyEl('refresh').addEventListener('click', () => loadHistory()); +historyEl('next').addEventListener('click', () => loadHistory(true)); + +if (import.meta.env.DEV) { + window.__CCC_HISTORY_TEST__ = { session: saveSession, pending: value => { pipelineState.isRunning = value; }, state: () => pipelineState }; +} diff --git a/e2e/generation-history.spec.js b/e2e/generation-history.spec.js new file mode 100644 index 0000000..3b6e8b2 --- /dev/null +++ b/e2e/generation-history.spec.js @@ -0,0 +1,83 @@ +import { test, expect } from '@playwright/test'; +import { applyDefaultRoutes, ENDPOINTS } from './fixtures/apiFixtures.js'; +test('history bounded pagination, safe detail and selected deletion', async ({ page }) => { + await page.addInitScript(() => { + localStorage.setItem('hasSeenWalkthrough', 'true'); + localStorage.setItem('ccc_auth_session', JSON.stringify({email:'test@example.com',sessionToken:'synthetic'})); + }); + await applyDefaultRoutes(page, { [ENDPOINTS.authRefreshSession]: {status:200,contentType:'application/json',body:JSON.stringify({email:'test@example.com',sessionToken:'synthetic'})} }); + const calls=[]; let deleteFailed = false; + await page.route('**/service/generation-history', route => { + const body=route.request().postDataJSON(); calls.push(body); + expect(route.request().headers().authorization).toBe('Bearer synthetic'); + expect(body.user_id).toBeUndefined(); + if (body.action === 'delete' && !deleteFailed) { deleteFailed = true; return route.fulfill({status:500,json:{error:{code:'INTERNAL_ERROR'}}}); } + const data=body.action==='list' ? body.cursor ? {items:[{id:'entry',status:''}],nextCursor:null} : {items:[],nextCursor:'continue'} : body.action==='detail' ? {generation:{id:'entry',request_id:'entry',stages:{generator:{output_text:''}}}} : {deleted:true,id:'entry'}; + return route.fulfill({json:data}); + }); + await page.goto('/'); await page.evaluate(()=>window.switchView('account')); + await page.locator('#history-refresh').click(); + await expect(page.locator('#history-status')).toContainText('Continue'); + await page.locator('#history-next').click(); + await page.getByRole('button',{name:'entry',exact:true}).click(); + await expect(page.locator('#history-detail')).toContainText('Replay unavailable'); + await expect(page.locator('#history-detail script')).toHaveCount(0); + await page.getByRole('button',{name:'Delete this generation',exact:true}).click(); + await page.getByRole('button',{name:'Confirm delete',exact:true}).click(); + await expect(page.locator('#history-status')).toContainText('Try again'); + await page.getByRole('button',{name:'Confirm delete',exact:true}).click(); + await expect(page.locator('#history-status')).toContainText('Generation deleted'); + expect(calls.map(c=>c.action)).toEqual(['list','list','detail','delete','delete']); +}); + +const stage = (data, field='output') => ({status:'success',finish_reason:'stop',[`${field}_text`]:JSON.stringify(data),[`${field}_chars`]:JSON.stringify(data).length,[`${field}_truncated`]:false}); +for (const reviewed of [true,false]) test(`recover multi-artifact results review=${reviewed} without generation`, async ({page}) => { + await page.addInitScript(()=>localStorage.setItem('hasSeenWalkthrough','true')); + await applyDefaultRoutes(page, { [ENDPOINTS.authRefreshSession]: {status:200,contentType:'application/json',body:JSON.stringify({email:'a@example.com',sessionToken:'synthetic'})} }); + await page.addInitScript(()=>localStorage.setItem('ccc_auth_session',JSON.stringify({email:'a@example.com',sessionToken:'synthetic'}))); + const bundle={schemaVersion:'artifact-bundle/v1',artifacts:['one','two'].map(id=>({id,artifactType:'CodeFile',artifactName:id,fileName:`${id}.dart`,code:`class ${id} {}`}))}; + const review={bundleReview:{status:'pass',score:95,summary:'Synthetic'},artifacts:['one','two'].map(id=>({id,review:{status:'pass',fixedSource:`class ${id} { int x = 1; }`}}))}; + let forbidden=0; + await page.route('**/service/runpipeline**',r=>{forbidden++;return r.abort();}); + await page.route('**/service/generation-history',r=>r.fulfill({json:r.request().postDataJSON().action==='list'?{items:[{id:'saved'}],nextCursor:null}:{generation:{id:'saved',request_id:'saved',stages:{architect:stage({userRequest:'Synthetic prompt'},'input'),generator:stage(bundle),...(reviewed?{review:stage(review)}:{})}}}})); + await page.goto('/'); await page.waitForFunction(()=>window.__CCC_HISTORY_TEST__); + await expect(page.locator('#topbar-avatar')).toContainText('A'); + await page.evaluate(()=>window.switchView('account')); await page.locator('#history-refresh').click(); + await page.getByRole('button',{name:'saved',exact:true}).click(); + await page.evaluate(()=>window.__CCC_HISTORY_TEST__.pending(true)); + await page.getByRole('button',{name:'Open in Results',exact:true}).click(); + await expect(page.locator('#history-status')).toContainText('Wait for generation'); + await page.evaluate(()=>window.__CCC_HISTORY_TEST__.pending(false)); + await page.getByRole('button',{name:'Open in Results',exact:true}).click(); + const state=await page.evaluate(()=>window.__CCC_HISTORY_TEST__.state()); + expect(state.artifactBundle.artifacts).toHaveLength(2); expect(state.submittedPrompt).toBe('Synthetic prompt'); + if(reviewed) expect(state.bundleReview.artifacts[0].fixedCode).toContain('int x'); else expect(state.step3Result).toBeNull(); + await page.route('**/*checkout*',r=>{forbidden++;return r.abort();}); + await page.evaluate(()=>window.initiateCommitToFlutterFlow()); + expect(forbidden).toBe(0); +}); + +test('late list is invalidated by account switch and sign out',async({page})=>{ + await page.addInitScript(()=>localStorage.setItem('hasSeenWalkthrough','true')); await applyDefaultRoutes(page, { [ENDPOINTS.authRefreshSession]: {status:200,contentType:'application/json',body:JSON.stringify({email:'a@example.com',sessionToken:'synthetic'})} }); + await page.addInitScript(()=>localStorage.setItem('ccc_auth_session',JSON.stringify({email:'a@example.com',sessionToken:'synthetic'}))); + let release; await page.route('**/service/generation-history',async r=>{await new Promise(resolve=>release=resolve); await r.fulfill({json:{items:[{id:'private-entry'}],nextCursor:null}}).catch(()=>{});}); + await page.goto('/'); await page.waitForFunction(()=>window.__CCC_HISTORY_TEST__); + await expect(page.locator('#topbar-avatar')).toContainText('A'); + await page.evaluate(()=>window.switchView('account')); await page.locator('#history-refresh').click(); + await expect.poll(()=>!!release).toBe(true); + await page.evaluate(()=>window.__CCC_HISTORY_TEST__.session('b@example.com','other')); + release(); await expect(page.locator('#history-list')).toBeEmpty(); + await page.evaluate(()=>window.handleSignOut()); await expect(page.locator('#history-detail')).toBeEmpty(); +}); + +test('malformed list reports error and refresh retries one page', async ({page}) => { + await page.addInitScript(()=>{localStorage.setItem('hasSeenWalkthrough','true');localStorage.setItem('ccc_auth_session',JSON.stringify({email:'a@example.com',sessionToken:'synthetic'}));}); + await applyDefaultRoutes(page,{[ENDPOINTS.authRefreshSession]:{status:200,contentType:'application/json',body:JSON.stringify({email:'a@example.com',sessionToken:'synthetic'})}}); + let count=0; + await page.route('**/service/generation-history',r=>r.fulfill({json:++count===1?{items:{bad:true},nextCursor:null}:{items:[],nextCursor:null}})); + await page.goto('/'); await expect(page.locator('#topbar-avatar')).toContainText('A'); + await page.evaluate(()=>window.switchView('account')); await page.locator('#history-refresh').click(); + await expect(page.locator('#history-status')).toContainText('Try again'); + await page.locator('#history-refresh').click(); await expect(page.locator('#history-status')).toContainText('No saved generations'); + expect(count).toBe(2); await expect(page.locator('#history-next')).toBeDisabled(); +}); diff --git a/index.html b/index.html index 5677072..11bd464 100644 --- a/index.html +++ b/index.html @@ -3672,11 +3672,14 @@

Usage this month

Generation history

- not saved + Saved generations
-
-

Saved history isn't available yet.

-

Per-run records aren't persisted, so there is no past list to show. Your current result stays open in the generation workspace.

+
+

Refresh to load your saved generations.

+ +
    + +
    From bdeacc6671e4a69c987f2f8159c7a2a61d5a59b6 Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 10 Nov 2026 21:55:36 +1100 Subject: [PATCH 05/15] test: cover real empty generation history in account overview --- e2e/stu383-account-overview.spec.js | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/e2e/stu383-account-overview.spec.js b/e2e/stu383-account-overview.spec.js index c11e8ad..fdf7eb1 100644 --- a/e2e/stu383-account-overview.spec.js +++ b/e2e/stu383-account-overview.spec.js @@ -157,26 +157,21 @@ test.describe("STU-383 account overview", () => { ); }); - test("the no-history state is truthful and points to the generation workspace", async ({ page }) => { + test("empty saved history is truthful and does not fabricate rows", async ({ page }) => { await seedSession(page); await applyDefaultRoutes(page, { ...refreshOverride(), [ENDPOINTS.identity]: identityWithUsage({ email: undefined, count: 3 }), [ENDPOINTS.getSubscription]: professionalSubscription(), }); + await page.route('**/service/generation-history', route => route.fulfill({json:{items:[],nextCursor:null}})); await page.goto("/"); await openAccount(page); - - await expect(page.locator("#acct-no-history")).toContainText("Saved history isn't available yet."); - await expect(page.locator("#acct-no-history")).toContainText("generation workspace"); - // No illustrative breakdown/history rows are fabricated. - const text = await page.locator("#acct-history").innerText(); - expect(text).not.toMatch(/Custom Widget 9|Committed/); - - // The empty state keeps current results reachable via the generation workspace. - await page.locator("#acct-no-history a").click(); - await expect(page.locator("#home-view")).toBeVisible(); - await expect(page.locator("#home-view")).toHaveClass(/is-active/); + await page.locator('#history-refresh').click(); + await expect(page.locator('#history-status')).toContainText('No saved generations'); + await expect(page.locator('#history-list')).toBeEmpty(); + await expect(page.locator('#history-next')).toBeDisabled(); + expect(await page.locator('#acct-history').innerText()).not.toMatch(/Custom Widget 9|Committed/); }); test("account reflects a usage refresh without stale private information", async ({ page }) => { From c6a7ef1ee5c4219a1fdef9928812f36a2b031a49 Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 10 Nov 2026 22:00:14 +1100 Subject: [PATCH 06/15] test: close generation history browser evidence gaps --- e2e/generation-history.spec.js | 98 ++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) diff --git a/e2e/generation-history.spec.js b/e2e/generation-history.spec.js index 3b6e8b2..ff6f7d8 100644 --- a/e2e/generation-history.spec.js +++ b/e2e/generation-history.spec.js @@ -81,3 +81,101 @@ test('malformed list reports error and refresh retries one page', async ({page}) await page.locator('#history-refresh').click(); await expect(page.locator('#history-status')).toContainText('No saved generations'); expect(count).toBe(2); await expect(page.locator('#history-next')).toBeDisabled(); }); + +async function historySetup(page, code = 'class Saved {}') { + await page.addInitScript(() => { + localStorage.setItem('hasSeenWalkthrough','true'); + localStorage.setItem('ccc_auth_session',JSON.stringify({email:'a@example.com',sessionToken:'synthetic'})); + }); + await applyDefaultRoutes(page,{[ENDPOINTS.authRefreshSession]:{status:200,json:{email:'a@example.com',sessionToken:'synthetic'}}}); + const detail={generation:{id:'saved',request_id:'saved',stages:{generator:stage({schemaVersion:'artifact-bundle/v1',artifacts:[{id:'saved',artifactType:'CodeFile',artifactName:'Saved',fileName:'saved.dart',code}]})}}}; + await page.route('**/service/generation-history',r=>r.fulfill({json:r.request().postDataJSON().action==='list'?{items:[{id:'saved',status:'success'}],nextCursor:null}:detail})); + await page.goto('/#account'); + await expect(page.locator('#topbar-avatar')).toContainText('A'); + await page.locator('#history-refresh').click(); + await expect(page.getByRole('button',{name:'saved',exact:true})).toBeVisible(); + return detail; +} + +for (const action of ['detail','delete']) for (const transition of ['refresh','logout','account']) { + test(`late ${action} cannot overwrite ${transition}`,async({page})=>{ + const detail=await historySetup(page); + if(action==='delete') { + await page.getByRole('button',{name:'saved',exact:true}).click(); + await page.getByRole('button',{name:'Delete this generation',exact:true}).click(); + } + let release; + let completed; + const settled=new Promise(resolve=>completed=resolve); + await page.route('**/service/generation-history',async r=>{ + if(r.request().postDataJSON().action!==action) return r.fallback(); + await new Promise(resolve=>release=resolve); + try { await r.fulfill({json:action==='detail'?detail:{deleted:true,id:'saved'}}); } catch {} finally { completed(); } + }); + await page.getByRole('button',{name:action==='detail'?'saved':'Confirm delete',exact:true}).click(); + await expect.poll(()=>!!release).toBe(true); + if(transition==='refresh') await page.locator('#history-refresh').click(); + else if(transition==='logout') await page.evaluate(()=>window.handleSignOut()); + else await page.evaluate(()=>window.__CCC_HISTORY_TEST__.session('b@example.com','other')); + await expect(page.locator('#history-panel')).toHaveAttribute('aria-busy','false'); + const status=await page.locator('#history-status').textContent(); + release(); await settled; + // Drain browser tasks after the held transport completes, including abort rejection handlers. + await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))); + await expect(page.locator('#history-detail')).toBeEmpty(); + await expect(page.locator('#history-status')).toHaveText(status); + await expect(page.locator('#history-list li')).toHaveCount(transition==='refresh'?1:0); + expect((await page.evaluate(()=>window.__CCC_HISTORY_TEST__.state())).artifactBundle).toBeNull(); + }); +} + +for(const width of [360,1440]) test(`populated history keyboard and layout at ${width}`,async({page})=>{ + await page.setViewportSize({width,height:900}); await historySetup(page); + const row=page.getByRole('button',{name:'saved',exact:true}); + await page.locator('#history-refresh').focus(); + await page.keyboard.press('Tab'); + await expect(row).toBeFocused(); await page.keyboard.press('Enter'); + await expect(page.locator('#history-detail')).toContainText('Review unavailable'); + const summary=page.locator('#history-detail summary').first(); + await summary.focus(); await page.keyboard.press('Enter'); + await expect(page.locator('#history-detail details').first()).toHaveAttribute('open',''); + await expect(page.locator('#history-status')).toHaveAttribute('role','status'); + for(const selector of ['#history-panel','#history-list','#history-detail']) { + const bounds=await page.locator(selector).boundingBox(); + expect(bounds.x).toBeGreaterThanOrEqual(0); expect(bounds.x+bounds.width).toBeLessThanOrEqual(width+1); + } + await page.getByRole('button',{name:'Delete this generation',exact:true}).focus(); + await page.keyboard.press('Enter'); + await expect(page.getByRole('group',{name:'Confirm deletion'})).toBeVisible(); + await page.getByRole('button',{name:'Cancel',exact:true}).focus(); await page.keyboard.press('Enter'); + await expect(page.getByRole('group',{name:'Confirm deletion'})).toHaveCount(0); +}); + +for(const valid of [true,false]) test(`restored code passes through configured deployment gate valid=${valid}`,async({page})=>{ + await historySetup(page,valid?'class Saved {}':'class Saved {'); + await page.locator('.acct-connection button',{hasText:'Configure'}).first().click(); + await page.locator('#flutterflow-api-key-input').fill('synthetic-history-key'); + await page.locator('#flutterflow-api-key-input').blur(); + await expect(page.locator('#flutterflow-projects-select option[value="proj-abc-123"]')).toHaveCount(1); + await page.locator('#flutterflow-projects-select').selectOption('proj-abc-123'); + await page.locator('#api-keys-modal .bg-blue-500').click(); + await expect(page.locator('#api-keys-modal')).toBeHidden(); + const forbidden=[]; + page.on('request',request=>{ + if(/runpipeline|stripe|checkout|billing|deployCustom|syncCustomCode|exportCode|ffai-runner/.test(request.url())) forbidden.push(request.url()); + }); + await page.getByRole('button',{name:'saved',exact:true}).click(); + await page.getByRole('button',{name:'Open in Results',exact:true}).click(); + await expect(page.locator('#results-view')).toBeVisible(); + expect(forbidden).toEqual([]); + await page.evaluate(()=>window.initiateCommitToFlutterFlow()); + if(valid) { + await expect(page.locator('#commit-confirm-modal')).toBeVisible(); + await expect(page.locator('#confirm-project-select option[value="proj-abc-123"]')).toHaveCount(1); + } else { + await expect(page.getByText(/Pre-commit checks failed:.*FlutterFlow cannot format/)).toBeVisible(); + await expect(page.locator('#commit-confirm-modal')).toBeHidden(); + } + await expect(page.locator('#api-keys-modal')).toBeHidden(); + expect(forbidden).toEqual([]); +}); From 74681c915ba17996eee152326248fc15034eed6c Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 10 Nov 2026 22:17:11 +1100 Subject: [PATCH 07/15] feat: guard staging deployment and document history acceptance --- docs/design/BEHAVIOR-OVERRIDES.md | 8 ++- docs/design/TRACEABILITY.md | 4 +- docs/generation-history-acceptance.md | 23 ++++++++ scripts/deploy_ftp.py | 81 ++++++++++++++++++++++++-- scripts/test-deploy-guard.py | 5 ++ scripts/test-staging-deploy.py | 82 +++++++++++++++++++++++++++ 6 files changed, 195 insertions(+), 8 deletions(-) create mode 100644 docs/generation-history-acceptance.md create mode 100644 scripts/test-staging-deploy.py diff --git a/docs/design/BEHAVIOR-OVERRIDES.md b/docs/design/BEHAVIOR-OVERRIDES.md index c14ce7e..866c0d7 100644 --- a/docs/design/BEHAVIOR-OVERRIDES.md +++ b/docs/design/BEHAVIOR-OVERRIDES.md @@ -47,7 +47,7 @@ The handoff shows several demo-only concepts. Production must not fabricate them | Purchases inside the hero modal | Pricing modal links to Stripe checkout / portal via existing `startCheckout` / `openCustomerPortal`. | | Connection success animations | Show real connection status; use loading, error, and retry states. | | Usage breakdown by day/category | Show only the data the backend returns (`used / limit` and current period). | -| Generation history table | Do not add a history table unless the backend endpoint exists and is enabled. | +| Generation history table | Owner-scoped history is implemented under STU-930–933; runtime availability requires the configured authenticated endpoint. See [acceptance boundaries](../generation-history-acceptance.md). | | Account deletion flow | Do not add account deletion; if unavailable, omit the control or show a disabled / support message. | ## 5. Other production rules @@ -55,3 +55,9 @@ The handoff shows several demo-only concepts. Production must not fabricate them - Keep the brand logomark inline (SVG), not as an external image request. - Preserve the real copy and labels from the export, but replace any static placeholders with live data equivalents listed above. - Do not add OpenDesign chrome, preview labels, or design-process annotations to the production UI. + +## Generation history (STU-933) + +List existing records, including incomplete ones, without new retention or tier restrictions. Empty pages may have continuation cursors. Open restores available artifacts into Results without generation, billing or deployment; Deploy remains a separate explicit action with existing safety gates. Prefer complete generator output, otherwise validated nontruncated review-input generatedBundle. Missing review remains unavailable; generator code never implies reviewer approval. Stored fixedCode merges by artifact identity. Preserve safe raw text for partial records. + +Logout/account changes invalidate pending requests and clear history; opening history prevents late generation responses replacing the selection. Delete removes generation content, retaining only an internal owner-bound anti-resurrection marker. Foreign, absent and deleted records share 404. Source acceptance does not establish live endpoint availability. diff --git a/docs/design/TRACEABILITY.md b/docs/design/TRACEABILITY.md index 255f733..f563247 100644 --- a/docs/design/TRACEABILITY.md +++ b/docs/design/TRACEABILITY.md @@ -21,7 +21,9 @@ | No fabricated purchases | Hero plan/billing dialogs | Stripe checkout/portal only | Use existing `startCheckout` / `openCustomerPortal`. | | No fabricated connection success | Journey / account connection card | Real connection states only | | | No usage breakdown | Account usage card | Show `used / limit` only | | -| No generation history | Account history table | Omit unless backend endpoint exists | | +| Owner-scoped generation history (STU-930–933) | Approved generation-history plan | Account list/detail/delete and Results hydration | [Source and delivery boundaries](../generation-history-acceptance.md). | | No account deletion | Account security section | Omit or show support message | | | Nine handoff viewports with reflow expectations | `DESIGN-HANDOFF.md` + manifest | Responsive tests | See [RESPONSIVE.md](./RESPONSIVE.md). | | Fixed 1920×1080 fit scaling is presentation-only | `custom-code-connect-hero.html` `.stage` | Real fluid layout | See [RESPONSIVE.md](./RESPONSIVE.md). | +| Staging FTP isolation (STU-933) | Approved exact ownership amendment | scripts/deploy_ftp.py --target staging | Local mocked guard proof only. | +| Actual staging acceptance (STU-934) | Post-PR delivery gate | Provider routes, auth/CORS, indexes, two-account isolation, FlutterFlow redeploy | Outstanding; requires actual isolated infrastructure. | diff --git a/docs/generation-history-acceptance.md b/docs/generation-history-acceptance.md new file mode 100644 index 0000000..552c142 --- /dev/null +++ b/docs/generation-history-acceptance.md @@ -0,0 +1,23 @@ +# Generation history source acceptance — STU-933 + +Candidate starts at frontend c6a7ef1ee5c4219a1fdef9928812f36a2b031a49, in `/Users/home/.t3/worktrees/dreamflowCommandForFlutterFlow/t3-3d283578-bd96247123bf8c0a`. Common Git directory verified as `/Users/home/Projects/dreamflowCommandForFlutterFlow/.git`. The commit containing this document identifies the complete handoff candidate; controller acceptance remains separate. + +Backend: [PR 194](https://github.com/sgardoll/buildship/pull/194) was merged externally on 10 November 2026 at 11:08:09 UTC with head `00d89badea64a62f8365d9728776d896e0e7bd04` (GitHub readback verified). The editor-schema repair is separate in [PR 195](https://github.com/sgardoll/buildship/pull/195), head `da5b58e2821cfb95ac22035439ef22bfde3ea734`. Backend controller reports independent acceptance of the combined fallback/retry/schema changes at `3296990a`, with 21 functional and 6 schema/isolation tests, and an identical source tree after cherry-picking onto current main. PR 195 checks and hosted editor sync/retest remain outstanding; no deployed service acceptance is claimed. Earlier accepted source `fadcedf02ff64e6e088cfb503cab56caf5c394e1` is historical evidence only. + +## Contract checked against accepted source + +Read-only source: `/Users/home/Projects/buildship/workflows/service-generation-history-Hst1/nodes/history-api/main.ts`, plus workflow `triggers.json`. The worker compared these API files at the earlier accepted source. Subsequent backend fallback/schema changes require final controller pairing verification; the endpoint envelope is reported unchanged. Compared with `src/generationHistory.js`, its synthetic unit fixtures, and `e2e/generation-history.spec.js`. + +POST `/service/generation-history` (staging `/staging/service/generation-history`) uses bearer application session authentication. Bodies contain action plus optional cursor or id, never owner. List returns `{items,nextCursor}`, at most 20 items scanned within 100 documents; empty continuation pages are valid. Detail returns `{generation,identityMismatch}` with whitelisted stage text, character counts, truncation and finish reason. Delete returns `{deleted:true,id}`; repeat deletion returns 404. Errors use `{error:{code,message}}`; absent, foreign and tombstoned records share NOT_FOUND. Timestamps are seconds/nanoseconds objects or null. Backend rejects extra fields, invalid IDs and invalid signed cursors. Frontend validation is deliberately less restrictive (8192 cursor characters versus backend 6000, character versus byte ID limit); backend validation remains authoritative and normal returned cursors/IDs are compatible. Mock fixtures are synthetic partial response subsets, not captures of live service traffic. + +## Staging FTP guard + +Use the existing script with `--target staging`. Export all five `STAGING_FTP_HOSTNAME`, `STAGING_FTP_PORT`, `STAGING_FTP_USERNAME`, `STAGING_FTP_PASSWORD`, `STAGING_FTP_HOME_PATH` settings through a secure shell environment. The script does not read .env automatically. No production password/Keychain fallback is allowed. A separate account and explicit absolute non-root path are mandatory; bare web roots, traversal and control characters are rejected. Every managed remote directory must already exist and report its expected absolute PWD before upload/prune. Provider aliases and directory provisioning must be resolved during STU-934. Local symlinks, remote symlinks in managed directories, failed directory listings and unsafe remote file names are rejected. Dry-run does not mkdir, upload or delete, but does connect/read remote metadata when actually invoked. No FTP invocation was made for this task. + +Default production target retains existing host/account/password resolution and reproducibility/build guards. Remote listing safety applies to both targets. FTP server PWD behavior and real account confinement still require provider verification; local guards cannot prove server-side isolation or distinguish undisclosed production aliases. + +## Evidence and remaining delivery gate + +Local evidence directory: `/tmp/stu933-evidence/` (ephemeral machine-local logs). `backend-source.txt` and `backend-contract.txt` retain the source examined; `node.txt`, `ci.log`, command logs and `results.txt` record local verification. No secrets or customer exports were used. + +`staging-acceptance` means **local configuration/isolation guard proof only**. STU-934 remains outstanding: actual staging host/certificate/root isolation, deployed routes and result bindings, CORS and session-verifier compatibility, staging collection/index queries, synthetic two-account list/detail/delete, and real explicit FlutterFlow redeploy. No production data was copied/deleted, no provider write or deployment occurred, and no PR/push/merge was performed. Fresh independent acceptance and the frontend PR remain pending. Recovered worker logs show 428 unit tests, 283 browser tests, build, seven accessibility shells, nine deployment checks, thirty proxy cases, bundle scan and fourteen staging checks passed on Node 22.15.1. Controller added malformed-listing rejection and reran the fifteen staging tests. diff --git a/scripts/deploy_ftp.py b/scripts/deploy_ftp.py index ed659fe..57b2649 100755 --- a/scripts/deploy_ftp.py +++ b/scripts/deploy_ftp.py @@ -66,6 +66,52 @@ def resolve_password(): ) +def staging_config(): + """Resolve staging only from explicit environment; never consult Keychain.""" + keys = ('HOSTNAME', 'PORT', 'USERNAME', 'PASSWORD', 'HOME_PATH') + values = {key: os.environ.get('STAGING_FTP_' + key, '') for key in keys} + if any(not value.strip() for value in values.values()): + sys.exit('Staging requires all STAGING_FTP_* settings, including HOME_PATH.') + root = values['HOME_PATH'] + parts = root.split('/')[1:] + if (not root.startswith('/') or not parts or + any(not part or part in ('.', '..') for part in parts) or + any(c in root for c in ('\\', '\r', '\n', '\x00')) or + root.lower() in ('/public_html', '/www', '/htdocs')): + sys.exit('Staging requires an explicit non-root isolated absolute HOME_PATH.') + if values['USERNAME'].casefold() == USER.casefold(): + sys.exit('Staging must use a separate FTP account.') + if any(c in values['HOSTNAME'] + values['USERNAME'] for c in ('\r', '\n', '\x00')): + sys.exit('Invalid staging connection settings.') + try: + port = int(values['PORT']) + if not 1 <= port <= 65535: + raise ValueError() + except ValueError: + sys.exit('Invalid STAGING_FTP_PORT.') + return values['HOSTNAME'], port, values['USERNAME'], values['PASSWORD'], root + + +def enter_staging_root(ftp, root, local_dirs): + """Fail closed on aliases/symlinked managed directories before any writes.""" + ftp.cwd(root) + if ftp.pwd() != root: + sys.exit('Staging root does not resolve to the configured absolute path.') + for rel in sorted(local_dirs - {''}): + path = root + '/' + rel + try: + ftp.cwd(path) + except ftplib.error_perm as error: + if not str(error).startswith('550'): + raise + sys.exit('Staging managed directories must exist and be verifiable before deployment.') + if ftp.pwd() != path: + sys.exit('Staging managed directory resolves outside its expected path.') + ftp.cwd(root) + for rel in sorted(local_dirs): + list_remote_dir(ftp, rel, strict=True) + + def local_files_and_dirs(root): """Returns (relative file paths, relative dir paths including "") under root.""" files = set() @@ -101,7 +147,8 @@ def upload_all(ftp, local_files, dry_run): failed = [] for rel in sorted(local_files): - ensure_remote_dir(ftp, os.path.dirname(rel), made_dirs) + if not dry_run: + ensure_remote_dir(ftp, os.path.dirname(rel), made_dirs) local_path = DIST / rel size = local_path.stat().st_size @@ -121,22 +168,33 @@ def upload_all(ftp, local_files, dry_run): return uploaded, failed -def list_remote_dir(ftp, rel_dir): +def list_remote_dir(ftp, rel_dir, strict=False): """Returns [(name, is_dir), ...] for one directory, or [] if it doesn't exist.""" entries = [] lines = [] try: ftp.retrlines(f"LIST {rel_dir}" if rel_dir else "LIST", lines.append) except ftplib.all_errors: + if strict: + sys.exit("Cannot inspect staging directory; refusing deployment.") return entries for line in lines: parts = line.split(None, 8) if len(parts) < 9: + if strict: + sys.exit("Unrecognized staging directory listing; refusing deployment.") continue name = parts[8] if name in (".", ".."): continue + if '/' in name or "\\" in name or any(ord(c) < 32 for c in name): + sys.exit('Unsafe remote listing entry; refusing to prune.') + # Never follow or delete symlinks advertised by LIST. + if parts[0].startswith('l'): + if strict: + sys.exit('Staging managed directory contains a symlink.') + continue entries.append((name, parts[0].startswith("d"))) return entries @@ -298,7 +356,9 @@ def main(): "--allow-dirty", action="store_true", help="Allow deploying an uncommitted dist/ (not recommended)", ) + parser.add_argument("--target", choices=("production", "staging"), default="production") args = parser.parse_args() + staging = staging_config() if args.target == "staging" else None if not DIST.is_dir(): sys.exit(f"{DIST} does not exist. Run `npm run build` first.") @@ -310,12 +370,21 @@ def main(): if not local_files: sys.exit(f"{DIST} has no files to deploy.") - password = resolve_password() + if staging: + host, port, user, password, root = staging + if any('\\' in rel or any(ord(c) < 32 for c in rel) for rel in local_files | local_dirs): + sys.exit('Unsafe staging artifact path.') + if any(path.is_symlink() for path in DIST.rglob('*')): + sys.exit('Staging dist must not contain symlinks.') + else: + host, port, user, password = HOST, PORT, USER, resolve_password() ftp = ftplib.FTP() - ftp.connect(HOST, PORT, timeout=120) - ftp.login(USER, password) - print(f"connected to {HOST} as {USER}" + (" (dry run)" if args.dry_run else "")) + ftp.connect(host, port, timeout=120) + ftp.login(user, password) + if staging: + enter_staging_root(ftp, root, local_dirs) + print(f"connected to {args.target}" + (" (dry run)" if args.dry_run else "")) print("\n-- upload --") uploaded, upload_failed = upload_all(ftp, local_files, args.dry_run) diff --git a/scripts/test-deploy-guard.py b/scripts/test-deploy-guard.py index 6fb0cf8..c7c0f33 100644 --- a/scripts/test-deploy-guard.py +++ b/scripts/test-deploy-guard.py @@ -50,6 +50,11 @@ def expected_absent_bundles(deploy, html): def main(): deploy = load_deploy_module() + # Production password precedence remains unchanged; no Keychain access. + from unittest.mock import patch + with patch.dict(deploy.os.environ, {'FTP_PASSWORD': 'synthetic-production'}), patch.object(deploy.subprocess, 'run', side_effect=AssertionError('unexpected Keychain')): + assert deploy.resolve_password() == 'synthetic-production' + built_html = (deploy.DIST / "index.html").read_text(encoding="utf-8") absent_html = built_html.replace("assets/index-", "assets/index-absent-") diff --git a/scripts/test-staging-deploy.py b/scripts/test-staging-deploy.py new file mode 100644 index 0000000..88e3a80 --- /dev/null +++ b/scripts/test-staging-deploy.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""Local mocked staging isolation proof; never connects to FTP.""" +import importlib.util +import os +import unittest +from unittest.mock import Mock, patch +from pathlib import Path +spec = importlib.util.spec_from_file_location('deploy', Path(__file__).with_name('deploy_ftp.py')) +d = importlib.util.module_from_spec(spec) +spec.loader.exec_module(d) +ENV = dict(zip(('STAGING_FTP_' + k for k in ('HOSTNAME','PORT','USERNAME','PASSWORD','HOME_PATH')), ('staging.example.test','21','stage-user','synthetic-password','/staging'))) + +class StagingTests(unittest.TestCase): + def test_explicit_settings(self): + with patch.dict(os.environ, ENV, clear=True), patch.object(d, 'resolve_password', side_effect=AssertionError): + self.assertEqual(d.staging_config(), ('staging.example.test',21,'stage-user','synthetic-password','/staging')) + def test_each_missing_setting_fails_without_fallback(self): + for key in ENV: + env = {**ENV, 'FTP_PASSWORD':'production-placeholder'} + del env[key] + with self.subTest(key=key), patch.dict(os.environ, env, clear=True), self.assertRaises(SystemExit): + d.staging_config() + def test_unsafe_roots(self): + for root in ('/', '', '/public_html', '/www', '/htdocs', 'staging', '/a/../b', '/a//b', '/a/', '/a\nb', '/a\\b'): + with self.subTest(root=root), patch.dict(os.environ, {**ENV,'STAGING_FTP_HOME_PATH':root}, clear=True), self.assertRaises(SystemExit): + d.staging_config() + def test_production_account_and_invalid_port(self): + for key,value in [('USERNAME',d.USER),('PORT','0'),('PORT','65536'),('PORT','x')]: + with patch.dict(os.environ,{**ENV,'STAGING_FTP_'+key:value},clear=True), self.assertRaises(SystemExit): + d.staging_config() + def test_root_alias_fails_before_write(self): + ftp=Mock(); ftp.pwd.return_value='/' + with self.assertRaises(SystemExit): d.enter_staging_root(ftp,'/staging',{''}) + ftp.storbinary.assert_not_called(); ftp.delete.assert_not_called() + def test_subdirectory_alias_fails(self): + ftp=Mock(); ftp.pwd.side_effect=['/staging','/production/assets'] + with self.assertRaises(SystemExit): d.enter_staging_root(ftp,'/staging',{'','assets'}) + def test_verified_root_restored(self): + ftp=Mock(); ftp.pwd.side_effect=['/staging','/staging/assets'] + d.enter_staging_root(ftp,'/staging',{'','assets'}) + self.assertEqual(ftp.cwd.call_args.args,('/staging',)) + def test_dry_run_has_no_mkdir_upload_delete(self): + ftp=Mock() + with patch.object(d,'DIST',Path(__file__).parent.parent): + d.upload_all(ftp,{'scripts/deploy_ftp.py'},True) + ftp.mkd.assert_not_called(); ftp.storbinary.assert_not_called() + def test_missing_directory_fails_closed(self): + ftp=Mock(); ftp.pwd.return_value='/staging' + ftp.cwd.side_effect=[None,d.ftplib.error_perm('550 unavailable')] + with self.assertRaises(SystemExit): d.enter_staging_root(ftp,'/staging',{'','assets'}) + ftp.mkd.assert_not_called() + def test_missing_config_prevents_connection_even_allow_dirty(self): + with patch.dict(os.environ,{},clear=True), patch('sys.argv',['deploy','--target','staging','--allow-dirty']), patch.object(d.ftplib,'FTP') as factory: + with self.assertRaises(SystemExit): d.main() + factory.assert_not_called() + def test_staging_main_uses_only_staging_connection(self): + ftp=Mock() + with patch.dict(os.environ,ENV,clear=True), patch('sys.argv',['deploy','--target','staging']), patch.object(d,'ensure_dist_self_consistent'), patch.object(d,'ensure_dist_committed'), patch.object(d,'local_files_and_dirs',return_value=({'index.html'},{''})), patch.object(d,'resolve_password',side_effect=AssertionError), patch.object(d.ftplib,'FTP',return_value=ftp), patch.object(d,'enter_staging_root') as enter, patch.object(d,'upload_all',return_value=([],[])), patch.object(d,'prune_stale_files',return_value=([],[])): + d.main() + ftp.connect.assert_called_once_with('staging.example.test',21,timeout=120) + ftp.login.assert_called_once_with('stage-user','synthetic-password') + enter.assert_called_once_with(ftp,'/staging',{''}) + def test_remote_symlink_blocks_staging(self): + ftp=Mock(); ftp.pwd.return_value='/staging' + ftp.retrlines.side_effect=lambda cmd,cb: cb('lrwxrwxrwx 1 u g 1 Jan 1 00:00 index.html -> target') + with self.assertRaises(SystemExit): d.enter_staging_root(ftp,'/staging',{''}) + ftp.storbinary.assert_not_called() + def test_listing_failure_blocks_staging(self): + ftp=Mock(); ftp.pwd.return_value='/staging' + ftp.retrlines.side_effect=d.ftplib.error_perm('550 denied') + with self.assertRaises(SystemExit): d.enter_staging_root(ftp,'/staging',{''}) + def test_malformed_listing_blocks_staging(self): + ftp=Mock(); ftp.pwd.return_value="/staging" + ftp.retrlines.side_effect=lambda cmd,cb: cb("unrecognized listing") + with self.assertRaises(SystemExit): d.enter_staging_root(ftp,"/staging",{""}) + ftp.storbinary.assert_not_called() + def test_hostile_listing_cannot_escape(self): + ftp=Mock(); ftp.retrlines.side_effect=lambda cmd,cb: cb('-rw-r--r-- 1 u g 1 Jan 1 00:00 ../outside') + with self.assertRaises(SystemExit): d.prune_stale_files(ftp,set(),{''},False) + ftp.delete.assert_not_called() + +if __name__ == '__main__': unittest.main() From d9a4045a7311c197f744f8baf35992270f23326b Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 10 Nov 2026 22:22:13 +1100 Subject: [PATCH 08/15] fix: fail staging prune on directory listing errors --- docs/generation-history-acceptance.md | 4 ++-- scripts/deploy_ftp.py | 6 +++--- scripts/test-staging-deploy.py | 8 ++++++++ 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/docs/generation-history-acceptance.md b/docs/generation-history-acceptance.md index 552c142..963e12c 100644 --- a/docs/generation-history-acceptance.md +++ b/docs/generation-history-acceptance.md @@ -2,7 +2,7 @@ Candidate starts at frontend c6a7ef1ee5c4219a1fdef9928812f36a2b031a49, in `/Users/home/.t3/worktrees/dreamflowCommandForFlutterFlow/t3-3d283578-bd96247123bf8c0a`. Common Git directory verified as `/Users/home/Projects/dreamflowCommandForFlutterFlow/.git`. The commit containing this document identifies the complete handoff candidate; controller acceptance remains separate. -Backend: [PR 194](https://github.com/sgardoll/buildship/pull/194) was merged externally on 10 November 2026 at 11:08:09 UTC with head `00d89badea64a62f8365d9728776d896e0e7bd04` (GitHub readback verified). The editor-schema repair is separate in [PR 195](https://github.com/sgardoll/buildship/pull/195), head `da5b58e2821cfb95ac22035439ef22bfde3ea734`. Backend controller reports independent acceptance of the combined fallback/retry/schema changes at `3296990a`, with 21 functional and 6 schema/isolation tests, and an identical source tree after cherry-picking onto current main. PR 195 checks and hosted editor sync/retest remain outstanding; no deployed service acceptance is claimed. Earlier accepted source `fadcedf02ff64e6e088cfb503cab56caf5c394e1` is historical evidence only. +Backend: [PR 194](https://github.com/sgardoll/buildship/pull/194) was merged externally on 10 November 2026 at 11:08:09 UTC with head `00d89badea64a62f8365d9728776d896e0e7bd04` (GitHub readback verified). The editor-schema repair is separate in [PR 195](https://github.com/sgardoll/buildship/pull/195), head `da5b58e2821cfb95ac22035439ef22bfde3ea734`. Backend controller reports independent acceptance of the combined fallback/retry/schema changes at `3296990a`, with 21 functional and 6 schema/isolation tests, and an identical source tree after cherry-picking onto current main. PR 195 was subsequently reported merged. Follow-up [PR 196](https://github.com/sgardoll/buildship/pull/196), head `4989e9c2ac48030c4ad726047e756f17b293c652`, fixes missing trigger-root metadata after reproducing the editor isFile crash with its actual classifier. Backend controller reports seven schema/isolation tests, successful GitGuardian/Entire Gates and exact-head Devin review without findings. Hosted editor sync/retest remains outstanding; no deployed service acceptance is claimed. Earlier accepted source `fadcedf02ff64e6e088cfb503cab56caf5c394e1` is historical evidence only. ## Contract checked against accepted source @@ -20,4 +20,4 @@ Default production target retains existing host/account/password resolution and Local evidence directory: `/tmp/stu933-evidence/` (ephemeral machine-local logs). `backend-source.txt` and `backend-contract.txt` retain the source examined; `node.txt`, `ci.log`, command logs and `results.txt` record local verification. No secrets or customer exports were used. -`staging-acceptance` means **local configuration/isolation guard proof only**. STU-934 remains outstanding: actual staging host/certificate/root isolation, deployed routes and result bindings, CORS and session-verifier compatibility, staging collection/index queries, synthetic two-account list/detail/delete, and real explicit FlutterFlow redeploy. No production data was copied/deleted, no provider write or deployment occurred, and no PR/push/merge was performed. Fresh independent acceptance and the frontend PR remain pending. Recovered worker logs show 428 unit tests, 283 browser tests, build, seven accessibility shells, nine deployment checks, thirty proxy cases, bundle scan and fourteen staging checks passed on Node 22.15.1. Controller added malformed-listing rejection and reran the fifteen staging tests. +`staging-acceptance` means **local configuration/isolation guard proof only**. STU-934 remains outstanding: actual staging host/certificate/root isolation, deployed routes and result bindings, CORS and session-verifier compatibility, staging collection/index queries, synthetic two-account list/detail/delete, and real explicit FlutterFlow redeploy. No production data was copied/deleted, no provider write or deployment occurred, and no PR/push/merge was performed. Fresh independent acceptance and the frontend PR remain pending. Recovered worker logs show 428 unit tests, 283 browser tests, build, seven accessibility shells, nine deployment checks, thirty proxy cases, bundle scan and fourteen staging checks passed on Node 22.15.1. Controller added malformed-listing rejection and post-preflight pruning failure propagation; all sixteen staging tests pass. diff --git a/scripts/deploy_ftp.py b/scripts/deploy_ftp.py index 57b2649..dd08cbb 100755 --- a/scripts/deploy_ftp.py +++ b/scripts/deploy_ftp.py @@ -200,7 +200,7 @@ def list_remote_dir(ftp, rel_dir, strict=False): return entries -def prune_stale_files(ftp, local_files, local_dirs, dry_run): +def prune_stale_files(ftp, local_files, local_dirs, dry_run, strict=False): """Deletes remote files not present locally, scoped to directories dist manages. A remote directory with no local counterpart is never listed, so it is never touched.""" @@ -208,7 +208,7 @@ def prune_stale_files(ftp, local_files, local_dirs, dry_run): failed = [] for rel_dir in sorted(local_dirs): - for name, is_dir in list_remote_dir(ftp, rel_dir): + for name, is_dir in list_remote_dir(ftp, rel_dir, strict=strict): if is_dir: continue # only prune files; subdirectories are handled by their own entry in local_dirs rel = f"{rel_dir}/{name}" if rel_dir else name @@ -390,7 +390,7 @@ def main(): uploaded, upload_failed = upload_all(ftp, local_files, args.dry_run) print("\n-- prune stale files --") - removed, prune_failed = prune_stale_files(ftp, local_files, local_dirs, args.dry_run) + removed, prune_failed = prune_stale_files(ftp, local_files, local_dirs, args.dry_run, strict=bool(staging)) ftp.quit() diff --git a/scripts/test-staging-deploy.py b/scripts/test-staging-deploy.py index 88e3a80..9e90c1a 100644 --- a/scripts/test-staging-deploy.py +++ b/scripts/test-staging-deploy.py @@ -74,6 +74,14 @@ def test_malformed_listing_blocks_staging(self): ftp.retrlines.side_effect=lambda cmd,cb: cb("unrecognized listing") with self.assertRaises(SystemExit): d.enter_staging_root(ftp,"/staging",{""}) ftp.storbinary.assert_not_called() + def test_listing_failure_after_preflight_fails_main(self): + ftp=Mock(); ftp.pwd.return_value='/staging' + ftp.retrlines.side_effect=[None,d.ftplib.error_perm('550 listing denied')] + with patch.dict(os.environ,ENV,clear=True), patch('sys.argv',['deploy','--target','staging']), patch.object(d,'ensure_dist_self_consistent'), patch.object(d,'ensure_dist_committed'), patch.object(d,'local_files_and_dirs',return_value=({'index.html'},{''})), patch.object(d.ftplib,'FTP',return_value=ftp), patch.object(d,'upload_all',return_value=([],[])): + with self.assertRaisesRegex(SystemExit,'Cannot inspect staging directory'): + d.main() + self.assertEqual(ftp.retrlines.call_count,2) + ftp.delete.assert_not_called() def test_hostile_listing_cannot_escape(self): ftp=Mock(); ftp.retrlines.side_effect=lambda cmd,cb: cb('-rw-r--r-- 1 u g 1 Jan 1 00:00 ../outside') with self.assertRaises(SystemExit): d.prune_stale_files(ftp,set(),{''},False) From db9ef4d8f3c9d7297eea068b0896a83a5838249e Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 10 Nov 2026 22:34:24 +1100 Subject: [PATCH 09/15] fix: restore saved results visibility and session teardown --- app.js | 8 ++++++++ docs/generation-history-acceptance.md | 6 ++++-- e2e/generation-history.spec.js | 19 +++++++++++++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/app.js b/app.js index a585c48..27e46f0 100644 --- a/app.js +++ b/app.js @@ -9495,6 +9495,10 @@ function showResultsView(codeContent, auditContent) { const panel = document.getElementById("main-stage-container"); const from = currentSurfaceRect(panel); const wasResults = document.body.classList.contains("results-fullscreen"); + panel?.classList.add("visible"); + document.getElementById("ready-state")?.classList.add("hidden"); + const promptEl = document.getElementById("pipeline-submitted-prompt"); + if (promptEl) promptEl.textContent = pipelineState.submittedPrompt || ""; cancelPipelineHideTimer(); document.getElementById("pipeline-progress")?.classList.remove("visible"); setGenerationStageVisible(true); @@ -10133,6 +10137,10 @@ function resetHistory() { pipelineState.submittedPrompt = ""; document.getElementById("results-view")?.classList.remove("visible"); document.body.classList.remove("results-fullscreen", "results-with-sidebar"); + document.getElementById("main-stage-container")?.classList.remove("visible"); + const promptEl = document.getElementById("pipeline-submitted-prompt"); + if (promptEl) promptEl.textContent = ""; + setGenerationStageVisible(false); } historyResultsBundle = null; historyEpoch++; diff --git a/docs/generation-history-acceptance.md b/docs/generation-history-acceptance.md index 963e12c..beb82c5 100644 --- a/docs/generation-history-acceptance.md +++ b/docs/generation-history-acceptance.md @@ -2,7 +2,9 @@ Candidate starts at frontend c6a7ef1ee5c4219a1fdef9928812f36a2b031a49, in `/Users/home/.t3/worktrees/dreamflowCommandForFlutterFlow/t3-3d283578-bd96247123bf8c0a`. Common Git directory verified as `/Users/home/Projects/dreamflowCommandForFlutterFlow/.git`. The commit containing this document identifies the complete handoff candidate; controller acceptance remains separate. -Backend: [PR 194](https://github.com/sgardoll/buildship/pull/194) was merged externally on 10 November 2026 at 11:08:09 UTC with head `00d89badea64a62f8365d9728776d896e0e7bd04` (GitHub readback verified). The editor-schema repair is separate in [PR 195](https://github.com/sgardoll/buildship/pull/195), head `da5b58e2821cfb95ac22035439ef22bfde3ea734`. Backend controller reports independent acceptance of the combined fallback/retry/schema changes at `3296990a`, with 21 functional and 6 schema/isolation tests, and an identical source tree after cherry-picking onto current main. PR 195 was subsequently reported merged. Follow-up [PR 196](https://github.com/sgardoll/buildship/pull/196), head `4989e9c2ac48030c4ad726047e756f17b293c652`, fixes missing trigger-root metadata after reproducing the editor isFile crash with its actual classifier. Backend controller reports seven schema/isolation tests, successful GitGuardian/Entire Gates and exact-head Devin review without findings. Hosted editor sync/retest remains outstanding; no deployed service acceptance is claimed. Earlier accepted source `fadcedf02ff64e6e088cfb503cab56caf5c394e1` is historical evidence only. +Backend source evidence is historical and separate from live readiness. [PR 194](https://github.com/sgardoll/buildship/pull/194) merged externally at `00d89badea64a62f8365d9728776d896e0e7bd04`; PR 195 was subsequently reported merged. Source schema repair `4989e9c2ac48030c4ad726047e756f17b293c652` in PR 196 had passing checks, but PR 196 closed unmerged. A later live export renamed the production workflow to `service-generation-history-6f54`, upgraded REST to 2.0.2, and dropped allowedOrigins and response-body mappings. The proposed reconciliation in PR 197 is superseded by Stuart's report that he completed the repair manually and is closing that PR. Neither PR 196 nor PR 197 merge is a prerequisite now. Preserve owner changes and refresh live state before any further backend edit. + +The independent frontend review checked the API source at `4989e9c2` against `00d89bad` and found compatible request/response envelopes. This does not verify the manually edited hosted workflow. Hosted editor, HTTP/CORS and two-account staging acceptance remain unproven under STU-934. Expected response mappings are handler.body and HTTP status handler.status; the canonical frontend origin is https://customcode.connectio.com.au. ## Contract checked against accepted source @@ -20,4 +22,4 @@ Default production target retains existing host/account/password resolution and Local evidence directory: `/tmp/stu933-evidence/` (ephemeral machine-local logs). `backend-source.txt` and `backend-contract.txt` retain the source examined; `node.txt`, `ci.log`, command logs and `results.txt` record local verification. No secrets or customer exports were used. -`staging-acceptance` means **local configuration/isolation guard proof only**. STU-934 remains outstanding: actual staging host/certificate/root isolation, deployed routes and result bindings, CORS and session-verifier compatibility, staging collection/index queries, synthetic two-account list/detail/delete, and real explicit FlutterFlow redeploy. No production data was copied/deleted, no provider write or deployment occurred, and no PR/push/merge was performed. Fresh independent acceptance and the frontend PR remain pending. Recovered worker logs show 428 unit tests, 283 browser tests, build, seven accessibility shells, nine deployment checks, thirty proxy cases, bundle scan and fourteen staging checks passed on Node 22.15.1. Controller added malformed-listing rejection and post-preflight pruning failure propagation; all sixteen staging tests pass. +`staging-acceptance` means **local configuration/isolation guard proof only**. STU-934 remains outstanding: actual staging host/certificate/root isolation, deployed routes and result bindings, CORS and session-verifier compatibility, staging collection/index queries, synthetic two-account list/detail/delete, and real explicit FlutterFlow redeploy. No production data was copied/deleted and no provider deployment occurred in frontend source verification. Frontend PR 131 was subsequently created after independent acceptance at d9a4045; later review repairs require their own current-head checks. Recovered worker logs show 428 unit tests, 283 browser tests, build, seven accessibility shells, nine deployment checks, thirty proxy cases, bundle scan and fourteen staging checks passed on Node 22.15.1. Controller added malformed-listing rejection and post-preflight pruning failure propagation; all sixteen staging tests pass. diff --git a/e2e/generation-history.spec.js b/e2e/generation-history.spec.js index ff6f7d8..43428f0 100644 --- a/e2e/generation-history.spec.js +++ b/e2e/generation-history.spec.js @@ -49,6 +49,12 @@ for (const reviewed of [true,false]) test(`recover multi-artifact results review await expect(page.locator('#history-status')).toContainText('Wait for generation'); await page.evaluate(()=>window.__CCC_HISTORY_TEST__.pending(false)); await page.getByRole('button',{name:'Open in Results',exact:true}).click(); + await expect(page.locator('#main-stage-container')).toHaveClass(/visible/); + await expect(page.locator('#main-stage-container')).toBeVisible(); + await expect(page.locator('#main-stage-container')).toHaveCSS('opacity','1'); + await expect(page.locator('#main-stage-container')).toHaveCSS('pointer-events','auto'); + await page.locator('#artifact-tabs button').first().click(); + await expect(page.locator('#pipeline-submitted-prompt')).toHaveText('Synthetic prompt'); const state=await page.evaluate(()=>window.__CCC_HISTORY_TEST__.state()); expect(state.artifactBundle.artifacts).toHaveLength(2); expect(state.submittedPrompt).toBe('Synthetic prompt'); if(reviewed) expect(state.bundleReview.artifacts[0].fixedCode).toContain('int x'); else expect(state.step3Result).toBeNull(); @@ -179,3 +185,16 @@ for(const valid of [true,false]) test(`restored code passes through configured d await expect(page.locator('#api-keys-modal')).toBeHidden(); expect(forbidden).toEqual([]); }); + + test('sign out after opening saved results restores the home composer', async ({page}) => { + await historySetup(page); + await page.evaluate(()=>document.getElementById('pipeline-submitted-prompt').textContent='Earlier private prompt'); + await page.getByRole('button',{name:'saved',exact:true}).click(); + await page.getByRole('button',{name:'Open in Results',exact:true}).click(); + await expect(page.locator('#pipeline-submitted-prompt')).toHaveText(''); + await page.evaluate(()=>window.handleSignOut()); + await expect(page.locator('#generation-stage')).toBeHidden(); + await expect(page.locator('#hero')).toBeVisible(); + await expect(page.locator('#composer')).toBeVisible(); + await expect(page.locator('#main-stage-container')).not.toHaveClass(/visible/); + }); From 2613dc45f9d58bfea043c06aed84df0d442cbdb4 Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 10 Nov 2026 22:50:51 +1100 Subject: [PATCH 10/15] fix: resolve account-scoped generation identity from app sessions --- app.js | 67 +++++++++++++++++++++++-- docs/generation-history-acceptance.md | 4 ++ docs/generation-history-account-auth.md | 11 ++++ e2e/fixtures/apiFixtures.js | 4 +- e2e/generation-session.spec.js | 47 +++++++++++++++++ src/generationSession.js | 50 ++++++++++++++++++ src/generationSession.test.js | 44 ++++++++++++++++ 7 files changed, 223 insertions(+), 4 deletions(-) create mode 100644 docs/generation-history-account-auth.md create mode 100644 e2e/generation-session.spec.js create mode 100644 src/generationSession.js create mode 100644 src/generationSession.test.js diff --git a/app.js b/app.js index 27e46f0..9848241 100644 --- a/app.js +++ b/app.js @@ -1,3 +1,4 @@ +import { createGenerationSessionClient } from './src/generationSession.js'; import { createGenerationHistoryClient, recoverGenerationHistory } from './src/generationHistory.js'; import { resolveGenerationHistoryEndpoint } from './src/generationHistoryConfig.js'; import posthog from "posthog-js"; @@ -173,13 +174,13 @@ let subscriptionState = createSubscriptionState({ isResolved: true }) let sessionReadiness = Promise.resolve() // --- PIPELINE --- -const PIPELINE_ENDPOINT = `${BUILDSHIP_BASE_URL}/service/runpipeline` +const PIPELINE_ENDPOINT = `${BUILDSHIP_BASE_URL}${import.meta.env.VITE_HISTORY_TARGET === 'staging' ? '/staging' : ''}/service/runpipeline` // --- IDENTITY RESOLUTION --- const IDENTITY_COOKIE_KEY = 'bs_identity' const IDENTITY_SESSION_KEY = 'bs_user_id' const IDENTITY_TOKEN_KEY = 'bs_identity_token' -const IDENTITY_ENDPOINT = `${BUILDSHIP_BASE_URL}/authUserCheck` +const IDENTITY_ENDPOINT = `${BUILDSHIP_BASE_URL}${import.meta.env.VITE_HISTORY_TARGET === 'staging' ? '/staging' : ''}/authUserCheck` let identityState = { userId: null, @@ -188,6 +189,38 @@ let identityState = { resolved: false, } +let identityEpoch = 0; +// Obtain a fresh anonymous proof; persisted tokens may have expired or been claimed. +let legacyIdentityToken = null; +const generationSessionClient = createGenerationSessionClient({ + endpoint: IDENTITY_ENDPOINT, + getSession: () => ({ token: authState.sessionToken, key: authState.isVerified ? authState.email : null }), + getLegacyToken: async () => { + if (!legacyIdentityToken) { + let timer; + try { await Promise.race([resolveIdentity(), new Promise(resolve => { timer = setTimeout(resolve, 5000); })]); } + finally { clearTimeout(timer); } + } + return legacyIdentityToken; + }, +}); +function resetGenerationIdentity() { + identityEpoch++; + legacyIdentityToken = null; + generationSessionClient.invalidate(); + identityResolvePromise = null; + identityState = { userId: null, token: null, status: null, resolved: false }; +} +async function ensureAccountGenerationIdentity() { + const epoch = identityEpoch; + const token = authState.sessionToken; + const result = await generationSessionClient.ensure(); + if (epoch !== identityEpoch || token !== authState.sessionToken || !authState.isVerified) { + throw new DOMException('Account session changed', 'AbortError'); + } + identityState = { ...result, status: 'account', resolved: true }; +} + // --- TIER LIMITS --- // Single source of truth in src/plansSurface.js so the plans page, the // paywall and generation gating agree (STU-382 criterion 1). @@ -6087,6 +6120,13 @@ async function refreshSession(sessionToken) { function saveSession(email, sessionToken) { resetHistory(); + if (authState.isVerified && authState.email !== email) { + invalidatePipelineRun(); + abortPipelineRequests(); + pipelineState.isRunning = false; + setRunPipelineButtonBusy(false); + } + resetGenerationIdentity(); const storedSession = getStoredSession() const sessionChanged = (authState.email || storedSession.email) !== email authState.email = email @@ -6095,10 +6135,16 @@ function saveSession(email, sessionToken) { subscriptionState = createSubscriptionState({ isLoading: true }) localStorage.setItem(AUTH_SESSION_STORAGE_KEY, JSON.stringify({ email, sessionToken })) if (sessionChanged) clearSubscriptionCache() + void ensureAccountGenerationIdentity().catch(() => {}); } function clearSession() { resetHistory(); + resetGenerationIdentity(); + invalidatePipelineRun(); + abortPipelineRequests(); + pipelineState.isRunning = false; + setRunPipelineButtonBusy(false); authState.email = null authState.sessionToken = null authState.isVerified = false @@ -6264,6 +6310,11 @@ async function handleMagicLinkRequest() { function handleSignOut() { resetHistory(); + resetGenerationIdentity(); + invalidatePipelineRun(); + abortPipelineRequests(); + pipelineState.isRunning = false; + setRunPipelineButtonBusy(false); // Reset in-memory auth/subscription state first so the immediate re-render // below reflects a signed-out identity/plan. authState.email = null @@ -6374,6 +6425,7 @@ function getOrCreateCookieId() { } async function resolveIdentity() { + const epoch = identityEpoch; try { if (typeof FingerprintJS === 'undefined') { console.warn('resolveIdentity: FingerprintJS not loaded, skipping') @@ -6395,6 +6447,9 @@ async function resolveIdentity() { } const data = await response.json() + if (epoch !== identityEpoch) return; + legacyIdentityToken = data.identity_token || null; + if (authState.isVerified) return; identityState.userId = data.user_id identityState.token = data.identity_token || null identityState.status = data.status @@ -6421,6 +6476,7 @@ async function resolveIdentity() { let identityResolvePromise = null function ensureIdentityReady(maxWaitMs = 5000) { + if (authState.isVerified) return ensureAccountGenerationIdentity(); if (identityState.resolved) return Promise.resolve() if (!identityResolvePromise) { identityResolvePromise = resolveIdentity().catch((err) => { @@ -7073,6 +7129,7 @@ function abortPipelineRequests() { } async function callBuildShip(step, model, prompt, context = {}, images = []) { + if (authState.isVerified) await ensureAccountGenerationIdentity(); const BUILDSHIP_TIMEOUT_MS = 120000 const controller = new AbortController() activeBuildShipControllers.add(controller) @@ -10164,7 +10221,11 @@ async function historyTask(action) { historyClient.invalidate(); historyEl('status').textContent = 'Loading history…'; historyEl('panel').setAttribute('aria-busy', 'true'); - try { await action(() => epoch === historyEpoch); } + try { + await ensureAccountGenerationIdentity(); + if (epoch !== historyEpoch) return; + await action(() => epoch === historyEpoch); + } catch (error) { if (epoch === historyEpoch && error.name !== 'AbortError') historyEl('status').textContent = error.status === 401 ? 'Session expired. Sign in again, then refresh.' : diff --git a/docs/generation-history-acceptance.md b/docs/generation-history-acceptance.md index beb82c5..a08a580 100644 --- a/docs/generation-history-acceptance.md +++ b/docs/generation-history-acceptance.md @@ -6,6 +6,10 @@ Backend source evidence is historical and separate from live readiness. [PR 194] The independent frontend review checked the API source at `4989e9c2` against `00d89bad` and found compatible request/response envelopes. This does not verify the manually edited hosted workflow. Hosted editor, HTTP/CORS and two-account staging acceptance remain unproven under STU-934. Expected response mappings are handler.body and HTTP status handler.status; the canonical frontend origin is https://customcode.connectio.com.au. +## Account authentication correction + +The earlier compatibility review missed that real sign-in sessions contain email rather than user_id. Its authentication conclusion is withdrawn. See [account identity repair](generation-history-account-auth.md) for the coordinated `/authUserCheck` bootstrap and session lifecycle. Backend repair and current-head acceptance are required before readiness; historical tests below do not prove live account ownership. + ## Contract checked against accepted source Read-only source: `/Users/home/Projects/buildship/workflows/service-generation-history-Hst1/nodes/history-api/main.ts`, plus workflow `triggers.json`. The worker compared these API files at the earlier accepted source. Subsequent backend fallback/schema changes require final controller pairing verification; the endpoint envelope is reported unchanged. Compared with `src/generationHistory.js`, its synthetic unit fixtures, and `e2e/generation-history.spec.js`. diff --git a/docs/generation-history-account-auth.md b/docs/generation-history-account-auth.md new file mode 100644 index 0000000..156f2d4 --- /dev/null +++ b/docs/generation-history-account-auth.md @@ -0,0 +1,11 @@ +# Account identity repair + +The original history implementation confused an email app-session JWT with a pipeline identity JWT. A live email session was rejected by the history verifier. Earlier synthetic-token source acceptance does not prove this integration. + +The frontend now calls the existing POST `/authUserCheck` (staging `/staging/authUserCheck`) with JSON `{sessionToken, identityToken?}`. The session token is the verified sign-in session; the optional identity token is fresh legacy proof obtained from the anonymous resolver, never a submitted owner ID. No Authorization header is required by this resolver contract. The backend owns signature verification and immutable account-to-identity association. It reuses an established account marker; first linkage may adopt only a proven unclaimed/same-account legacy identity, and foreign proof produces a distinct account identity without exposing foreign history. + +The resolver returns `{user_id, identity_token, ...}`. The frontend retains the account credentials only in memory and refreshes them before signed-in pipeline calls, including retries/refinements. The backend caps their expiry at the app session expiry. History list/detail/delete retain `Authorization: Bearer ` and are sent only after account bootstrap succeeds. History never authenticates using the device token. Staging resolver, history and pipeline routes all use `/staging/` and require the backend's isolated collection bindings. + +Sign-in/session rotation and sign-out invalidate pending account resolutions. Account changes also cancel an active generation. Late anonymous or account responses cannot replace the current account's identity. Bridge failure blocks signed-in generation/history rather than falling back to anonymous access. Anonymous generation keeps its existing resolver path; the backend must refuse anonymous capabilities for an identity already claimed by an account. + +Evidence is synthetic and local: unit tests exercise real email-session-shaped request semantics, owner-field omission, delayed response rejection, logout, malformed responses and retry. Browser tests check email-vs-generation token separation, account A→B switching during a delayed bridge, and fail-closed behavior. Full-suite and independent-review results are recorded with the PR head. Backend source/emulator acceptance, deployment, CORS, real authenticated reads, two-account isolation and editor retest remain separate; no live writes or deployment are authorized by these tests. Preserve Stuart's manual backend workflow changes. diff --git a/e2e/fixtures/apiFixtures.js b/e2e/fixtures/apiFixtures.js index 0047d92..5c21b5f 100644 --- a/e2e/fixtures/apiFixtures.js +++ b/e2e/fixtures/apiFixtures.js @@ -496,7 +496,9 @@ const VENDORED_SRI_ASSETS = [ */ export async function applyDefaultRoutes(page, overrides = {}) { const routes = { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.identity]: request => request.postDataJSON()?.sessionToken + ? ok({user_id:"account-test-0001",identity_token:"synthetic-account-generation-token",status:"recognized"}) + : guestIdentity(), [ENDPOINTS.authSendMagicLink]: magicLinkSent(), [ENDPOINTS.authVerifyMagicLink]: signedInSession(), [ENDPOINTS.authRefreshSession]: signedInSession(), diff --git a/e2e/generation-session.spec.js b/e2e/generation-session.spec.js new file mode 100644 index 0000000..1a37a5a --- /dev/null +++ b/e2e/generation-session.spec.js @@ -0,0 +1,47 @@ +import {test, expect} from '@playwright/test'; +import {applyDefaultRoutes, ENDPOINTS, ok} from './fixtures/apiFixtures.js'; +const emailJwt = email => `${Buffer.from('{"alg":"HS256"}').toString('base64url')}.${Buffer.from(JSON.stringify({email,iat:1,exp:9999999999})).toString('base64url')}.synthetic-signature`; +async function setup(page) { + const token=emailJwt('a@example.com'); + await page.addInitScript(token=>{localStorage.setItem('hasSeenWalkthrough','true');localStorage.setItem('ccc_auth_session',JSON.stringify({email:'a@example.com',sessionToken:token}));},token); + await applyDefaultRoutes(page,{[ENDPOINTS.authRefreshSession]:ok({email:'a@example.com',sessionToken:token}),[ENDPOINTS.identity]:ok({user_id:'legacy-device',identity_token:'signed-legacy-proof',status:'recognized'})}); + return token; +} +test('email session bootstraps account identity; history keeps email token and pipeline uses scoped token',async({page})=>{ + const token=await setup(page);let bridgeCalls=0;let historyCalls=0;let pipelineCalls=0; + await page.route(ENDPOINTS.identity,r=>{ + if (!r.request().postDataJSON().sessionToken) return r.fallback(); + bridgeCalls++; + expect(r.request().postDataJSON()).toEqual({sessionToken:token,identityToken:'signed-legacy-proof'}); + return r.fulfill({json:{user_id:'account-owner',identity_token:'signed-account-proof'}}); + }); + await page.route('**/service/generation-history',r=>{historyCalls++;expect(r.request().headers().authorization).toBe(`Bearer ${token}`);return r.fulfill({json:{items:[],nextCursor:null}});}); + await page.route(ENDPOINTS.pipeline,r=>{pipelineCalls++;expect(r.request().headers().authorization).toBe('Bearer signed-account-proof');expect(r.request().postDataJSON().user_id).toBe('account-owner');return r.fulfill({status:503,json:{error:'Synthetic stop'}});}); + await page.goto('/#account');await expect(page.locator('#topbar-avatar')).toContainText('A'); + await page.locator('#history-refresh').click();await expect(page.locator('#history-status')).toContainText('No saved');expect(historyCalls).toBe(1); + await page.evaluate(()=>window.switchView('home'));await page.locator('#pipeline-input').fill('Build a calendar');await page.locator('#hero-send').click(); + await expect.poll(()=>pipelineCalls).toBeGreaterThan(0);expect(bridgeCalls).toBeGreaterThan(0); +}); +test('delayed account A bridge cannot replace account B credentials',async({page})=>{ + const a=await setup(page),b=emailJwt('b@example.com');let release;let historyCalls=0; + await page.route(ENDPOINTS.identity,async r=>{ + if (!r.request().postDataJSON().sessionToken) return r.fallback(); + if(r.request().postDataJSON().sessionToken===a) { await new Promise(resolve=>release=resolve);await r.fulfill({json:{user_id:'owner-a',identity_token:'scope-a'}}).catch(()=>{}); } + else { expect(r.request().postDataJSON().sessionToken).toBe(b);await r.fulfill({json:{user_id:'owner-b',identity_token:'scope-b'}}); } + }); + await page.route('**/service/generation-history',r=>{historyCalls++;expect(r.request().headers().authorization).toBe(`Bearer ${b}`);return r.fulfill({json:{items:[],nextCursor:null}});}); + await page.route(ENDPOINTS.pipeline,r=>{expect(r.request().headers().authorization).toBe('Bearer scope-b');expect(r.request().postDataJSON().user_id).toBe('owner-b');return r.fulfill({status:503,json:{error:'Synthetic stop'}});}); + await page.goto('/#account');await expect.poll(()=>!!release).toBe(true); + await page.evaluate(token=>window.__CCC_HISTORY_TEST__.session('b@example.com',token),b); + release();await page.locator('#history-refresh').click();await expect(page.locator('#history-status')).toContainText('No saved');expect(historyCalls).toBe(1); + const request=page.waitForRequest(ENDPOINTS.pipeline);await page.evaluate(()=>window.switchView('home'));await page.locator('#pipeline-input').fill('Account B code');await page.locator('#hero-send').click();await request; +}); +test('failed bridge blocks history and generation rather than using legacy identity',async({page})=>{ + await setup(page);let forbidden=0; + await page.route(ENDPOINTS.identity,r=>r.request().postDataJSON().sessionToken ? r.fulfill({status:503,json:{error:'Unavailable'}}) : r.fallback()); + await page.route('**/service/generation-history',r=>{forbidden++;return r.abort();}); + await page.route(ENDPOINTS.pipeline,r=>{forbidden++;return r.abort();}); + await page.goto('/#account');await expect(page.locator('#topbar-avatar')).toContainText('A');await page.locator('#history-refresh').click();await expect(page.locator('#history-status')).toContainText('Try again'); + await page.evaluate(()=>window.switchView('home'));await page.locator('#pipeline-input').fill('Must not run');await page.locator('#hero-send').click(); + await expect.poll(()=>page.evaluate(()=>window.__CCC_HISTORY_TEST__.state().isRunning)).toBe(false);expect(forbidden).toBe(0); +}); diff --git a/src/generationSession.js b/src/generationSession.js new file mode 100644 index 0000000..68975df --- /dev/null +++ b/src/generationSession.js @@ -0,0 +1,50 @@ +// Account generation credentials are never persisted or used to authenticate history. +export function createGenerationSessionClient({ endpoint, getSession, getLegacyToken, fetchImpl = fetch }) { + let epoch = 0; + let pending = null; + const stale = () => new DOMException('Account session changed', 'AbortError'); + function invalidate() { + epoch++; + pending?.controller.abort(); + pending = null; + } + async function ensure() { + const session = getSession(); + if (!session?.token || !session?.key) throw new Error('Sign in to prepare generation.'); + if (pending?.token === session.token && pending.key === session.key) return pending.promise; + invalidate(); + const currentEpoch = epoch; + const controller = new AbortController(); + const current = () => { + const now = getSession(); + return epoch === currentEpoch && now?.token === session.token && now?.key === session.key; + }; + const task = { token: session.token, key: session.key, controller }; + task.promise = (async () => { + const timer = setTimeout(() => controller.abort(), 15000); + try { + const identityToken = await getLegacyToken(); + if (!current()) throw stale(); + const response = await fetchImpl(endpoint, { + method: 'POST', signal: controller.signal, + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ sessionToken: session.token, ...(identityToken ? { identityToken } : {}) }), + }); + if (!current()) throw stale(); + if (!response.ok) throw new Error('Account generation access could not be prepared. Please retry.'); + const data = await response.json(); + if (!current()) throw stale(); + if (typeof data?.user_id !== 'string' || !data.user_id || typeof data.identity_token !== 'string' || !data.identity_token) { + throw new Error('Invalid account generation session.'); + } + return { userId: data.user_id, token: data.identity_token }; + } finally { + clearTimeout(timer); + if (pending === task) pending = null; + } + })(); + pending = task; + return task.promise; + } + return { ensure, invalidate }; +} diff --git a/src/generationSession.test.js b/src/generationSession.test.js new file mode 100644 index 0000000..e91edab --- /dev/null +++ b/src/generationSession.test.js @@ -0,0 +1,44 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createGenerationSessionClient } from './generationSession.js'; +const session = { key: 'a@example.com', token: 'email-session-jwt' }; +const response = (user_id = 'account-a') => ({ ok: true, json: async () => ({ user_id, identity_token: `signed-${user_id}` }) }); +test('bridge authenticates email session; legacy token is proof only, no caller owner fields', async () => { + const client = createGenerationSessionClient({ endpoint: '/authUserCheck', getSession: () => session, getLegacyToken: async () => 'legacy-signed', fetchImpl: async (url, init) => { + assert.equal(url, '/authUserCheck'); + assert.equal(init.headers.Authorization, undefined); + assert.deepEqual(JSON.parse(init.body), { sessionToken: 'email-session-jwt', identityToken: 'legacy-signed' }); + return response(); + } }); + assert.deepEqual(await client.ensure(), { userId: 'account-a', token: 'signed-account-a' }); +}); +test('missing legacy identity sends only session token; server identity is authoritative', async () => { + const client = createGenerationSessionClient({ endpoint: '/bridge', getSession: () => session, getLegacyToken: async () => null, fetchImpl: async (_, init) => { assert.deepEqual(JSON.parse(init.body), { sessionToken: 'email-session-jwt' }); return response('new-owner'); } }); + assert.equal((await client.ensure()).userId, 'new-owner'); +}); +test('account switch rejects old delayed response, even if transport ignores abort', async () => { + let current = session, release, entered; + const started = new Promise(r => entered = r); + const client = createGenerationSessionClient({ endpoint: '/bridge', getSession: () => current, getLegacyToken: async () => null, fetchImpl: async (_, init) => { + if (JSON.parse(init.body).sessionToken === 'email-session-jwt') { entered(); await new Promise(r => release = r); return response(); } + return response('account-b'); + } }); + const old = client.ensure(); await started; + current = { key: 'b@example.com', token: 'email-b' }; client.invalidate(); + assert.equal((await client.ensure()).userId, 'account-b'); + release(); await assert.rejects(old, { name: 'AbortError' }); +}); +test('logout while obtaining proof prevents bridge request', async () => { + let current = session, release; + const proof = new Promise(r => release = r); + const client = createGenerationSessionClient({ endpoint: '/bridge', getSession: () => current, getLegacyToken: () => proof, fetchImpl: () => { throw new Error('Must not request'); } }); + const pending = client.ensure(); current = null; client.invalidate(); release('legacy'); + await assert.rejects(pending, { name: 'AbortError' }); +}); +test('bridge errors and malformed credentials fail closed and allow retry', async () => { + let count = 0; + const client = createGenerationSessionClient({ endpoint: '/bridge', getSession: () => session, getLegacyToken: async () => null, fetchImpl: async () => ++count === 1 ? { ok: false } : count === 2 ? { ok: true, json: async () => ({ user_id: 'a' }) } : response() }); + await assert.rejects(client.ensure(), /could not be prepared/); + await assert.rejects(client.ensure(), /Invalid/); + assert.equal((await client.ensure()).userId, 'account-a'); +}); From 64d43e48a5bed523bed9a9b0f4d1be92491e59da Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 10 Nov 2026 22:55:29 +1100 Subject: [PATCH 11/15] fix: cancel stale account bootstrap before pipeline fallback --- app.js | 12 ++++++++++- e2e/generation-session.spec.js | 31 ++++++++++++++++++++++++++- e2e/smoke.spec.js | 14 ++++++------ e2e/stu376-composer.spec.js | 4 ++-- e2e/stu377-pipeline-progress.spec.js | 4 ++-- e2e/stu381-monthly-usage.spec.js | 4 ++-- e2e/stu382-plans-paywall.spec.js | 4 ++-- e2e/stu383-account-overview.spec.js | 4 ++-- e2e/stu384-connection.spec.js | 4 ++-- e2e/stu385-composer-settings.spec.js | 10 ++++----- e2e/stu386-magic-link-signin.spec.js | 22 +++++++++---------- e2e/stu390-logo-loop.spec.js | 4 ++-- e2e/stu394-generation-trigger.spec.js | 4 ++-- 13 files changed, 80 insertions(+), 41 deletions(-) diff --git a/app.js b/app.js index 9848241..c844c91 100644 --- a/app.js +++ b/app.js @@ -4942,6 +4942,7 @@ async function runPromptArchitect(userInput, images = []) { } async function runCodeGenerator(masterPrompt, selectedModel, images = [], runId) { + const generationRunId = runId ?? pipelineState.runId; const prompt = buildGeneratorPrompt(masterPrompt) const context = createBuildShipContext("generator", pipelineState.bundleSpec) try { @@ -4956,6 +4957,10 @@ async function runCodeGenerator(masterPrompt, selectedModel, images = [], runId) // A cancelled request is a stale run, not a model problem: it must not // trigger a second request on the fallback model. if (primaryError.isPipelineCancel) throw primaryError + if (!isCurrentPipelineRun(generationRunId)) { + primaryError.isPipelineCancel = true; + throw primaryError; + } if (selectedModel !== FALLBACK_MODEL) { console.warn(`Code Generator failed with ${selectedModel}, retrying with fallback model:`, primaryError.message) // The fallback is a real service event, so the run says so while it @@ -7129,7 +7134,8 @@ function abortPipelineRequests() { } async function callBuildShip(step, model, prompt, context = {}, images = []) { - if (authState.isVerified) await ensureAccountGenerationIdentity(); + const requestRunId = pipelineState.runId; + const requestIdentityEpoch = identityEpoch; const BUILDSHIP_TIMEOUT_MS = 120000 const controller = new AbortController() activeBuildShipControllers.add(controller) @@ -7140,6 +7146,10 @@ async function callBuildShip(step, model, prompt, context = {}, images = []) { }, BUILDSHIP_TIMEOUT_MS) try { + if (authState.isVerified) await ensureAccountGenerationIdentity(); + if (!isCurrentPipelineRun(requestRunId) || requestIdentityEpoch !== identityEpoch || controller.signal.aborted) { + throw new DOMException("Pipeline session changed", "AbortError"); + } const res = await fetch(PIPELINE_ENDPOINT, { method: 'POST', headers: { diff --git a/e2e/generation-session.spec.js b/e2e/generation-session.spec.js index 1a37a5a..1a1a48b 100644 --- a/e2e/generation-session.spec.js +++ b/e2e/generation-session.spec.js @@ -1,5 +1,5 @@ import {test, expect} from '@playwright/test'; -import {applyDefaultRoutes, ENDPOINTS, ok} from './fixtures/apiFixtures.js'; +import {applyDefaultRoutes, ENDPOINTS, ok, professionalSubscription} from './fixtures/apiFixtures.js'; const emailJwt = email => `${Buffer.from('{"alg":"HS256"}').toString('base64url')}.${Buffer.from(JSON.stringify({email,iat:1,exp:9999999999})).toString('base64url')}.synthetic-signature`; async function setup(page) { const token=emailJwt('a@example.com'); @@ -45,3 +45,32 @@ test('failed bridge blocks history and generation rather than using legacy ident await page.evaluate(()=>window.switchView('home'));await page.locator('#pipeline-input').fill('Must not run');await page.locator('#hero-send').click(); await expect.poll(()=>page.evaluate(()=>window.__CCC_HISTORY_TEST__.state().isRunning)).toBe(false);expect(forbidden).toBe(0); }); +test('switch during generator bootstrap cancels without fallback under the new account',async({page})=>{ + const a=await setup(page),b=emailJwt('b@example.com');let release;let architectDone=false;const calls=[]; + await page.route(ENDPOINTS.getSubscription,r=>r.fulfill(professionalSubscription())); + await page.route(ENDPOINTS.identity,async r=>{ + const body=r.request().postDataJSON(); + if(!body.sessionToken) return r.fallback(); + if(body.sessionToken===a && architectDone) { + await new Promise(resolve=>release=resolve); + await r.fulfill({json:{user_id:'owner-a',identity_token:'scope-a'}}).catch(()=>{}); + } else await r.fulfill({json:{user_id:body.sessionToken===a?'owner-a':'owner-b',identity_token:body.sessionToken===a?'scope-a':'scope-b'}}); + }); + await page.route(ENDPOINTS.pipeline,r=>{ + const body=r.request().postDataJSON();calls.push({step:body.step,token:r.request().headers().authorization}); + architectDone=true;return r.fulfill({json:{output:JSON.stringify({schemaVersion:'artifact-bundle/v1',artifacts:[{id:'widget',artifactType:'CodeFile',artifactName:'Widget',fileName:'widget.dart',code:'class Widget {}'}]})}}); + }); + await page.goto('/');await expect(page.locator('#topbar-avatar')).toContainText('A'); + await page.getByRole('button',{name:'Generation settings',exact:true}).click(); + await page.locator('#composer-settings-model').selectOption('anthropic/claude-opus-5'); + await page.locator('#composer-settings-modal').getByRole('button',{name:'Done',exact:true}).click(); + await page.locator('#pipeline-input').fill('Account A private prompt'); + await page.evaluate(()=>{window.__accountSwitchRun = window.runThinkingPipeline();}); + await expect.poll(()=>!!release).toBe(true); + await page.evaluate(token=>window.__CCC_HISTORY_TEST__.session('b@example.com',token),b); + release(); + await expect.poll(()=>page.evaluate(()=>window.__CCC_HISTORY_TEST__.state().isRunning)).toBe(false); + // Await the actual abandoned run, not the flag cleared immediately by sign-out. + await page.evaluate(()=>window.__accountSwitchRun); + expect(calls).toEqual([{step:'architect',token:'Bearer scope-a'}]); +}); diff --git a/e2e/smoke.spec.js b/e2e/smoke.spec.js index df1224e..438a8fe 100644 --- a/e2e/smoke.spec.js +++ b/e2e/smoke.spec.js @@ -1,7 +1,7 @@ import { test, expect } from "@playwright/test"; import { applyDefaultRoutes, - guestIdentity, + freeSubscription, professionalSubscription, powerSubscription, @@ -46,7 +46,7 @@ test.describe("Redesigned hero landing and composer", () => { // itself is verified in the STU-445 composer suite. await page.emulateMedia({ reducedMotion: "reduce" }); await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.getSubscription]: freeSubscription(), }); @@ -80,7 +80,7 @@ test.describe("Redesigned hero landing and composer", () => { test("composer accepts input and reflects typed state", async ({ page }) => { await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.getSubscription]: freeSubscription(), }); @@ -99,7 +99,7 @@ test.describe("Redesigned hero landing and composer", () => { test("guest usage badge shows the intercepted free allowance", async ({ page }) => { await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.getSubscription]: freeSubscription(), }); @@ -113,7 +113,7 @@ test.describe("Redesigned hero landing and composer", () => { test("signed-in Professional badge is rendered from fixture", async ({ page }) => { await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.getSubscription]: professionalSubscription(), }); @@ -137,7 +137,7 @@ test.describe("Redesigned hero landing and composer", () => { test("signed-in Power badge is rendered from fixture", async ({ page }) => { await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.getSubscription]: powerSubscription(), }); @@ -160,7 +160,7 @@ test.describe("Redesigned hero landing and composer", () => { test("unresolved subscription surfaces the unavailable plan state", async ({ page }) => { await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.getSubscription]: unresolvedSubscription(), }); diff --git a/e2e/stu376-composer.spec.js b/e2e/stu376-composer.spec.js index d00d704..e265a23 100644 --- a/e2e/stu376-composer.spec.js +++ b/e2e/stu376-composer.spec.js @@ -1,7 +1,7 @@ import { test, expect } from "@playwright/test"; import { applyDefaultRoutes, - guestIdentity, + freeSubscription, oneArtifact, rejectedGeneration, @@ -79,7 +79,7 @@ test.beforeEach(async ({ page }) => { } }); await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.getSubscription]: freeSubscription(), }); }); diff --git a/e2e/stu377-pipeline-progress.spec.js b/e2e/stu377-pipeline-progress.spec.js index 7c3bf7f..6ea5ef8 100644 --- a/e2e/stu377-pipeline-progress.spec.js +++ b/e2e/stu377-pipeline-progress.spec.js @@ -3,7 +3,7 @@ import { applyDefaultRoutes, ENDPOINTS, freeSubscription, - guestIdentity, + oneArtifact, professionalSubscription, providerError, @@ -69,7 +69,7 @@ async function openHome(page, overrides = {}) { localStorage.setItem("hasSeenWalkthrough", "true"); }); await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.getSubscription]: freeSubscription(), ...overrides, }); diff --git a/e2e/stu381-monthly-usage.spec.js b/e2e/stu381-monthly-usage.spec.js index 2db199f..4b434ef 100644 --- a/e2e/stu381-monthly-usage.spec.js +++ b/e2e/stu381-monthly-usage.spec.js @@ -1,7 +1,7 @@ import { test, expect } from "@playwright/test"; import { applyDefaultRoutes, - guestIdentity, + freeSubscription, professionalSubscription, powerSubscription, @@ -293,7 +293,7 @@ test.describe("STU-381 monthly usage metering", () => { test("a signed-out guest's Manage Subscription follows the sign-in path", async ({ page }) => { let calls = 0; await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.createPortal]: () => { calls += 1; return portalSession(); diff --git a/e2e/stu382-plans-paywall.spec.js b/e2e/stu382-plans-paywall.spec.js index 2b1d567..d775b20 100644 --- a/e2e/stu382-plans-paywall.spec.js +++ b/e2e/stu382-plans-paywall.spec.js @@ -1,7 +1,7 @@ import { test, expect } from "@playwright/test"; import { applyDefaultRoutes, - guestIdentity, + freeSubscription, professionalSubscription, unresolvedSubscription, @@ -311,7 +311,7 @@ test.describe("STU-382 plans surface and paywall states", () => { test("C4/C1: keyboard-reachable sign-in, upgrade and Manage actions render correctly", async ({ page }) => { // Guest account view: Sign In and Upgrade are keyboard-focusable on mobile. await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.getSubscription]: freeSubscription(), }); await page.setViewportSize({ width: 360, height: 800 }); diff --git a/e2e/stu383-account-overview.spec.js b/e2e/stu383-account-overview.spec.js index fdf7eb1..4269913 100644 --- a/e2e/stu383-account-overview.spec.js +++ b/e2e/stu383-account-overview.spec.js @@ -1,7 +1,7 @@ import { test, expect } from "@playwright/test"; import { applyDefaultRoutes, - guestIdentity, + freeSubscription, professionalSubscription, powerSubscription, @@ -214,7 +214,7 @@ test.describe("STU-383 account overview", () => { test("a guest sees the anonymous Free allowance, never a signed-in overview", async ({ page }) => { await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + }); await page.goto("/"); await openAccount(page); diff --git a/e2e/stu384-connection.spec.js b/e2e/stu384-connection.spec.js index 05a909b..495b196 100644 --- a/e2e/stu384-connection.spec.js +++ b/e2e/stu384-connection.spec.js @@ -1,7 +1,7 @@ import { test, expect } from "@playwright/test"; import { applyDefaultRoutes, - guestIdentity, + signedInSession, freeSubscription, ok, @@ -1171,7 +1171,7 @@ test.describe("STU-384 account connection", () => { test("signed-out entry can still save the key without a connection card", async ({ page }) => { // No session seeded: the account view shows the signed-out prompt. await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + }); await page.goto("/"); diff --git a/e2e/stu385-composer-settings.spec.js b/e2e/stu385-composer-settings.spec.js index c394e19..1e02447 100644 --- a/e2e/stu385-composer-settings.spec.js +++ b/e2e/stu385-composer-settings.spec.js @@ -3,7 +3,7 @@ import { applyDefaultRoutes, ENDPOINTS, freeSubscription, - guestIdentity, + oneArtifact, professionalSubscription, unresolvedSubscription, @@ -82,7 +82,7 @@ test.beforeEach(async ({ page }) => { test.describe("model availability by subscription tier", () => { test("free plan labels Pro models and offers a transparent upgrade", async ({ page }) => { await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.getSubscription]: freeSubscription(), }); await page.goto("/"); @@ -222,7 +222,7 @@ test.describe("the dialog stays wired to the generation request", () => { page, }) => { await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.getSubscription]: freeSubscription(), }); await page.goto("/"); @@ -241,7 +241,7 @@ test.describe("the dialog stays wired to the generation request", () => { test.describe("focus and walkthrough behaviour around the dialog", () => { test("closing the dialog returns focus to the composer", async ({ page }) => { await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.getSubscription]: freeSubscription(), }); await page.goto("/"); @@ -256,7 +256,7 @@ test.describe("focus and walkthrough behaviour around the dialog", () => { test("an ordinary close never reopens the walkthrough", async ({ page }) => { await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.getSubscription]: freeSubscription(), }); await page.goto("/"); diff --git a/e2e/stu386-magic-link-signin.spec.js b/e2e/stu386-magic-link-signin.spec.js index 934fa89..ad9291c 100644 --- a/e2e/stu386-magic-link-signin.spec.js +++ b/e2e/stu386-magic-link-signin.spec.js @@ -1,7 +1,7 @@ import { test, expect } from "@playwright/test"; import { applyDefaultRoutes, - guestIdentity, + freeSubscription, professionalSubscription, signedInSession, @@ -29,7 +29,7 @@ test.describe("Magic-link sign-in", () => { test("rejects an invalid email inline without calling the backend", async ({ page }) => { let sendCalled = false; await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.getSubscription]: freeSubscription(), }); await page.route(ENDPOINTS.authSendMagicLink, async (route) => { @@ -54,7 +54,7 @@ test.describe("Magic-link sign-in", () => { test("sends a link, then leaves the submit control usable to resend", async ({ page }) => { await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.getSubscription]: freeSubscription(), [ENDPOINTS.authSendMagicLink]: magicLinkSent(), }); @@ -85,7 +85,7 @@ test.describe("Magic-link sign-in", () => { test("shows an inline alias-policy error and keeps normal addresses working", async ({ page }) => { await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.getSubscription]: freeSubscription(), [ENDPOINTS.authSendMagicLink]: magicLinkAliasRejected("user+tag@gmail.com"), }); @@ -108,7 +108,7 @@ test.describe("Magic-link sign-in", () => { test("an HTTP-success response with an unexpected error code is surfaced as an error", async ({ page }) => { await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.getSubscription]: freeSubscription(), // HTTP 200, but the body carries an error code that is not the // specifically handled plus-alias rejection: the send did not happen. @@ -139,7 +139,7 @@ test.describe("Magic-link sign-in", () => { test("an HTTP-success response that declares success:false is surfaced as an error", async ({ page }) => { await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.getSubscription]: freeSubscription(), // HTTP 200 with an explicit failure and no code: this must never read as // "Sent!" or clear the address. @@ -166,7 +166,7 @@ test.describe("Magic-link sign-in", () => { test("recovers from a failed send, and retry succeeds", async ({ page }) => { let attempt = 0; await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.getSubscription]: freeSubscription(), }); await page.route(ENDPOINTS.authSendMagicLink, async (route) => { @@ -194,7 +194,7 @@ test.describe("Magic-link sign-in", () => { test("an expired or invalid token surfaces an inline retry in the sign-in modal", async ({ page }) => { await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.getSubscription]: freeSubscription(), [ENDPOINTS.authVerifyMagicLink]: magicLinkVerifyFailure(), }); @@ -211,7 +211,7 @@ test.describe("Magic-link sign-in", () => { test("a successful token verification refreshes the session and subscription", async ({ page }) => { await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.authVerifyMagicLink]: signedInSession(), [ENDPOINTS.getSubscription]: professionalSubscription(), }); @@ -228,7 +228,7 @@ test.describe("Magic-link sign-in", () => { test("signing in from the Plans surface returns to Plans after verification", async ({ page }) => { await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.getSubscription]: freeSubscription(), }); @@ -242,7 +242,7 @@ test.describe("Magic-link sign-in", () => { // The magic-link round trip is a fresh navigation with no memory of the // DOM — the return surface must survive via storage, not page state. await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.authVerifyMagicLink]: signedInSession(), [ENDPOINTS.getSubscription]: professionalSubscription(), }); diff --git a/e2e/stu390-logo-loop.spec.js b/e2e/stu390-logo-loop.spec.js index 8b5d699..254842a 100644 --- a/e2e/stu390-logo-loop.spec.js +++ b/e2e/stu390-logo-loop.spec.js @@ -3,7 +3,7 @@ import { applyDefaultRoutes, ENDPOINTS, freeSubscription, - guestIdentity, + oneArtifact, quotaExhausted, reviewPassed, @@ -65,7 +65,7 @@ async function openHome(page, overrides = {}) { localStorage.setItem("hasSeenWalkthrough", "true"); }); await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.getSubscription]: freeSubscription(), ...overrides, }); diff --git a/e2e/stu394-generation-trigger.spec.js b/e2e/stu394-generation-trigger.spec.js index 0bbbc3c..f737a08 100644 --- a/e2e/stu394-generation-trigger.spec.js +++ b/e2e/stu394-generation-trigger.spec.js @@ -1,7 +1,7 @@ import { test, expect } from "@playwright/test"; import { applyDefaultRoutes, - guestIdentity, + freeSubscription, ENDPOINTS, } from "./fixtures/apiFixtures.js"; @@ -48,7 +48,7 @@ test.describe("Generation trigger (STU-394)", () => { localStorage.setItem("hasSeenWalkthrough", "true"); }); await applyDefaultRoutes(page, { - [ENDPOINTS.identity]: guestIdentity(), + [ENDPOINTS.getSubscription]: freeSubscription(), }); await page.goto("/"); From 39ed0c4c889626c014e42f68b6d7e6ccaee5d08c Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 10 Nov 2026 23:00:00 +1100 Subject: [PATCH 12/15] fix: preserve account usage during identity renewal --- app.js | 13 ++++++++++--- src/generationSession.js | 6 +++++- src/generationSession.test.js | 7 +++++++ 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/app.js b/app.js index c844c91..66f0be8 100644 --- a/app.js +++ b/app.js @@ -211,14 +211,20 @@ function resetGenerationIdentity() { identityResolvePromise = null; identityState = { userId: null, token: null, status: null, resolved: false }; } -async function ensureAccountGenerationIdentity() { +async function ensureAccountGenerationIdentity({ reconcileUsage = true } = {}) { const epoch = identityEpoch; const token = authState.sessionToken; const result = await generationSessionClient.ensure(); if (epoch !== identityEpoch || token !== authState.sessionToken || !authState.isVerified) { throw new DOMException('Account session changed', 'AbortError'); } - identityState = { ...result, status: 'account', resolved: true }; + identityState = { userId: result.userId, token: result.token, status: 'account', resolved: true }; + if (reconcileUsage && result.usageCount !== undefined) { + const month = getCurrentYearMonth(); + const count = !result.usageMonth || result.usageMonth === month ? result.usageCount : 0; + localStorage.setItem(USAGE_STORAGE_KEY, JSON.stringify({ count, month })); + updateUsageDisplay(); + } } // --- TIER LIMITS --- @@ -7146,7 +7152,8 @@ async function callBuildShip(step, model, prompt, context = {}, images = []) { }, BUILDSHIP_TIMEOUT_MS) try { - if (authState.isVerified) await ensureAccountGenerationIdentity(); + // Stage token renewal must not overwrite the newer generator metering result. + if (authState.isVerified) await ensureAccountGenerationIdentity({ reconcileUsage: false }); if (!isCurrentPipelineRun(requestRunId) || requestIdentityEpoch !== identityEpoch || controller.signal.aborted) { throw new DOMException("Pipeline session changed", "AbortError"); } diff --git a/src/generationSession.js b/src/generationSession.js index 68975df..5af9fe0 100644 --- a/src/generationSession.js +++ b/src/generationSession.js @@ -37,7 +37,11 @@ export function createGenerationSessionClient({ endpoint, getSession, getLegacyT if (typeof data?.user_id !== 'string' || !data.user_id || typeof data.identity_token !== 'string' || !data.identity_token) { throw new Error('Invalid account generation session.'); } - return { userId: data.user_id, token: data.identity_token }; + return { + userId: data.user_id, token: data.identity_token, + ...(Number.isInteger(data.usage_count) && data.usage_count >= 0 ? { usageCount: data.usage_count } : {}), + ...(typeof data.usage_month === 'string' && /^\d{4}-\d{2}$/.test(data.usage_month) ? { usageMonth: data.usage_month } : {}), + }; } finally { clearTimeout(timer); if (pending === task) pending = null; diff --git a/src/generationSession.test.js b/src/generationSession.test.js index e91edab..9dae175 100644 --- a/src/generationSession.test.js +++ b/src/generationSession.test.js @@ -42,3 +42,10 @@ test('bridge errors and malformed credentials fail closed and allow retry', asyn await assert.rejects(client.ensure(), /Invalid/); assert.equal((await client.ensure()).userId, 'account-a'); }); +test('returns validated account usage without accepting malformed counters', async () => { + let data = { user_id: 'account-a', identity_token: 'signed', usage_count: 31, usage_month: '2026-11' }; + const client = createGenerationSessionClient({ endpoint: '/authUserCheck', getSession: () => session, getLegacyToken: async () => null, fetchImpl: async () => ({ ok: true, json: async () => data }) }); + assert.deepEqual(await client.ensure(), { userId: 'account-a', token: 'signed', usageCount: 31, usageMonth: '2026-11' }); + data = { ...data, usage_count: -1, usage_month: {} }; + assert.deepEqual(await client.ensure(), { userId: 'account-a', token: 'signed' }); +}); From 993f150f26be4f2b92392bfa8dc6afffb4023441 Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 10 Nov 2026 23:03:13 +1100 Subject: [PATCH 13/15] fix: discard stale pipeline responses before metering --- app.js | 4 +++ src/pipelineAccountIsolation.test.js | 45 ++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 src/pipelineAccountIsolation.test.js diff --git a/app.js b/app.js index 66f0be8..ff893e2 100644 --- a/app.js +++ b/app.js @@ -7179,6 +7179,10 @@ async function callBuildShip(step, model, prompt, context = {}, images = []) { // instead of a JSON body. Parse defensively so we surface the raw body in // the error rather than crashing on JSON.parse. const rawText = await res.text() + // Abort may lose a race with response delivery; stale accounts cannot meter usage. + if (!isCurrentPipelineRun(requestRunId) || requestIdentityEpoch !== identityEpoch || controller.signal.aborted) { + throw new DOMException("Pipeline session changed", "AbortError"); + } let data = {} try { data = rawText ? JSON.parse(rawText) : {} diff --git a/src/pipelineAccountIsolation.test.js b/src/pipelineAccountIsolation.test.js new file mode 100644 index 0000000..80c4abb --- /dev/null +++ b/src/pipelineAccountIsolation.test.js @@ -0,0 +1,45 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +const app = readFileSync(new URL('../app.js', import.meta.url), 'utf8'); +const start = app.indexOf('async function callBuildShip('); +const actualFunction = app.slice(start, app.indexOf('\n// Set when', start)); +function harness(status = 200) { + let release, started; + const bodyStarted = new Promise(resolve => { started = resolve; }); + const body = new Promise(resolve => { release = resolve; }); + const writes = []; + const env = { + pipelineState: { runId: 1, requestId: 'request-a' }, identityEpoch: 1, + authState: { isVerified: true }, identityState: { userId: 'a', token: 'scoped-a' }, + ensureAccountGenerationIdentity: async () => {}, + isCurrentPipelineRun: id => id === env.pipelineState.runId, + activeBuildShipControllers: new Set(), AbortController, DOMException, setTimeout, clearTimeout, + PIPELINE_ENDPOINT: 'https://example.test/pipeline', USAGE_STORAGE_KEY: 'usage', + fetch: async () => ({ status, ok: status === 200, text: async () => { started(); return body; } }), + localStorage: { setItem: (...args) => writes.push(args) }, + updateUsageDisplay: () => {}, getCurrentYearMonth: () => '2026-11', incrementUsage: () => writes.push('increment'), + createModelArmorError: () => null, console: { log() {} }, + }; + // Execute the production function with an abort-insensitive transport, not a duplicate implementation. + const call = new Function('env', `with (env) { return (${actualFunction}); }`)(env); + return { env, writes, release, bodyStarted, call }; +} +for (const status of [200, 429]) test(`late ${status} response cannot meter a different account`, async () => { + const h = harness(status); + const pending = h.call('generator', 'model', 'account A prompt'); + await h.bodyStarted; + h.env.identityEpoch++; h.env.pipelineState.runId++; + h.env.identityState = { userId: 'b', token: 'scoped-b' }; + h.env.activeBuildShipControllers.forEach(c => c.abort()); + h.release(JSON.stringify({ output: 'code', usage_status: 'success', usage_count: 31, usage_month: '2026-11', serverCount: 31 })); + await assert.rejects(pending, error => error.isPipelineCancel === true); + assert.deepEqual(h.writes, []); +}); +test('current account generator response still reconciles usage', async () => { + const h = harness(); const pending = h.call('generator', 'model', 'prompt'); + await h.bodyStarted; + h.release(JSON.stringify({ output: 'code', usage_status: 'success', usage_count: 31, usage_month: '2026-11' })); + assert.equal(await pending, 'code'); + assert.deepEqual(h.writes, [['usage', JSON.stringify({ count: 31, month: '2026-11' })]]); +}); From 776e218c5bcf21295b3a0b13d7dfc3a0fecdc8e5 Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 10 Nov 2026 23:42:58 +1100 Subject: [PATCH 14/15] fix: send generation credentials in JSON bodies --- app.js | 4 +++- docs/generation-history-account-auth.md | 4 +++- e2e/generation-history.spec.js | 2 +- e2e/generation-session.spec.js | 12 ++++++------ src/generationHistory.js | 2 +- src/generationHistory.test.js | 4 ++-- src/generationSession.js | 2 +- src/generationSession.test.js | 1 + src/pipelineAccountIsolation.test.js | 7 ++++++- 9 files changed, 24 insertions(+), 14 deletions(-) diff --git a/app.js b/app.js index ff893e2..6356271 100644 --- a/app.js +++ b/app.js @@ -6449,6 +6449,7 @@ async function resolveIdentity() { const response = await fetch(IDENTITY_ENDPOINT, { method: 'POST', + credentials: 'omit', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ fingerprint: result.visitorId, cookie_id: cookieId }), }) @@ -7159,13 +7160,14 @@ async function callBuildShip(step, model, prompt, context = {}, images = []) { } const res = await fetch(PIPELINE_ENDPOINT, { method: 'POST', + credentials: 'omit', headers: { 'Content-Type': 'application/json', - ...(identityState.token ? { Authorization: `Bearer ${identityState.token}` } : {}), }, signal: controller.signal, body: JSON.stringify({ user_id: identityState.userId, + sessionToken: identityState.token, request_id: pipelineState.requestId, step, model, diff --git a/docs/generation-history-account-auth.md b/docs/generation-history-account-auth.md index 156f2d4..268f571 100644 --- a/docs/generation-history-account-auth.md +++ b/docs/generation-history-account-auth.md @@ -4,8 +4,10 @@ The original history implementation confused an email app-session JWT with a pip The frontend now calls the existing POST `/authUserCheck` (staging `/staging/authUserCheck`) with JSON `{sessionToken, identityToken?}`. The session token is the verified sign-in session; the optional identity token is fresh legacy proof obtained from the anonymous resolver, never a submitted owner ID. No Authorization header is required by this resolver contract. The backend owns signature verification and immutable account-to-identity association. It reuses an established account marker; first linkage may adopt only a proven unclaimed/same-account legacy identity, and foreign proof produces a distinct account identity without exposing foreign history. -The resolver returns `{user_id, identity_token, ...}`. The frontend retains the account credentials only in memory and refreshes them before signed-in pipeline calls, including retries/refinements. The backend caps their expiry at the app session expiry. History list/detail/delete retain `Authorization: Bearer ` and are sent only after account bootstrap succeeds. History never authenticates using the device token. Staging resolver, history and pipeline routes all use `/staging/` and require the backend's isolated collection bindings. +The resolver returns `{user_id, identity_token, ...}`. The frontend retains the account credentials only in memory and refreshes them before signed-in pipeline calls, including retries/refinements. The backend caps their expiry at the app session expiry. History list/detail/delete send the email app session as JSON `sessionToken` and are sent only after account bootstrap succeeds. Pipeline requests send the scoped account (or signed-out anonymous) identity token as JSON `sessionToken`. Neither request sends Authorization; both use `credentials: omit`, as does account bootstrap. History never authenticates using the device token. Staging resolver, history and pipeline routes all use `/staging/` and require the backend's isolated collection bindings. Sign-in/session rotation and sign-out invalidate pending account resolutions. Account changes also cancel an active generation. Late anonymous or account responses cannot replace the current account's identity. Bridge failure blocks signed-in generation/history rather than falling back to anonymous access. Anonymous generation keeps its existing resolver path; the backend must refuse anonymous capabilities for an identity already claimed by an account. Evidence is synthetic and local: unit tests exercise real email-session-shaped request semantics, owner-field omission, delayed response rejection, logout, malformed responses and retry. Browser tests check email-vs-generation token separation, account A→B switching during a delayed bridge, and fail-closed behavior. Full-suite and independent-review results are recorded with the PR head. Backend source/emulator acceptance, deployment, CORS, real authenticated reads, two-account isolation and editor retest remain separate; no live writes or deployment are authorized by these tests. Preserve Stuart's manual backend workflow changes. + +Body-token transition (owner authorized): backend may accept legacy headers but must reject conflicting body/header credentials. JSON Content-Type still triggers a preflight; removing Authorization reduces the requested headers to content-type with credentials omitted. A local cross-origin browser probe observed OPTIONS requesting only content-type and a successful POST with no Authorization/cookies. Production/staging invalid-token list probes returned readable401; these are not valid-session acceptance. The preview browser also allowed the Authorization negative control, so this harness does not establish strict browser CORS enforcement; deployed ordinary-browser acceptance remains required. No valid bootstrap, generation or deletion was performed. diff --git a/e2e/generation-history.spec.js b/e2e/generation-history.spec.js index 43428f0..f842570 100644 --- a/e2e/generation-history.spec.js +++ b/e2e/generation-history.spec.js @@ -9,7 +9,7 @@ test('history bounded pagination, safe detail and selected deletion', async ({ p const calls=[]; let deleteFailed = false; await page.route('**/service/generation-history', route => { const body=route.request().postDataJSON(); calls.push(body); - expect(route.request().headers().authorization).toBe('Bearer synthetic'); + expect(route.request().headers().authorization).toBeUndefined();expect(route.request().postDataJSON().sessionToken).toBe('synthetic'); expect(body.user_id).toBeUndefined(); if (body.action === 'delete' && !deleteFailed) { deleteFailed = true; return route.fulfill({status:500,json:{error:{code:'INTERNAL_ERROR'}}}); } const data=body.action==='list' ? body.cursor ? {items:[{id:'entry',status:''}],nextCursor:null} : {items:[],nextCursor:'continue'} : body.action==='detail' ? {generation:{id:'entry',request_id:'entry',stages:{generator:{output_text:''}}}} : {deleted:true,id:'entry'}; diff --git a/e2e/generation-session.spec.js b/e2e/generation-session.spec.js index 1a1a48b..42c1268 100644 --- a/e2e/generation-session.spec.js +++ b/e2e/generation-session.spec.js @@ -15,8 +15,8 @@ test('email session bootstraps account identity; history keeps email token and p expect(r.request().postDataJSON()).toEqual({sessionToken:token,identityToken:'signed-legacy-proof'}); return r.fulfill({json:{user_id:'account-owner',identity_token:'signed-account-proof'}}); }); - await page.route('**/service/generation-history',r=>{historyCalls++;expect(r.request().headers().authorization).toBe(`Bearer ${token}`);return r.fulfill({json:{items:[],nextCursor:null}});}); - await page.route(ENDPOINTS.pipeline,r=>{pipelineCalls++;expect(r.request().headers().authorization).toBe('Bearer signed-account-proof');expect(r.request().postDataJSON().user_id).toBe('account-owner');return r.fulfill({status:503,json:{error:'Synthetic stop'}});}); + await page.route('**/service/generation-history',r=>{historyCalls++;expect(r.request().headers().authorization).toBeUndefined();expect(r.request().postDataJSON().sessionToken).toBe(token);return r.fulfill({json:{items:[],nextCursor:null}});}); + await page.route(ENDPOINTS.pipeline,r=>{pipelineCalls++;expect(r.request().headers().authorization).toBeUndefined();expect(r.request().postDataJSON().sessionToken).toBe('signed-account-proof');expect(r.request().postDataJSON().user_id).toBe('account-owner');return r.fulfill({status:503,json:{error:'Synthetic stop'}});}); await page.goto('/#account');await expect(page.locator('#topbar-avatar')).toContainText('A'); await page.locator('#history-refresh').click();await expect(page.locator('#history-status')).toContainText('No saved');expect(historyCalls).toBe(1); await page.evaluate(()=>window.switchView('home'));await page.locator('#pipeline-input').fill('Build a calendar');await page.locator('#hero-send').click(); @@ -29,8 +29,8 @@ test('delayed account A bridge cannot replace account B credentials',async({page if(r.request().postDataJSON().sessionToken===a) { await new Promise(resolve=>release=resolve);await r.fulfill({json:{user_id:'owner-a',identity_token:'scope-a'}}).catch(()=>{}); } else { expect(r.request().postDataJSON().sessionToken).toBe(b);await r.fulfill({json:{user_id:'owner-b',identity_token:'scope-b'}}); } }); - await page.route('**/service/generation-history',r=>{historyCalls++;expect(r.request().headers().authorization).toBe(`Bearer ${b}`);return r.fulfill({json:{items:[],nextCursor:null}});}); - await page.route(ENDPOINTS.pipeline,r=>{expect(r.request().headers().authorization).toBe('Bearer scope-b');expect(r.request().postDataJSON().user_id).toBe('owner-b');return r.fulfill({status:503,json:{error:'Synthetic stop'}});}); + await page.route('**/service/generation-history',r=>{historyCalls++;expect(r.request().headers().authorization).toBeUndefined();expect(r.request().postDataJSON().sessionToken).toBe(b);return r.fulfill({json:{items:[],nextCursor:null}});}); + await page.route(ENDPOINTS.pipeline,r=>{expect(r.request().headers().authorization).toBeUndefined();expect(r.request().postDataJSON().sessionToken).toBe('scope-b');expect(r.request().postDataJSON().user_id).toBe('owner-b');return r.fulfill({status:503,json:{error:'Synthetic stop'}});}); await page.goto('/#account');await expect.poll(()=>!!release).toBe(true); await page.evaluate(token=>window.__CCC_HISTORY_TEST__.session('b@example.com',token),b); release();await page.locator('#history-refresh').click();await expect(page.locator('#history-status')).toContainText('No saved');expect(historyCalls).toBe(1); @@ -57,7 +57,7 @@ test('switch during generator bootstrap cancels without fallback under the new a } else await r.fulfill({json:{user_id:body.sessionToken===a?'owner-a':'owner-b',identity_token:body.sessionToken===a?'scope-a':'scope-b'}}); }); await page.route(ENDPOINTS.pipeline,r=>{ - const body=r.request().postDataJSON();calls.push({step:body.step,token:r.request().headers().authorization}); + const body=r.request().postDataJSON();calls.push({step:body.step,token:body.sessionToken}); architectDone=true;return r.fulfill({json:{output:JSON.stringify({schemaVersion:'artifact-bundle/v1',artifacts:[{id:'widget',artifactType:'CodeFile',artifactName:'Widget',fileName:'widget.dart',code:'class Widget {}'}]})}}); }); await page.goto('/');await expect(page.locator('#topbar-avatar')).toContainText('A'); @@ -72,5 +72,5 @@ test('switch during generator bootstrap cancels without fallback under the new a await expect.poll(()=>page.evaluate(()=>window.__CCC_HISTORY_TEST__.state().isRunning)).toBe(false); // Await the actual abandoned run, not the flag cleared immediately by sign-out. await page.evaluate(()=>window.__accountSwitchRun); - expect(calls).toEqual([{step:'architect',token:'Bearer scope-a'}]); + expect(calls).toEqual([{step:'architect',token:'scope-a'}]); }); diff --git a/src/generationHistory.js b/src/generationHistory.js index e1aba47..7e83a72 100644 --- a/src/generationHistory.js +++ b/src/generationHistory.js @@ -30,7 +30,7 @@ export function createGenerationHistoryClient({ endpoint, getSession, fetchImpl }; try { check(); - const response = await fetchImpl(url.href, { method: 'POST', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify(body), signal: controller.signal }); + const response = await fetchImpl(url.href, { method: 'POST', credentials: 'omit', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...body, sessionToken: token }), signal: controller.signal }); const data = await response.json(); check(); if (!response.ok) { diff --git a/src/generationHistory.test.js b/src/generationHistory.test.js index af6a9e0..163340e 100644 --- a/src/generationHistory.test.js +++ b/src/generationHistory.test.js @@ -19,8 +19,8 @@ test('missing, unsupported, truncated, duplicate and mismatched data cannot repl }); test('bounded page allows empty continuation and sends no owner fields', async () => { let body; - const c = client({endpoint:'https://example.test/service/generation-history',getSession:()=>({token:'synthetic',key:'a'}),fetchImpl:async (_,opts)=>{body=JSON.parse(opts.body);return {ok:true,json:async()=>({items:[],nextCursor:'next'})};}}); - assert.equal((await c.list({user_id:'forged'})).nextCursor,'next'); assert.deepEqual(body,{action:'list'}); + const c = client({endpoint:'https://example.test/service/generation-history',getSession:()=>({token:'synthetic',key:'a'}),fetchImpl:async (_,opts)=>{assert.equal(opts.credentials,'omit'); assert.deepEqual(opts.headers,{'Content-Type':'application/json'}); body=JSON.parse(opts.body);return {ok:true,json:async()=>({items:[],nextCursor:'next'})};}}); + assert.equal((await c.list({user_id:'forged'})).nextCursor,'next'); assert.deepEqual(body,{action:'list',sessionToken:'synthetic'}); await assert.rejects(c.list({cursor:'next'}),/Invalid history page/); }); test('session changes and invalidation suppress late responses even if fetch ignores abort', async () => { diff --git a/src/generationSession.js b/src/generationSession.js index 5af9fe0..d9e217e 100644 --- a/src/generationSession.js +++ b/src/generationSession.js @@ -26,7 +26,7 @@ export function createGenerationSessionClient({ endpoint, getSession, getLegacyT const identityToken = await getLegacyToken(); if (!current()) throw stale(); const response = await fetchImpl(endpoint, { - method: 'POST', signal: controller.signal, + method: 'POST', credentials: 'omit', signal: controller.signal, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionToken: session.token, ...(identityToken ? { identityToken } : {}) }), }); diff --git a/src/generationSession.test.js b/src/generationSession.test.js index 9dae175..18c73db 100644 --- a/src/generationSession.test.js +++ b/src/generationSession.test.js @@ -7,6 +7,7 @@ test('bridge authenticates email session; legacy token is proof only, no caller const client = createGenerationSessionClient({ endpoint: '/authUserCheck', getSession: () => session, getLegacyToken: async () => 'legacy-signed', fetchImpl: async (url, init) => { assert.equal(url, '/authUserCheck'); assert.equal(init.headers.Authorization, undefined); + assert.equal(init.credentials, 'omit'); assert.deepEqual(JSON.parse(init.body), { sessionToken: 'email-session-jwt', identityToken: 'legacy-signed' }); return response(); } }); diff --git a/src/pipelineAccountIsolation.test.js b/src/pipelineAccountIsolation.test.js index 80c4abb..c96bd6f 100644 --- a/src/pipelineAccountIsolation.test.js +++ b/src/pipelineAccountIsolation.test.js @@ -16,7 +16,7 @@ function harness(status = 200) { isCurrentPipelineRun: id => id === env.pipelineState.runId, activeBuildShipControllers: new Set(), AbortController, DOMException, setTimeout, clearTimeout, PIPELINE_ENDPOINT: 'https://example.test/pipeline', USAGE_STORAGE_KEY: 'usage', - fetch: async () => ({ status, ok: status === 200, text: async () => { started(); return body; } }), + fetch: async (_, init) => { assert.equal(init.credentials, 'omit'); assert.deepEqual(init.headers, { 'Content-Type': 'application/json' }); assert.equal(JSON.parse(init.body).sessionToken, env.identityState.token); return ({ status, ok: status === 200, text: async () => { started(); return body; } }); }, localStorage: { setItem: (...args) => writes.push(args) }, updateUsageDisplay: () => {}, getCurrentYearMonth: () => '2026-11', incrementUsage: () => writes.push('increment'), createModelArmorError: () => null, console: { log() {} }, @@ -43,3 +43,8 @@ test('current account generator response still reconciles usage', async () => { assert.equal(await pending, 'code'); assert.deepEqual(h.writes, [['usage', JSON.stringify({ count: 31, month: '2026-11' })]]); }); + +test("anonymous pipeline retains its identity token in the body", async () => { + const h = harness(); h.env.authState.isVerified = false; h.env.identityState.token = "anonymous-proof"; + const pending = h.call("architect", "model", "prompt"); await h.bodyStarted; h.release(JSON.stringify({ output: "plan" })); assert.equal(await pending, "plan"); +}); From aea4a5d8572ab66093056d2246a68435d6337c9a Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 10 Nov 2026 23:43:18 +1100 Subject: [PATCH 15/15] fix: keep identity bootstrap transport unchanged --- app.js | 1 - docs/generation-history-account-auth.md | 2 +- src/generationSession.js | 2 +- src/generationSession.test.js | 1 - 4 files changed, 2 insertions(+), 4 deletions(-) diff --git a/app.js b/app.js index 6356271..30f5716 100644 --- a/app.js +++ b/app.js @@ -6449,7 +6449,6 @@ async function resolveIdentity() { const response = await fetch(IDENTITY_ENDPOINT, { method: 'POST', - credentials: 'omit', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ fingerprint: result.visitorId, cookie_id: cookieId }), }) diff --git a/docs/generation-history-account-auth.md b/docs/generation-history-account-auth.md index 268f571..0f63678 100644 --- a/docs/generation-history-account-auth.md +++ b/docs/generation-history-account-auth.md @@ -4,7 +4,7 @@ The original history implementation confused an email app-session JWT with a pip The frontend now calls the existing POST `/authUserCheck` (staging `/staging/authUserCheck`) with JSON `{sessionToken, identityToken?}`. The session token is the verified sign-in session; the optional identity token is fresh legacy proof obtained from the anonymous resolver, never a submitted owner ID. No Authorization header is required by this resolver contract. The backend owns signature verification and immutable account-to-identity association. It reuses an established account marker; first linkage may adopt only a proven unclaimed/same-account legacy identity, and foreign proof produces a distinct account identity without exposing foreign history. -The resolver returns `{user_id, identity_token, ...}`. The frontend retains the account credentials only in memory and refreshes them before signed-in pipeline calls, including retries/refinements. The backend caps their expiry at the app session expiry. History list/detail/delete send the email app session as JSON `sessionToken` and are sent only after account bootstrap succeeds. Pipeline requests send the scoped account (or signed-out anonymous) identity token as JSON `sessionToken`. Neither request sends Authorization; both use `credentials: omit`, as does account bootstrap. History never authenticates using the device token. Staging resolver, history and pipeline routes all use `/staging/` and require the backend's isolated collection bindings. +The resolver returns `{user_id, identity_token, ...}`. The frontend retains the account credentials only in memory and refreshes them before signed-in pipeline calls, including retries/refinements. The backend caps their expiry at the app session expiry. History list/detail/delete send the email app session as JSON `sessionToken` and are sent only after account bootstrap succeeds. Pipeline requests send the scoped account (or signed-out anonymous) identity token as JSON `sessionToken`. Neither request sends Authorization; both use `credentials: omit`. Account bootstrap is unchanged. History never authenticates using the device token. Staging resolver, history and pipeline routes all use `/staging/` and require the backend's isolated collection bindings. Sign-in/session rotation and sign-out invalidate pending account resolutions. Account changes also cancel an active generation. Late anonymous or account responses cannot replace the current account's identity. Bridge failure blocks signed-in generation/history rather than falling back to anonymous access. Anonymous generation keeps its existing resolver path; the backend must refuse anonymous capabilities for an identity already claimed by an account. diff --git a/src/generationSession.js b/src/generationSession.js index d9e217e..5af9fe0 100644 --- a/src/generationSession.js +++ b/src/generationSession.js @@ -26,7 +26,7 @@ export function createGenerationSessionClient({ endpoint, getSession, getLegacyT const identityToken = await getLegacyToken(); if (!current()) throw stale(); const response = await fetchImpl(endpoint, { - method: 'POST', credentials: 'omit', signal: controller.signal, + method: 'POST', signal: controller.signal, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionToken: session.token, ...(identityToken ? { identityToken } : {}) }), }); diff --git a/src/generationSession.test.js b/src/generationSession.test.js index 18c73db..9dae175 100644 --- a/src/generationSession.test.js +++ b/src/generationSession.test.js @@ -7,7 +7,6 @@ test('bridge authenticates email session; legacy token is proof only, no caller const client = createGenerationSessionClient({ endpoint: '/authUserCheck', getSession: () => session, getLegacyToken: async () => 'legacy-signed', fetchImpl: async (url, init) => { assert.equal(url, '/authUserCheck'); assert.equal(init.headers.Authorization, undefined); - assert.equal(init.credentials, 'omit'); assert.deepEqual(JSON.parse(init.body), { sessionToken: 'email-session-jwt', identityToken: 'legacy-signed' }); return response(); } });