forked from unimatrix/web
Use the production central database reader contract for masterkey instructions
This commit is contained in:
parent
5b31768d38
commit
5a7294bdfe
2 changed files with 8 additions and 7 deletions
|
|
@ -7,9 +7,10 @@ export const PROTECTED_RESET_TARGETS=Object.freeze(['113e9471-6288-43d6-ad8e-252
|
|||
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
|
||||
const hash=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex');
|
||||
const equal=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
|
||||
const first=(db,sql,args=[])=>db.prepare(sql).bind(...args).first();
|
||||
export async function initializeJarvisGenerator(db,{mysql=true}={}){
|
||||
await db.query(GENERATOR_SCHEMA);
|
||||
if(mysql){const column=await db.first("SELECT IS_NULLABLE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='site_clans' AND COLUMN_NAME='owner_id'");if(column?.IS_NULLABLE==='NO')await db.query('ALTER TABLE site_clans MODIFY owner_id CHAR(36) NULL');}
|
||||
if(mysql){const column=await first(db,"SELECT IS_NULLABLE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='site_clans' AND COLUMN_NAME='owner_id'");if(column?.IS_NULLABLE==='NO')await db.query('ALTER TABLE site_clans MODIFY owner_id CHAR(36) NULL');}
|
||||
db.jarvisGeneratorEnabled=true;
|
||||
}
|
||||
async function snapshot(tx){
|
||||
|
|
@ -31,18 +32,18 @@ export function createMasterKeyGenerator(db,keys,{authorize,clock=Date.now}){
|
|||
async issue(actor,{actionId,templateVersion,values,requestId}){
|
||||
const action=masterAction(actionId);assertWebIssuableMaster(action);if(!action||action.version!==templateVersion||!action.webIssue||!uuid(requestId))throw Error('Choose a connected masterkey action');
|
||||
await permitted(actor,action.permission);const fields=validateMasterFields(action,values),encoded=JSON.stringify(fields);
|
||||
const prior=await db.first('SELECT * FROM jarvis_generated_instructions WHERE request_id=?',[requestId]);
|
||||
const prior=await first(db,'SELECT * FROM jarvis_generated_instructions WHERE request_id=?',[requestId]);
|
||||
if(prior){if(prior.account_id!==actor.id||prior.action_id!==actionId||prior.fields_json!==encoded)throw Error('Instruction reference conflict');return availableCode({id:prior.key_id,created:false},actor.id);}
|
||||
const result=await keys.issue({accountId:actor.id,keyType:'clan-administration',scopeId:'protected-roster:'+requestId,expiresAt:clock()+86400000,authorize:async(tx,{keyId})=>{
|
||||
await permitted(actor,action.permission);const manifest=await snapshot(tx);
|
||||
await tx.query('INSERT INTO jarvis_generated_instructions(key_id,request_id,account_id,action_id,template_version,fields_json,manifest_json,state,created_at) VALUES(?,?,?,?,?,?,?,\'issued\',?)',[keyId,requestId,actor.id,actionId,templateVersion,encoded,JSON.stringify(manifest),clock()]);
|
||||
await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),actor.id,'jarvis-key-generated',JSON.stringify({keyId,actionId,requestId,ticketId:fields.ticketId,manifestHash:manifest.inventoryHash}),clock()]);
|
||||
}});const stored=await db.first('SELECT fields_json FROM jarvis_generated_instructions WHERE key_id=? AND account_id=?',[result.id,actor.id]);if(!stored||stored.fields_json!==encoded)throw Error('Instruction reference conflict');return availableCode(result,actor.id);
|
||||
}});const stored=await first(db,'SELECT fields_json FROM jarvis_generated_instructions WHERE key_id=? AND account_id=?',[result.id,actor.id]);if(!stored||stored.fields_json!==encoded)throw Error('Instruction reference conflict');return availableCode(result,actor.id);
|
||||
},
|
||||
async redeem(actor,{code,requestId}){
|
||||
await permitted(actor,'web.jarvis.clans.reset');if(typeof code!=='string'||!uuid(requestId))throw TypeError('Enter the generated key');
|
||||
const own=await db.first('SELECT id FROM organisation_keys WHERE account_id=? AND key_type=? AND code_hash=?',[actor.id,'clan-administration',hashOrganisationKey(code,'clan-administration')]);if(!own)throw Error('Key unavailable for this account');
|
||||
const instruction=await db.first('SELECT * FROM jarvis_generated_instructions WHERE key_id=? AND account_id=?',[own.id,actor.id]);if(!instruction)throw Error('Instruction unavailable');
|
||||
const own=await first(db,'SELECT id FROM organisation_keys WHERE account_id=? AND key_type=? AND code_hash=?',[actor.id,'clan-administration',hashOrganisationKey(code,'clan-administration')]);if(!own)throw Error('Key unavailable for this account');
|
||||
const instruction=await first(db,'SELECT * FROM jarvis_generated_instructions WHERE key_id=? AND account_id=?',[own.id,actor.id]);if(!instruction)throw Error('Instruction unavailable');
|
||||
return keys.consume({accountId:actor.id,keyType:'clan-administration',code,targetId:instruction.request_id,requestId,apply:async(tx,{keyId,scopeId})=>{
|
||||
await permitted(actor,'web.jarvis.clans.reset');
|
||||
const row=await tx.first('SELECT * FROM jarvis_generated_instructions WHERE key_id=? AND account_id=? FOR UPDATE',[keyId,actor.id]);
|
||||
|
|
|
|||
|
|
@ -4,10 +4,10 @@ import {companyFixture} from './company-deed-fixture.mjs';
|
|||
import {initializeJarvisGenerator,createMasterKeyGenerator,PROTECTED_RESET_TARGETS} from '../node/jarvis-master-generator.mjs';
|
||||
import {createMasterKeyGeneratorAPI} from '../node/jarvis-master-generator-api.mjs';
|
||||
async function fixture(){const f=await companyFixture();f.db.sqlite.exec("CREATE UNIQUE INDEX clan_identity ON site_clans(id);ALTER TABLE site_clans ADD COLUMN version INTEGER DEFAULT 1;ALTER TABLE site_clans ADD COLUMN updated_at INTEGER DEFAULT 1;CREATE TABLE site_clan_institutions(clan_id TEXT PRIMARY KEY,institution_key TEXT);CREATE TABLE site_clan_requests(clan_id TEXT,user_id TEXT,status TEXT,updated_at INTEGER);CREATE TABLE account_audit(id TEXT PRIMARY KEY,actor_id TEXT,action TEXT,details TEXT,created_at INTEGER);CREATE TABLE website_settings(setting_key TEXT PRIMARY KEY,setting_value TEXT,updated_at INTEGER);");await f.db.query(CLAN_DEED_SCHEMA);await initializeJarvisGenerator(f.db,{mysql:false});for(const [i,id]of PROTECTED_RESET_TARGETS.entries()){await f.db.query('INSERT INTO site_clans(id,name,owner_id,active) VALUES(?,?,?,1)',[id,i?'Veiled Concord':'Vaerkring',f.people.Owner.id]);await f.db.query('INSERT INTO site_clan_institutions VALUES(?,?)',[id,i?'bene':'guild']);await f.db.query("INSERT INTO site_clan_members VALUES(?,?,'owner')",[id,f.people.Owner.id]);await f.db.query('INSERT INTO site_clan_deeds(clan_id,updated_at) VALUES(?,1)',[id]);}
|
||||
let allowed=true;const authorize=async user=>allowed&&user.id===f.people.Owner.id,service=createMasterKeyGenerator(f.db,f.keys,{authorize});return {...f,service,authorize,revoke:()=>{allowed=false;},input:{actionId:'clan.clear-protected-rosters',templateVersion:1,values:{ticketId:'402',reference:'Owner-approved protected clan reset'},requestId:randomUUID()}};}
|
||||
const central={prepare:f.db.prepare.bind(f.db),query:f.db.query.bind(f.db),transaction:f.db.transaction.bind(f.db)};let allowed=true;const authorize=async user=>allowed&&user.id===f.people.Owner.id,service=createMasterKeyGenerator(central,f.keys,{authorize});return {...f,central,service,authorize,revoke:()=>{allowed=false;},input:{actionId:'clan.clear-protected-rosters',templateVersion:1,values:{ticketId:'402',reference:'Owner-approved protected clan reset'},requestId:randomUUID()}};}
|
||||
test('mastertemplate generates one bound key without changing clans; redemption clears only fixed rosters and owners',async()=>{const f=await fixture();try{
|
||||
const user=f.people.Owner,key=await f.service.issue(user,f.input);assert.ok(key.code.startsWith('CLAN-ADM-'));assert.equal(JSON.parse((await f.db.first('SELECT fields_json FROM jarvis_generated_instructions WHERE key_id=?',[key.keyId])).fields_json).ticketId,'402');assert.equal((await f.db.first('SELECT COUNT(*) n FROM site_clan_members')).n,2);assert.equal((await f.service.issue(user,f.input)).keyId,key.keyId);
|
||||
const claims=JSON.stringify(await f.db.query('SELECT * FROM site_claim_registry'));const instruction={code:key.code,requestId:randomUUID()};await f.service.redeem(user,instruction);assert.equal((await f.db.first('SELECT COUNT(*) n FROM site_clan_members')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM site_clans WHERE owner_id IS NULL AND active=1')).n,2);assert.equal(JSON.stringify(await f.db.query('SELECT * FROM site_claim_registry')),claims);assert.equal((await f.service.redeem(user,instruction)).replayed,true);assert.equal((await f.db.first("SELECT COUNT(*) n FROM account_audit WHERE action='jarvis-protected-rosters-cleared'")).n,1);
|
||||
}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.db,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();}});
|
||||
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();}});
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff