import test from 'node:test'; import assert from 'node:assert/strict'; import vm from 'node:vm'; import {readFileSync} from 'node:fs'; // Parent may target the assembled bot/webapp/static/index.html without copying fixtures. const html=readFileSync(process.env.IISHKO_UI_HTML||new URL('../bot/webapp/static/index.html',import.meta.url),'utf8'); const scripts=[...html.matchAll(/]*>([\s\S]*?)<\/script>/g)].map(match=>match[1]).filter(source=>source.trim()); const main=scripts.find(source=>source.includes('/* Contest UI: begin.')); assert.ok(main,'contest additions must live in the real application HTML'); const between=(source,start,end)=>{ const from=source.indexOf(start),to=source.indexOf(end,from+start.length); assert.ok(from>=0&&to>from,`missing source anchors: ${start} / ${end}`); return source.slice(from,to); }; const helpers=scripts.find(source=>source.includes('const MiniAppFlows=')); const values=between(main,'const esc=v=>','function haptic('); const contest=between(main,'/* Contest UI: begin.','/* Contest UI: end.'); const keySource=between(main,'/* Keys are managed only here;','/* ---------- [V3] экономика'); const usageSource=between(main,'const ECON_PERIODS=','function econUsageResults('); const profileSource=between(main,'function profile(','/* Keys are managed only here;'); const modelSource=between(main,'function modelCard(','function modelsFiltered('); let nextId=0; const plain=value=>JSON.parse(JSON.stringify(value)); function harness(store=new Map()){ const elements=new Map(),listeners=new Map(),posts=[],gets=[],copies=[],notices=[],confirms=[],focus=[]; let renders=0; const document={visibilityState:'visible',activeElement:null,addEventListener(name,fn){const list=listeners.get(name)||[];list.push(fn);listeners.set(name,list)},querySelector:selector=>get(selector),querySelectorAll:()=>[]}; class Element{ constructor(selector){this.selector=selector;this.id=selector.replace(/^#/,'');this.dataset={};this.attributes={};this.listeners=new Map();this.innerHTML='';this.textContent='';this.value='';this.disabled=false;this.open=false;this.isConnected=true;this.fields=[];this.readOnly=false;this.style={};} addEventListener(name,fn){const list=this.listeners.get(name)||[];list.push(fn);this.listeners.set(name,list);} removeEventListener(){} setAttribute(name,value){this.attributes[name]=String(value);} getAttribute(name){return this.attributes[name]??null;} showModal(){this.open=true;} close(){if(!this.open)return;this.open=false;for(const fn of this.listeners.get('close')||[])fn({target:this});} focus(){document.activeElement=this;focus.push(this.selector);} select(){this.selected=true;} querySelector(selector){return /input|select|textarea/.test(selector)&&/<(?:input|select|textarea)\b/.test(this.innerHTML)?get('#first-field'):null;} querySelectorAll(){return [];} closest(selector){return [...selector.matchAll(/\[data-([a-z-]+)\]/g)].some(match=>Object.hasOwn(this.dataset,match[1].replace(/-([a-z])/g,(_,letter)=>letter.toUpperCase())))?this:null;} reportValidity(){return this.valid!==false;} } function get(selector){if(!elements.has(selector))elements.set(selector,new Element(selector));return elements.get(selector);} document.activeElement=get('#trigger'); const c=vm.createContext({console,Map,Set,Number,JSON,String,Math,Date,URL,URLSearchParams,Uint8Array,encodeURIComponent, localStorage:{getItem:key=>store.get(key)||null,setItem:(key,value)=>store.set(key,String(value)),removeItem:key=>store.delete(key)}, crypto:{randomUUID:()=>`contest-vm-request-${String(++nextId).padStart(6,'0')}`}, FormData:class{constructor(form){return form.fields[Symbol.iterator]();}}, document,window:{addEventListener(){}},performance:{now:()=>100},setTimeout,clearTimeout,setInterval:()=>1,clearInterval(){}, $:get,resolvedUid:'123',current:'activities',tg:null,navigator:{clipboard:{writeText:async value=>{copies.push(value);}}},location:{hash:'#keys'}, intro:(title,text)=>`

${title}

${text}

`,empty:(title,text)=>`

${title}

${text}

