Fix Jarvis code roundtrips, pin complete reset scope and lock issued forms

This commit is contained in:
unimatrixgit 2026-11-19 20:19:01 +01:00
commit a43e2d2f6a
7 changed files with 122 additions and 9 deletions

View file

@ -0,0 +1,15 @@
# J.A.R.V.I.S. key generator regression audit — 19 November 2026
Audited source: 5a7294bdfee7568f429e08be51633976dba8aa70.
Repair base: verified remote main 3dee0ee6b3df6ce45d029ab6a902162231b9bc04.
All three findings reproduced locally. Re-running the new focused tests with the three audited source files restored produced five expected failures: PRJ round-trip, issued form state, changed envoy, deed version and pending-request scope. The repaired versions pass.
- Versioned PRJ syntax now shares the existing canonical hashing route. All 19 registered types are tested in alpha, beta and live editions.
- Reset scope pins the full clan, member and deed rows and pending requests under the existing transaction locks. Old narrower manifests fail closed and require regeneration. Authority and key consumption remain in existing Jarvis services.
- Successful generation locks inputs and offers New instruction, which clears fields and assigns a new request ID. Identical backend retries remain idempotent; conflicting reused references remain rejected.
- A populated unrelated clan, owner, roster, deed, pending request and claim registry remain unchanged. Deliberately removing the roster/deed/owner SQL scope makes the preservation assertions fail.
- The actual mysql.mjs adapter is exercised with a mocked mysql2 pool, including startup, issuance, inspection and redemption. The root adapter has no first method. Its connection executes against the in-memory fixture: this checks the production adapter contract, not a live MySQL server or real lock scheduling.
- Headless Chrome at 1440px and 390px verifies locked fields, a new request ID and separate redemption without horizontal overflow. API responses are simulated.
No production key was issued or redeemed, no production clan was reset, and PR #337 was not changed by this audit.

View file

@ -1,6 +1,6 @@
// Shared syntax only: a readable edition is never proof of ownership or authority.
const legacy=/^(CLAN-ADM|PRJ|PRG|NEWS|XPC|XPX|ECO-SNAP|STAFF-LINK|STAFF-COM|STAFF-POL|XFR|CLAN-SUB|COM-SUB|POL-CLAN|QST|QSM|CLAN|COM|POL)-([A-F0-9]{48})$/;
const versioned=/^(CLAN-ADM|PRG|NEWS|XPC|XPX|ECO-SNAP|STAFF-LINK|STAFF-COM|STAFF-POL|XFR|CLAN-SUB|COM-SUB|POL-CLAN|QST|QSM|CLAN|COM|POL)-(ALPHA|BETA|LIVE)-((?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3})-(S\d{2,4})-([A-F0-9]{8}(?:-[A-F0-9]{8}){5})$/;
const versioned=/^(CLAN-ADM|PRJ|PRG|NEWS|XPC|XPX|ECO-SNAP|STAFF-LINK|STAFF-COM|STAFF-POL|XFR|CLAN-SUB|COM-SUB|POL-CLAN|QST|QSM|CLAN|COM|POL)-(ALPHA|BETA|LIVE)-((?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3})-(S\d{2,4})-([A-F0-9]{8}(?:-[A-F0-9]{8}){5})$/;
export function parseOrganisationCode(value){
if(typeof value!=='string'||value.length>128)throw new TypeError('Invalid organisation code');
const code=value.trim().toUpperCase(),old=code.match(legacy);

View file

@ -2,7 +2,7 @@ import {MASTER_KEY_TEMPLATES} from '../jarvis-master-keys.mjs';
export const KEY_GENERATOR_COMPONENTS=MASTER_KEY_TEMPLATES.map(t=>[t.label,t.actions.map(a=>a.label),[]]);
const el=(tag,text,cls)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;if(cls)n.className=cls;return n;};
export function createKeyGeneratorDesign({fetcher=fetch}={}){
const controller=new AbortController();let alive=true,busy=false,uncertain=false,templates=MASTER_KEY_TEMPLATES,inputs=new Map(),issuedCode='',issueId=crypto.randomUUID(),redeemId=crypto.randomUUID();
const controller=new AbortController();let alive=true,busy=false,uncertain=false,issued=false,templates=MASTER_KEY_TEMPLATES,inputs=new Map(),issuedCode='',issueId=crypto.randomUUID(),redeemId=crypto.randomUUID();
const root=el('section',undefined,'jarvis-generator'),status=el('p','Opening the masterkey register…','codex-preview-notice');status.setAttribute('role','status');
const tabs=el('nav',undefined,'jarvis-generator-tabs'),main=el('div'),history=el('section',undefined,'codex-management-box');history.hidden=true;
const generateTab=el('button','Generate key'),historyTab=el('button','History');for(const b of [generateTab,historyTab])b.type='button';tabs.append(generateTab,historyTab);
@ -12,14 +12,15 @@ export function createKeyGeneratorDesign({fetcher=fetch}={}){
const recipient=el('p'),fields=el('div'),effect=el('p',undefined,'codex-seal-note'),targets=el('div');
const consent=el('label',undefined,'jarvis-generator-consent'),confirmed=el('input');confirmed.type='checkbox';consent.append(confirmed,el('span','I reviewed the exact scope and effect.'));
const generate=el('button','Generate key');generate.type='submit';generate.disabled=true;
form.append(el('h3','Template & action'),top,recipient,targets,fields,effect,consent,generate);
const fresh=el('button','New instruction');fresh.type='button';fresh.hidden=true;
form.append(el('h3','Template & action'),top,recipient,targets,fields,effect,consent,generate,fresh);
const summary=el('dl',undefined,'jarvis-generator-summary'),output=el('code','Not issued'),copy=el('button','Copy key'),redeemForm=el('form'),redeemLabel=el('label',undefined,'codex-field'),codeInput=el('input'),redeem=el('button','Redeem key'),redeemConsent=el('label',undefined,'jarvis-generator-consent'),redeemCheck=el('input');
codeInput.type='text';codeInput.autocomplete='off';codeInput.maxLength=128;codeInput.required=true;redeemLabel.append(el('span','Key to redeem'),codeInput);redeemCheck.type='checkbox';redeemConsent.append(redeemCheck,el('span','Execute the instruction stored in this key.'));redeem.type='submit';copy.type='button';copy.disabled=true;redeem.disabled=true;redeemForm.append(redeemLabel,redeemConsent,redeem);
const decor=el('span',undefined,'jarvis-archive-box');decor.setAttribute('aria-hidden','true');preview.append(el('h3','Key preview'),summary,output,copy,el('p','Generation records an instruction. Only redemption executes it.'),el('h3','Redeem a key'),redeemForm,decor);layout.append(form,preview);main.append(layout);root.append(status,tabs,main,history);
const selected=()=>templates.find(t=>t.id===component.input.value)?.actions.find(a=>a.id===action.input.value);
function controls(){const a=selected();generate.disabled=busy||uncertain||!a?.available||!confirmed.checked;redeem.disabled=busy||uncertain||!redeemCheck.checked||!codeInput.value.trim();component.input.disabled=busy||uncertain;action.input.disabled=busy||uncertain;}
function controls(){const a=selected();generate.disabled=busy||uncertain||issued||!a?.available||!confirmed.checked;redeem.disabled=busy||uncertain||!redeemCheck.checked||!codeInput.value.trim();action.input.disabled=busy||uncertain||issued;component.input.disabled=busy||uncertain||issued;confirmed.disabled=busy||uncertain||issued;for(const {input} of inputs.values())input.disabled=busy||uncertain||issued;fresh.hidden=!issued;fresh.disabled=busy||uncertain;}
function updateSummary(){const a=selected();summary.replaceChildren();for(const [k,v]of [['Template',component.input.selectedOptions[0]?.textContent||''],['Action',a?.label||'No registered action'],['Version',a?.version||'—'],['Usage','Once'],['Status',issuedCode?'Issued':'Not issued']])summary.append(el('dt',k),el('dd',String(v)));controls();}
function renderFields(){const a=selected();inputs=new Map();fields.replaceChildren();targets.replaceChildren();confirmed.checked=false;issuedCode='';output.textContent='Not issued';copy.disabled=true;issueId=crypto.randomUUID();
function renderFields(){issued=false;const a=selected();inputs=new Map();fields.replaceChildren();targets.replaceChildren();confirmed.checked=false;issuedCode='';output.textContent='Not issued';copy.disabled=true;issueId=crypto.randomUUID();
for(const f of a?.fields||[]){const label=el('label',undefined,'codex-field'),input=el(f.type==='textarea'?'textarea':'input');if(input.tagName==='INPUT')input.type=f.type||'text';input.required=f.required===true;input.maxLength=f.maxLength||240;if(f.min!==undefined)input.min=f.min;input.setAttribute('aria-label',f.label);label.append(el('span',f.label),input);fields.append(label);inputs.set(f.name,{field:f,input});}
if(a?.fixedTargets){const table=el('table'),body=el('tbody');for(const name of a.fixedTargets){const row=el('tr');row.append(el('th',name),el('td','Current roster and owner · pinned on generation'));body.append(row);}table.append(body);targets.append(table);}
effect.textContent=a?.effect||(a?.recordOnly?'Sealed system record. It cannot be issued as a player reward.':'This action uses its existing domain service; standalone generator issuance is not connected yet.');updateSummary();}
@ -27,9 +28,10 @@ export function createKeyGeneratorDesign({fetcher=fetch}={}){
function renderTemplates(){const before=component.input.value;component.input.replaceChildren();for(const t of templates){const o=el('option',t.label);o.value=t.id;component.input.append(o);}if(templates.some(t=>t.id===before))component.input.value=before;renderActions();}
async function request(path,options){const response=await fetcher(path,{credentials:'same-origin',cache:'no-store',signal:controller.signal,...options});const data=await response.json();if(!response.ok)throw Error(data.message||'J.A.R.V.I.S. could not confirm the request.');return data;}
async function write(path,body){busy=true;controls();try{const result=await request(path,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});if(!alive)return null;return result;}catch(error){if(alive){uncertain=true;status.textContent=error.message+' Reload before another write; no automatic retry is sent.';}return null;}finally{busy=false;if(alive)controls();}}
form.onsubmit=async e=>{e.preventDefault();if(busy||uncertain||!form.reportValidity()||!confirmed.checked)return;const a=selected();if(!a?.available)return;const values=Object.fromEntries([...inputs].map(([name,{field,input}])=>[name,field.type==='number'?Number(input.value):input.value]));const result=await write('/api/jarvis/generator',{actionId:a.id,templateVersion:a.version,values,requestId:issueId,confirmed:true});if(!result)return;issuedCode=result.code||'';output.textContent=issuedCode||'This instruction is '+result.status+'.';codeInput.value=issuedCode;copy.disabled=!issuedCode;status.textContent=issuedCode?'Key generated. No clan has been changed.':'Existing instruction returned; no duplicate key was issued.';updateSummary();};
form.onsubmit=async e=>{e.preventDefault();if(busy||uncertain||issued||!form.reportValidity()||!confirmed.checked)return;const a=selected();if(!a?.available)return;const values=Object.fromEntries([...inputs].map(([name,{field,input}])=>[name,field.type==='number'?Number(input.value):input.value]));const result=await write('/api/jarvis/generator',{actionId:a.id,templateVersion:a.version,values,requestId:issueId,confirmed:true});if(!result)return;issued=true;issuedCode=result.code||'';output.textContent=issuedCode||'This instruction is '+result.status+'.';codeInput.value=issuedCode;copy.disabled=!issuedCode;status.textContent=issuedCode?'Key generated. This instruction is locked. Choose New instruction to generate another. No clan has been changed.':'Existing instruction returned; no duplicate key was issued.';updateSummary();};
redeemForm.onsubmit=async e=>{e.preventDefault();if(busy||uncertain||!redeemCheck.checked||!redeemForm.reportValidity())return;const result=await write('/api/jarvis/generator/redeem',{code:codeInput.value.trim(),requestId:redeemId,confirmed:true});if(!result)return;status.textContent=result.replayed?'This instruction was already completed.':'Instruction completed. Result recorded in J.A.R.V.I.S. history.';redeemCheck.checked=false;codeInput.value='';redeemId=crypto.randomUUID();controls();};
copy.onclick=()=>navigator.clipboard.writeText(issuedCode).then(()=>{if(alive)status.textContent='Key copied.';}).catch(()=>{if(alive)status.textContent='Select the key text to copy it.';});
fresh.onclick=()=>{renderFields();status.textContent='New instruction started with a new request reference.';};
component.input.onchange=renderActions;action.input.onchange=renderFields;confirmed.onchange=controls;redeemCheck.onchange=controls;codeInput.oninput=controls;
generateTab.onclick=()=>{main.hidden=false;history.hidden=true;};historyTab.onclick=async()=>{main.hidden=true;history.hidden=false;history.replaceChildren(el('h3','Your generated instructions'));try{const data=await request('/api/jarvis/generator/history');if(!alive)return;for(const row of data.records){const p=el('p',row.action_id+' · v'+row.template_version+' · '+row.state+' · '+new Date(Number(row.created_at)).toLocaleString('en-GB'));history.append(p);}if(!data.records.length)history.append(el('p','No generated instructions.'));}catch(error){if(alive)history.append(el('p',error.message));}};
renderTemplates();void request('/api/jarvis/generator').then(data=>{if(!alive)return;templates=data.templates;recipient.textContent='Recipient: '+data.recipient;status.textContent='Choose a mastertemplate and action. Server authority checks apply on issue and use.';renderTemplates();}).catch(error=>{if(alive)status.textContent=error.message;});

View file

@ -16,11 +16,13 @@ export async function initializeJarvisGenerator(db,{mysql=true}={}){
async function snapshot(tx){
const targets=[];
for(const id of PROTECTED_RESET_TARGETS){
const clan=await tx.first('SELECT id,name,owner_id,active,version FROM site_clans WHERE id=? FOR UPDATE',[id]);
const clan=await tx.first('SELECT * FROM site_clans WHERE id=? FOR UPDATE',[id]);
const institution=await tx.first('SELECT institution_key FROM site_clan_institutions WHERE clan_id=? FOR UPDATE',[id]);
if(!clan||Number(clan.active)!==1||!institution||!['bene','guild'].includes(institution.institution_key))throw Error('Protected clan identity changed');
const members=await tx.query('SELECT user_id,clan_role FROM site_clan_members WHERE clan_id=? ORDER BY user_id FOR UPDATE',[id]);
targets.push({...clan,institution:institution.institution_key,members});
const members=await tx.query('SELECT * FROM site_clan_members WHERE clan_id=? ORDER BY user_id FOR UPDATE',[id]);
const deed=await tx.first('SELECT * FROM site_clan_deeds WHERE clan_id=? FOR UPDATE',[id]);
const requests=await tx.query("SELECT * FROM site_clan_requests WHERE clan_id=? AND status='pending' ORDER BY user_id FOR UPDATE",[id]);
targets.push({...clan,institution:institution.institution_key,members,deed,requests});
}
return {targets,inventoryHash:hash(targets),preserve:['clans','claims','POL','Crysknife','companies','balances']};
}

View file

@ -0,0 +1,15 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {KEY_TYPES} from '../node/organisation-key-policy.mjs';
import {generateOrganisationKey,hashOrganisationKey} from '../node/organisation-keys.mjs';
import {formatOrganisationCode,parseOrganisationCode} from '../control-panel/public/codex-code-format.mjs';
for(const [type,{prefix}] of Object.entries(KEY_TYPES))test(type+' survives generation, editions, parsing and hashing',()=>{
const code=generateOrganisationKey(type),digest=hashOrganisationKey(code,type);
for(const stage of ['alpha','beta','live'])for(const season of ['S01','S9999']){
const formatted=formatOrganisationCode(code,{stage,version:'1.0.1.2',season});
assert.equal(parseOrganisationCode(formatted).canonical,code);
assert.equal(parseOrganisationCode(formatted).prefix,prefix);
assert.equal(hashOrganisationKey(formatted,type),digest);
assert.equal(hashOrganisationKey(formatted.toLowerCase(),type),digest);
}
});

View file

@ -0,0 +1,29 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {createKeyGeneratorDesign} from '../control-panel/public/cp-v2/cp-v2-key-generator.mjs';
import {MASTER_KEY_TEMPLATES} from '../control-panel/public/jarvis-master-keys.mjs';
class Element{
constructor(tag){this.tagName=tag.toUpperCase();this.children=[];this.textContent='';this.attributes={};}
append(...nodes){this.children.push(...nodes);}
replaceChildren(...nodes){this.children=nodes;this._value=undefined;}
setAttribute(k,v){this.attributes[k]=v;}
get value(){return this._value??(this.tagName==='SELECT'?this.children[0]?.value:'')??'';}
set value(v){this._value=v;}
get selectedOptions(){return this.children.filter(n=>n.value===this.value);}
reportValidity(){return true;}
remove(){}
}
const all=n=>[n,...n.children.flatMap(all)];
const settle=()=>new Promise(r=>setImmediate(r));
test('issued form locks; New instruction clears fields and uses a fresh reference',async()=>{
const before=globalThis.document;globalThis.document={createElement:t=>new Element(t)};const calls=[];
try{const root=createKeyGeneratorDesign({fetcher:async(path,options)=>{
if(options?.method==='POST'){calls.push(JSON.parse(options.body));return Response.json({code:'CLAN-ADM-'+'A'.repeat(48),status:'available'});}
return Response.json({recipient:'Owner',templates:MASTER_KEY_TEMPLATES.map(t=>({...t,actions:t.actions.map(a=>({...a,available:a.webIssue===true}))}))});
}});await settle();const find=(tag,text)=>all(root).find(n=>n.tagName===tag&&n.textContent===text),field=label=>all(root).find(n=>n.attributes['aria-label']===label),form=all(root).find(n=>n.tagName==='FORM');
const submit=async()=>{all(form).find(n=>n.type==='checkbox').checked=true;await form.onsubmit({preventDefault(){}});};
field('Ban / support ticket ID').value='402';await submit();assert.equal(calls.length,1);assert.equal(field('Ban / support ticket ID').disabled,true);assert.equal(all(form).find(n=>n.tagName==='BUTTON'&&n.textContent==='Generate key').disabled,true);assert.equal(find('BUTTON','New instruction').hidden,false);
field('Ban / support ticket ID').value='403';await submit();assert.equal(calls.length,1,'locked instruction cannot be changed or resubmitted');
find('BUTTON','New instruction').onclick();assert.equal(field('Ban / support ticket ID').value,'');assert.equal(field('Ban / support ticket ID').disabled,false);field('Ban / support ticket ID').value='403';await submit();assert.equal(calls.length,2);assert.notEqual(calls[0].requestId,calls[1].requestId);assert.equal(calls[1].values.ticketId,'403');root.dispose();
}finally{globalThis.document=before;}
});

View file

@ -12,3 +12,53 @@ test('mastertemplate generates one bound key without changing clans; redemption
}finally{f.db.close();}});
test('wrong account, revoked permission and changed roster cannot execute a generated key',async()=>{const f=await fixture();try{const key=await f.service.issue(f.people.Owner,f.input);await assert.rejects(f.service.redeem(f.people.Other,{code:key.code,requestId:randomUUID()}),/authority/);await f.db.query("INSERT INTO site_clan_members VALUES(?,?,'member')",[PROTECTED_RESET_TARGETS[0],f.people.Member.id]);await assert.rejects(f.service.redeem(f.people.Owner,{code:key.code,requestId:randomUUID()}),/inventory changed/);assert.equal((await f.keys.list(f.people.Owner.id)).find(k=>k.id===key.keyId).status,'available');f.revoke();await assert.rejects(f.service.redeem(f.people.Owner,{code:key.code,requestId:randomUUID()}),/authority/);}finally{f.db.close();}});
test('generator rejects target overrides and does not execute arbitrary template data',async()=>{const f=await fixture();try{await assert.rejects(f.service.issue(f.people.Owner,{...f.input,values:{reference:'No ticket'}}),/ticket ID is required/);await assert.rejects(f.service.issue(f.people.Owner,{...f.input,values:{...f.input.values,clanId:randomUUID()}}),/Unknown/);await assert.rejects(f.service.issue(f.people.Owner,{...f.input,actionId:'dev.issue'}),/Devkeys/);const api=createMasterKeyGeneratorAPI(f.central,f.keys,{authenticate:async()=>f.people.Owner,authorize:f.authorize});const post=(body,origin='https://cp.dunerealms.com')=>api(new Request('https://cp.dunerealms.com/api/jarvis/generator',{method:'POST',headers:{origin,'Content-Type':'application/json'},body:JSON.stringify(body)}));assert.equal((await post({...f.input,confirmed:true,sql:'DELETE FROM site_accounts'})).status,400);assert.equal((await post({...f.input,confirmed:true},'https://example.invalid')).status,403);const response=await post({...f.input,confirmed:true});assert.equal(response.status,200);assert.ok((await response.json()).code);}finally{f.db.close();}});
async function populated(f){
const id=randomUUID();
await f.db.query('INSERT INTO site_clans(id,name,owner_id,active,version,updated_at) VALUES(?,?,?,1,7,99)',[id,'Unrelated',f.people.Other.id]);
await f.db.query("INSERT INTO site_clan_members VALUES(?,?,'owner')",[id,f.people.Other.id]);
for(const clanId of [id,...PROTECTED_RESET_TARGETS]){
if(clanId===id)await f.db.query('INSERT INTO site_clan_deeds(clan_id,updated_at) VALUES(?,1)',[id]);
await f.db.query('UPDATE site_clan_deeds SET heir_account_id=?,consort_account_id=?,envoy_account_id=?,arms_account_id=?,heir_joined_at=11,consort_joined_at=12,envoy_joined_at=13,arms_joined_at=14,primary_color=?,version=9 WHERE clan_id=?',[f.people.Member.id,f.people.Ceo.id,f.people.Member.id,f.people.Ceo.id,'#123456',clanId]);
await f.db.query('INSERT INTO site_claim_registry VALUES(?,?,?,?,?)',['clan',clanId,JSON.stringify({chunks:[{x:2,z:3,world:'Arrakduin'}]}),4,99]);
await f.db.query("INSERT INTO site_clan_requests VALUES(?,?,'pending',1)",[clanId,f.people.Member.id]);
}
const preserved=async()=>({clan:await f.db.first('SELECT * FROM site_clans WHERE id=?',[id]),members:await f.db.query('SELECT * FROM site_clan_members WHERE clan_id=?',[id]),deed:await f.db.first('SELECT * FROM site_clan_deeds WHERE clan_id=?',[id]),requests:await f.db.query('SELECT * FROM site_clan_requests WHERE clan_id=?',[id]),claims:await f.db.query('SELECT * FROM site_claim_registry ORDER BY organisation_id'),owner:await f.db.first('SELECT * FROM site_accounts WHERE id=?',[f.people.Other.id])});
return {id,preserved,before:await preserved()};
}
test('populated unrelated clan, owner, roster, deed, requests and every claim survive reset',async()=>{
const f=await fixture();try{const p=await populated(f),key=await f.service.issue(f.people.Owner,f.input);await f.service.redeem(f.people.Owner,{code:key.code,requestId:randomUUID()});assert.deepEqual(await p.preserved(),p.before);for(const id of PROTECTED_RESET_TARGETS){const deed=await f.db.first('SELECT * FROM site_clan_deeds WHERE clan_id=?',[id]);for(const field of ['heir_account_id','consort_account_id','envoy_account_id','arms_account_id','heir_joined_at','consort_joined_at','envoy_joined_at','arms_joined_at'])assert.equal(deed[field],null);assert.equal(deed.version,10);assert.equal(deed.primary_color,'#123456');assert.equal((await f.db.first('SELECT status FROM site_clan_requests WHERE clan_id=?',[id])).status,'closed');}}finally{f.db.close();}
});
for(const change of [
["UPDATE site_clan_deeds SET envoy_account_id=?,version=version+1 WHERE clan_id=?",f=>[f.people.Ceo.id,PROTECTED_RESET_TARGETS[0]]],
["UPDATE site_clan_deeds SET version=version+1 WHERE clan_id=?",()=>[PROTECTED_RESET_TARGETS[0]]],
["UPDATE site_clan_requests SET updated_at=42 WHERE clan_id=?",()=>[PROTECTED_RESET_TARGETS[0]]]
])test('changed execution scope rejects before destructive writes: '+change[0],async()=>{
const f=await fixture();try{await populated(f);const key=await f.service.issue(f.people.Owner,f.input);await f.db.query(change[0],change[1](f));const before=JSON.stringify(await f.db.query('SELECT * FROM site_clan_deeds ORDER BY clan_id')),members=await f.db.query('SELECT * FROM site_clan_members ORDER BY clan_id');await assert.rejects(f.service.redeem(f.people.Owner,{code:key.code,requestId:randomUUID()}),/inventory changed/);assert.equal(JSON.stringify(await f.db.query('SELECT * FROM site_clan_deeds ORDER BY clan_id')),before);assert.deepEqual(await f.db.query('SELECT * FROM site_clan_members ORDER BY clan_id'),members);assert.equal((await f.keys.list(f.people.Owner.id)).find(k=>k.id===key.keyId).status,'available');}finally{f.db.close();}
});
test('same issue is safely repeatable; changed instruction cannot reuse its reference',async()=>{
const f=await fixture();try{const key=await f.service.issue(f.people.Owner,f.input);assert.equal((await f.service.issue(f.people.Owner,f.input)).keyId,key.keyId);await assert.rejects(f.service.issue(f.people.Owner,{...f.input,values:{...f.input.values,reference:'Different'}}),/reference conflict/);assert.notEqual((await f.service.issue(f.people.Owner,{...f.input,requestId:randomUUID(),values:{...f.input.values,reference:'Different'}})).keyId,key.keyId);}finally{f.db.close();}
});
import mysql from 'mysql2/promise';
import {openDatabase} from '../node/mysql.mjs';
import {readFile} from 'node:fs/promises';
async function mutatedService(f,from,to){
const url=new URL('../node/jarvis-master-generator.mjs',import.meta.url),source=await readFile(url,'utf8');assert.ok(source.includes(from));
const modified=source.replace(from,to).replace(/from '([^']+)'/g,(_,p)=>"from '"+new URL(p,url).href+"'");
const {createMasterKeyGenerator:factory}=await import('data:text/javascript;base64,'+Buffer.from(modified).toString('base64'));
return factory(f.central,f.keys,{authorize:f.authorize});
}
for(const [name,from,to] of [
['unscoped roster delete','DELETE FROM site_clan_members WHERE clan_id=?','DELETE FROM site_clan_members WHERE ? IS NOT NULL'],
['unscoped deed update',"WHERE clan_id=?',[clock(),clan.id]","WHERE ? IS NOT NULL',[clock(),clan.id]"],
['unscoped owner update',"WHERE id=?',[clock(),clan.id]","WHERE ? IS NOT NULL',[clock(),clan.id]"]
])test('preservation oracle catches mutation: '+name,async()=>{
const f=await fixture();try{const p=await populated(f),service=await mutatedService(f,from,to),key=await service.issue(f.people.Owner,f.input);await service.redeem(f.people.Owner,{code:key.code,requestId:randomUUID()});const after=await p.preserved();assert.throws(()=>assert.deepEqual(after,p.before),{name:'AssertionError'});}finally{f.db.close();}
});
test('real production adapter exposes no fixture-only root first method',async t=>{
const f=await fixture();let boot=true;const queries=[];
const connection={async query(){return [[],[]];},async execute(sql,args){queries.push(sql);if(boot)return [{affectedRows:0},[]];if(sql.includes('information_schema.COLUMNS'))return [[{IS_NULLABLE:'YES'}],[]];return [await f.db.query(sql,args),[]];},async beginTransaction(){f.db.sqlite.exec('BEGIN');},async commit(){f.db.sqlite.exec('COMMIT');},async rollback(){f.db.sqlite.exec('ROLLBACK');},release(){}};
t.mock.method(mysql,'createPool',()=>({async getConnection(){return connection;},async end(){}}));
try{const db=await openDatabase({});boot=false;assert.equal(db.first,undefined);await initializeJarvisGenerator(db);const keys=createOrganisationKeys(db,{secret:'ab'.repeat(32)}),service=createMasterKeyGenerator(db,keys,{authorize:f.authorize}),key=await service.issue(f.people.Owner,f.input);assert.equal((await keys.inspect(key.code,{accountId:f.people.Owner.id})).valid,true);await service.redeem(f.people.Owner,{code:key.code,requestId:randomUUID()});assert.ok(queries.some(q=>q.includes('information_schema.COLUMNS')));assert.equal((await f.db.first('SELECT COUNT(*) n FROM site_clan_members')).n,0);}finally{f.db.close();}
});