`, haptic:()=>{},popup:(...args)=>notices.push(args),bust:()=>{},render:async()=>{renders++;}, icon:()=>'', askCaptcha:async()=>null,askAmount:async()=>5,askConfirm:async(...args)=>{confirms.push(args);return true;}, connectionHelpHtml:()=>'',weeklyBlock:()=>'',progress:()=>'',ranksBlock:()=>'',globalBlock:()=>'',refreshBtn:()=>'',cached:()=>null, modelStatus:()=> 'stale',mMeta:{status_ts:0},STATUS_UI:{stale:['Не проверена','dim']},AG_LABEL:{}, publicConnectionField:(label,value)=>``,modelAgentAction:()=>'',uptimeHtml:()=>'', post:async(path,body)=>{ posts.push({path,body:plain(body)}); if(path==='keys/transfer')return {ok:true,moved_usd:7}; if(body.action==='purchase')return {ok:true,action:body.action,offer_id:body.offer_id,charged_cents:250,expires_at:1800000000}; if(body.action==='create_invoice')return {ok:true,action:body.action,invoice:{id:'invoice-one',amount_cents:500,currency:'USD',status:'pending',pay_url:'https://example.org/pay/invoice-one'}}; if(body.action==='check_invoice')return {ok:true,action:body.action,invoice:{id:body.invoice_id,amount_cents:500,currency:'USD',status:'pending'},paid:false,credited_cents:0}; return {ok:true,action:body.action,id:body.id||7,status:body.decision||'pending',reward_rep:body.reward_rep||0}; }, apiResponse:null,apiFresh:async path=>{gets.push(path);return c.apiResponse;} }); vm.runInContext(helpers,c); vm.runInContext(values,c); vm.runInContext(contest,c); vm.runInContext(usageSource,c); vm.runInContext(keySource,c); vm.runInContext(profileSource,c); vm.runInContext(modelSource,c); const run=source=>vm.runInContext(source,c); const state=(name,data)=>{c.fixture=data;return run(`${name}View(fixture)`);}; const emit=async(name,target)=>{for(const fn of listeners.get(name)||[])await fn({target,preventDefault(){}});await Promise.resolve();await Promise.resolve();}; const button=dataset=>{const el=new Element('button');el.dataset=dataset;return el;}; return {c,run,state,get,store,posts,gets,copies,notices,confirms,focus,button,emit,renders:()=>renders}; } const commerce=overrides=>({uid:123,wallet_cents:1000,currency:'USD',payment_enabled:true,offers:[{id:'topup',kind:'wallet_topup',title:'Пополнить кошелёк',price_cents:500},{id:'requests',kind:'extra_requests',title:'Дополнительные запросы',price_cents:250,requests:50},{id:'model-day',kind:'model_pass',title:'Пропуск модели',price_cents:250,model:'sample-model',duration_seconds:86400}],entitlements:{extra_requests:0,models:[],expires_at:null},invoices:[],history:[],...overrides}); const board=overrides=>({uid:123,is_admin:false,reputation:4,activities:[],own_submissions:[],review_queue:[],rules:{summary:'Репутация после независимой модерации',rubric:[],submission_guide:{}},...overrides}); const item=overrides=>({id:8,kind:'activity',category:'docs',title:'Проверяемая инструкция',description:'Достаточно подробное описание полезного результата.',proof:'https://example.org/proof',status:'accepted',author_uid:456,reward_rep:5,created_at:1790000000,review_reason:'Проверено независимо',...overrides}); const validBug=()=>({fields:[['category','high'],['title','Воспроизводимая ошибка'],['description','Окружение и безопасные шаги, ожидаемый и фактический результат.'],['proof','request_example_12345']]}); test('all real inline scripts compile and contest routes remain discoverable',()=>{ for(const [index,source] of scripts.entries())new vm.Script(source,{filename:`index.contest.html:${index}`}); assert.match(main,/activities:\['Вклад и баги','activities'\]/); assert.match(html,/data-tab="activities"/); assert.match(html,/data-tab="econ"/); assert.match(html,/id="contestdlg" aria-labelledby="contest-title" aria-describedby="contest-desc"/); assert.match(html,/id="providerdlg" aria-labelledby="provider-title"/); }); test('aggregate API credit uses all key buckets, never wallet cents or coins',()=>{ const h=harness();h.c.data={balance_usd:10,total_balance_usd:17,main_balance_usd:10,extras_balance_usd:5,promo_balance_usd:2,wallet_cents:90000,balance:1234}; assert.deepEqual(plain(h.run('contestBalances(data)')),{main:10,extras:5,promo:2,total:17}); h.c.data={keys:[{main:true,remain_usd:10},{n:1,remain_usd:5},{promo:true,remain_usd:2}]}; assert.equal(h.run('contestBalances(data).total'),17); assert.equal(h.run('contestBalances({balance_usd:10}).total'),null,'main alone is not a confirmed total'); assert.equal(h.run('contestBalances({total_balance_usd:null}).total'),null); assert.match(h.run('contestBalanceHtml(data,true)'),/Основной[\s\S]*Дополнительные[\s\S]*Промо/); }); test('real profile renders aggregate total and escapes account metadata',()=>{ const h=harness();h.c.me={uid:123,username:'',rank_name:'',balance_usd:10,total_balance_usd:17,main_balance_usd:10,extras_balance_usd:5,promo_balance_usd:2}; const view=h.run('profile(me,{},null,null,null)'); assert.match(view,/17 долларов API-кредита по всем ключам/); assert.match(view,/<svg onload=x>/);assert.doesNotMatch(view,//); assert.match(view,/Денежный кошелёк и монеты сообщества сюда не входят/); }); test('real key cards expose return without deleting and keep promo reveal-only',async()=>{ const h=harness();h.c.current='keys';h.c.keys={uid:123,cap:4,keys:[{n:0,main:true,status:1,remain_usd:10},{n:1,status:1,remain_usd:7},{n:-1,promo:true,status:1,remain_usd:2}]}; const before=plain(h.c.keys),view=h.run('keysView(keys)'); assert.match(view,/data-k="back" data-n="1"[^>]*>Вернуть остаток на основной/); assert.doesNotMatch(view,/data-k="back" data-n="(?:0|-1)"/); await h.run('keyAct({dataset:{k:"back",n:"1"}})'); assert.equal(h.posts.length,1);assert.equal(h.posts[0].path,'keys/transfer'); assert.equal(h.posts[0].body.usd,0);assert.equal(h.posts[0].body.dir,'from');assert.ok(h.posts[0].body.request_id); assert.deepEqual(plain(h.c.keys),before,'client never removes the extra key'); assert.match(h.confirms[0][1],/ключ не удаляется/);assert.match(h.notices[0][1],/не удалён/); }); test('lost non-destructive return replays the identical saved operation',async()=>{ const h=harness();h.c.current='keys';h.run('keysView({uid:123,cap:3,keys:[{n:1,remain_usd:7,status:1}]})'); h.c.post=async()=>{throw new Error('lost reply');}; await h.run('keyAct({dataset:{k:"back",n:"1"}})'); const saved=JSON.parse(h.store.get('keys-pending:123')); h.c.post=async(path,body)=>{h.posts.push({path,body:plain(body)});return {ok:true,moved_usd:7};}; await h.run('keyAct({dataset:{k:"retry"}})'); assert.deepEqual(h.posts[0].body,saved.body);assert.equal(h.posts[0].path,'keys/transfer');assert.equal(h.store.size,0); }); test('public feed rejects accidental private bugs, unaccepted work and foreign own reports',()=>{ const h=harness();const view=h.state('activities',board({activities:[item(),item({id:9,kind:'bug',title:'PRIVATE PUBLIC LEAK'}),item({id:10,status:'pending',title:'PENDING PUBLIC LEAK'})],own_submissions:[item({id:11,kind:'bug',author_uid:999,title:'FOREIGN OWN LEAK'})],review_queue:[item({kind:'bug',title:'ADMIN QUEUE LEAK',status:'pending'})]})); assert.match(view,/Проверяемая инструкция/); for(const secret of ['PRIVATE PUBLIC LEAK','PENDING PUBLIC LEAK','FOREIGN OWN LEAK','ADMIN QUEUE LEAK'])assert.ok(!view.includes(secret)); assert.doesNotMatch(view,/data-board-review/);assert.equal(h.run('boardReviewOpen(8)'),false); }); test('own private report is escaped and cannot create javascript/data links',()=>{ const h=harness(),payload=' & " \' '; const view=h.state('activities',board({own_submissions:[item({kind:'bug',author_uid:123,title:payload,description:payload,proof:'javascript:alert(1)',review_reason:payload})],rules:{summary:payload,rubric:[{kind:'activity',label:payload,example:payload,suggested_rep:[1,5]}]}})); assert.match(view,/Приватный баг-репорт · только автор и администрация/); assert.match(view,/<img/);assert.match(view,/&/);assert.match(view,/"/);assert.match(view,/'/); assert.doesNotMatch(view,//); for(const url of ['javascript:alert(1)','data:text/html,bad','https://name:password@example.org/']){h.c.url=url;assert.equal(h.run('contestSafeUrl(url)'),'');} }); test('private bug form submits real raw fields with a persisted stable id',async()=>{ const h=harness();h.state('activities',board()); await h.emit('click',h.button({boardKind:'bug'})); assert.equal(h.get('#contestdlg').open,true);assert.match(h.get('#contest-desc').textContent,/В публичную ленту баг не попадёт/); assert.match(h.get('#contest-fields').innerHTML,/name="description" required minlength="30" maxlength="6000"/); const form=validBug();h.c.form=form;const body=h.run('contestFormBody(contestState.operation,form)'); h.c.post=async(path,payload)=>{assert.equal(JSON.parse(h.store.get('contest-pending:activities:123')).body.request_id,payload.request_id);h.posts.push({path,body:plain(payload)});return {ok:true,action:'submit',id:7,status:'pending',reward_rep:0};}; h.c.body=body;await h.run('contestPerform("activities",body)'); assert.equal(h.posts[0].path,'activities/action');assert.equal(h.posts[0].body.kind,'bug');assert.equal(h.posts[0].body.category,'high'); assert.equal(h.store.size,0);assert.equal(h.get('#contestdlg').open,false);assert.match(h.run('contestState.notices.activities'),/ждёт модерации/); }); test('invalid report is blocked before POST and labels focus the editable fields',()=>{ const h=harness();h.state('activities',board());h.run('boardOpen("bug")');h.c.form={fields:[['category','high'],['title','bad'],['description','short'],['proof','tiny']]}; assert.throws(()=>h.run('contestFormBody(contestState.operation,form)'),/Проверь категорию/);assert.equal(h.posts.length,0); assert.equal(h.focus.at(-1),'#first-field');h.run('contestCloseDialog()');assert.equal(h.focus.at(-1),'#trigger'); }); test('administrator may review another pending report but cannot self-award',async()=>{ const h=harness();const view=h.state('activities',board({is_admin:true,review_queue:[item({id:8,kind:'bug',status:'pending'}),item({id:9,author_uid:123,status:'pending'})]})); assert.match(view,/data-board-review="8"/);assert.doesNotMatch(view,/data-board-review="9"/); assert.equal(h.run('boardReviewOpen(9)'),false);assert.equal(h.run('boardReviewOpen(8)'),true); h.c.form={fields:[['decision','duplicate'],['reward_rep','40'],['reason','Повтор уже подтверждённого дефекта']]}; const body=h.run('contestFormBody(contestState.operation,form)');assert.equal(body.reward_rep,0); h.c.body=body;await h.run('contestPerform("activities",body)');assert.equal(h.posts[0].body.decision,'duplicate');assert.equal(h.posts[0].body.reward_rep,0); assert.match(h.run('contestState.notices.activities'),/Дубликат/); }); test('provider unknown/null capability is honest and metadata is escaped',()=>{ const h=harness();h.c.data={model:'sample-model',providers:[{id:'opaque-route',name:'',available:null,effort:null,effort_levels:['high'],verification:{status:'unverified',method:'',checked_at:null}}]}; const view=h.run('providersHtml(data)'); assert.match(view,/Доступность неизвестна/);assert.match(view,/Происхождение не подтверждено/);assert.match(view,/Поддержка effort неизвестна/); assert.match(view,/<img/);assert.match(view,/<script>/);assert.doesNotMatch(view,/{ const h=harness();h.c.apiResponse={model:'vendor/sample-model',providers:[]}; assert.equal(await h.run('providerOpen("vendor/sample-model")'),true); assert.equal(h.gets[0],'providers?model=vendor%2Fsample-model');assert.equal(h.get('#providerdlg').open,true); assert.equal(h.get('#provider-content').attributes['aria-busy'],'false');assert.match(h.get('#provider-content').innerHTML,/нет опубликованных/); assert.equal(h.focus.at(-1),'#provider-close'); h.get('#providerdlg').close();assert.equal(h.focus.at(-1),'#trigger'); }); test('provider mismatch and transport failure never create a positive verified state',async()=>{ const h=harness();h.c.apiResponse={model:'different-model',providers:[]}; assert.equal(await h.run('providerOpen("sample-model")'),false);assert.match(h.get('#provider-content').innerHTML,/Метаданные провайдеров не подтверждены/); h.c.apiFresh=async()=>{throw new Error('');}; assert.equal(await h.run('providerOpen("sample-model")'),false);assert.match(h.get('#provider-content').innerHTML,/<svg/);assert.doesNotMatch(h.get('#provider-content').innerHTML,/{ const h=harness();h.c.apiResponse={model:'sample-model',providers:[{id:'route-one',name:'Route',available:true,effort:true,effort_levels:['low','high'],verification:{status:'verified',method:'operator_probe',checked_at:1790000000}}]}; await h.run('providerOpen("sample-model")'); // Contract is read from the real gateway sources, not from a string oracle: // relay rejects an effort header the body does not carry, registry reads effort from body fields. const relay=readFileSync(new URL('../gateway/gateway_provider_relay.py',import.meta.url),'utf8'); const registry=readFileSync(new URL('../gateway/gateway_providers.py',import.meta.url),'utf8'); const parser=readFileSync(new URL('../gateway/request_effort.py',import.meta.url),'utf8'); const effortFn=registry.slice(registry.indexOf('def response_effort'),registry.indexOf('def safe_to_retry')); assert.match(relay,/headers do not rewrite generation parameters/); assert.match(relay,/X-Iishko-Effort[\s\S]*effort_requires_request_field/); assert.match(registry,/from request_effort import InvalidEffort, read_effort/); assert.match(effortFn,/return read_effort\(payload\)/); assert.match(parser,/"reasoning_effort"/); const view=h.get('#provider-content').innerHTML; assert.doesNotMatch(view,/X-Iishko-Effort/,'the copied example must never suggest an effort header'); assert.match(view,/data-provider-copy-body="0"/);assert.match(view,/Фрагмент тела запроса/); assert.equal(h.run('providerSelectEffort(0,"high")'),true); assert.equal(h.get('#provider-example-0').value,'X-Iishko-Provider: route-one','selecting effort must not add a header'); const fragment=JSON.parse(h.get('#provider-body-0').value); assert.deepEqual(Object.keys(fragment),['reasoning_effort']);assert.equal(fragment.reasoning_effort,'high'); assert.ok(Object.keys(fragment).every(key=>parser.includes('"'+key+'"')),'fragment key must be one the shared gateway parser reads from the request body'); assert.equal(h.run('providerSelectEffort(0,"high\\r\\nInjected: value")'),false); assert.equal(h.get('#provider-body-0').value,'{"reasoning_effort": "high"}','rejected value must not reach the fragment'); assert.equal(h.run('providerSelectEffort(0,"medium")'),false,'unconfigured level is not selectable'); let copyButton=h.c.copyButton=h.button({providerCopy:'0'});await h.emit('click',copyButton); assert.deepEqual(h.copies,['X-Iishko-Provider: route-one']); copyButton=h.c.copyButton=h.button({providerCopyBody:'0'});await h.emit('click',copyButton); assert.deepEqual(h.copies,['X-Iishko-Provider: route-one','{"reasoning_effort": "high"}']); assert.equal(await h.run('providerSelectEffort(0,"")'),true); assert.equal(h.get('#provider-body-0').value,''); assert.equal(await h.run('providerCopy(0,copyButton,"body")'),false,'an empty fragment is not copyable'); assert.deepEqual(h.copies,['X-Iishko-Provider: route-one','{"reasoning_effort": "high"}']); assert.match(h.run('providersHtml(apiResponse)'),/operator_probe/); }); test('real model card exposes provider action rather than an API-only feature',()=>{ const h=harness();h.c.model={name:'sample-model',available:true,checked_at:0,rank_name:'Участник'}; const view=h.run('modelCard(model)');assert.match(view,/data-provider-model="sample-model"/);assert.match(view,/aria-haspopup="dialog"/);assert.match(view,/Провайдеры · effort · проверка/); }); test('payment disabled keeps topup visible but inert and never invents offers/prices',async()=>{ const h=harness();const view=h.state('commerce',commerce({payment_enabled:false,wallet_cents:0})); assert.match(view,/оплата отключена или ещё не настроена/); assert.match(view,/data-commerce="create_invoice"[^>]*disabled/);assert.equal(h.run('commerceOpen("create_invoice","topup")'),false); await h.emit('click',h.button({commerce:'create_invoice',offerId:'topup'}));assert.equal(h.posts.length,0);assert.equal(h.get('#contestdlg').open,false); const empty=h.state('commerce',commerce({payment_enabled:false,offers:[]}));assert.match(empty,/Предложения пока не настроены/);assert.doesNotMatch(empty,/data-commerce=/); }); test('configured limit/model passes are purchasable from a separate USD-cent wallet',async()=>{ const h=harness(),view=h.state('commerce',commerce());h.c.current='econ'; assert.match(view,/50 дополнительных запросов/);assert.match(view,/Пропуск на 24 часа: sample-model/);assert.match(view,/\$2\.50 USD/); assert.match(view,/Эти балансы не складываются/);await h.emit('click',h.button({commerce:'purchase',offerId:'requests'})); assert.equal(h.get('#contestdlg').open,true);assert.match(h.get('#contest-desc').textContent,/денежного кошелька/); await h.run('contestPerform("commerce",contestFormBody(contestState.operation,{}))'); assert.equal(h.posts[0].path,'commerce/action');assert.equal(h.posts[0].body.offer_id,'requests');assert.match(h.run('contestState.notices.commerce'),/Покупка подтверждена/); }); test('payment metadata/links are escaped and an unsafe pay URL is never clickable',()=>{ const h=harness(),view=h.state('commerce',commerce({offers:[{id:'safe-id',kind:'model_pass',title:'',price_cents:250,model:''}],invoices:[{id:'invoice-one',status:'pending',amount_cents:500,pay_url:'javascript:alert(1)'}],history:[{delta_cents:-250,kind:'',offer_id:'',ts:1790000000}]})); assert.match(view,/<img/);assert.match(view,/<svg/);assert.match(view,/<script>/);assert.doesNotMatch(view,/{ const h=harness(),receipts=new Map();let charges=0; const backend=async(path,body)=>{const fingerprint=JSON.stringify(body);if(receipts.has(body.request_id)){assert.equal(receipts.get(body.request_id).fingerprint,fingerprint);return {...receipts.get(body.request_id).receipt,replayed:true};}charges++;const receipt={ok:true,action:'purchase',offer_id:body.offer_id,charged_cents:250};receipts.set(body.request_id,{fingerprint,receipt});throw new Error('response lost after charge');}; h.c.post=backend;await assert.rejects(h.run('contestMutation("commerce",{action:"purchase",offer_id:"requests"})'),/response lost/); const saved=JSON.parse(h.store.get('contest-pending:commerce:123')); await assert.rejects(h.run('contestMutation("commerce",{action:"purchase",offer_id:"model-day"})'),/Сначала проверь/); const reopened=harness(h.store);reopened.c.post=backend;reopened.c.current='econ'; await reopened.run('contestPerform("commerce",{},true)');assert.equal(charges,1);assert.equal(reopened.store.size,0); assert.match(reopened.run('contestState.notices.commerce'),/сохранённая квитанция/);assert.equal(receipts.has(saved.body.request_id),true); }); test('lost private submission/review retains raw body and cannot silently become a new mutation',async()=>{ for(const action of [{action:'submit',kind:'bug',category:'high',title:'Private report',description:'Detailed safe reproduction of the defect.',proof:'safe-request-id'},{action:'review',id:8,decision:'accepted',reward_rep:5,reason:'Independently reproduced'}]){ const h=harness();h.c.post=async()=>{throw new Error('network uncertainty');};h.c.body=action; await assert.rejects(h.run('contestMutation("activities",body)')); const saved=JSON.parse(h.store.get('contest-pending:activities:123'));assert.deepEqual({...saved.body,request_id:undefined},{...action,request_id:undefined}); const reopened=harness(h.store);await reopened.run('contestMutation("activities",{},true)');assert.deepEqual(reopened.posts[0].body,saved.body);assert.equal(reopened.store.size,0); } }); test('401, server errors, conflicts and malformed 2xx preserve the uncertain id',async()=>{ for(const failure of [Object.assign(new Error('auth'),{status:401,data:{operation_rejected:true}}),Object.assign(new Error('server'),{status:503}),Object.assign(new Error('conflict'),{status:409,data:{error:'request_conflict',operation_rejected:true}}),null]){ const h=harness();h.c.post=async()=>{if(failure)throw failure;return {ok:true};}; await assert.rejects(h.run('contestMutation("commerce",{action:"purchase",offer_id:"requests"})')); assert.equal(h.store.size,1);assert.equal(h.run('contestState.busy.size'),0); } }); test('definitive rejection permits correction but storage denial blocks sending',async()=>{ const h=harness();h.c.post=async()=>{throw Object.assign(new Error('bad input'),{status:400,data:{operation_rejected:true,error:'invalid_title'}});}; await assert.rejects(h.run('contestMutation("activities",{action:"submit",kind:"bug"})'));assert.equal(h.store.size,0); const blocked=harness();blocked.c.localStorage.setItem=()=>{throw new Error('denied');}; await assert.rejects(blocked.run('contestMutation("commerce",{action:"purchase",offer_id:"requests"})'),/Хранилище/);assert.equal(blocked.posts.length,0); }); test('pending state and late results remain scoped to signed identity',async()=>{ const h=harness();h.state('commerce',commerce());h.state('activities',board()); h.c.post=async()=>{h.c.resolvedUid='456';return {ok:true,action:'purchase',offer_id:'requests',charged_cents:250};}; await assert.rejects(h.run('contestMutation("commerce",{action:"purchase",offer_id:"requests"})'),/Аккаунт изменился/); assert.equal(h.run('contestPending("commerce")'),null);assert.ok(h.store.has('contest-pending:commerce:123')); assert.equal(h.run('commerceOpen("purchase","requests")'),false);assert.equal(h.run('boardOpen("bug")'),false); const view=h.state('activities',board());assert.doesNotMatch(view,/data-board-kind=/); }); test('in-flight guard prevents double clicks and corrupt pending state fails closed',async()=>{ const h=harness();let release;h.c.post=async()=>new Promise(resolve=>{release=resolve;}); const first=h.run('contestMutation("commerce",{action:"purchase",offer_id:"requests"})'); await assert.rejects(h.run('contestMutation("commerce",{action:"purchase",offer_id:"requests"})'),/Дождись/); release({ok:true,action:'purchase',offer_id:'requests',charged_cents:250});await first; h.store.set('contest-pending:commerce:123','not-json');assert.match(h.state('commerce',commerce()),/Новые действия заблокированы/); assert.equal(h.run('commerceOpen("purchase","requests")'),false); }); test('real bound submit handler validates and sends private reports without a public action',async()=>{ const h=harness();h.state('activities',board());h.run('boardOpen("bug")'); const form=h.get('#contest-form');form.fields=validBug().fields; await form.listeners.get('submit')[0]({target:form,preventDefault(){}}); assert.equal(h.posts.length,1);assert.equal(h.posts[0].path,'activities/action');assert.equal(h.posts[0].body.kind,'bug'); assert.equal(h.get('#contestdlg').open,false);assert.equal(h.store.size,0); }); test('real bound invoice confirmation creates a payable invoice, never a wallet credit',async()=>{ const h=harness();h.c.current='econ';h.state('commerce',commerce()); assert.equal(h.run('commerceOpen("create_invoice","topup")'),true); const form=h.get('#contest-form'); await form.listeners.get('submit')[0]({target:form,preventDefault(){}}); assert.equal(h.posts[0].path,'commerce/action');assert.equal(h.posts[0].body.action,'create_invoice');assert.equal(h.posts[0].body.offer_id,'topup'); assert.match(h.run('contestState.notices.commerce'),/Деньги ещё не зачислены/);assert.equal(h.store.size,0); }); test('creating/uncertain invoice or inconsistent paid receipt is not a false success',async()=>{ for(const result of [ {ok:true,action:'create_invoice',invoice:{id:'invoice-one',currency:'USD',amount_cents:500,status:'uncertain',pay_url:'https://example.org/pay'}}, {ok:true,action:'check_invoice',paid:true,credited_cents:500,invoice:{id:'invoice-one',currency:'USD',amount_cents:500,status:'pending'}} ]){ const h=harness();h.c.post=async()=>result;h.c.body=result.action==='create_invoice'?{action:result.action,offer_id:'topup'}:{action:result.action,invoice_id:'invoice-one'}; await assert.rejects(h.run('contestMutation("commerce",body)'),/квитанцию/);assert.equal(h.store.size,1); } });