MC/website/tests/company-deeds.test.mjs
2026-11-27 23:43:05 +00:00

67 lines
11 KiB
JavaScript

import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';
import {BankFixture} from './postbank-fixture.mjs';
import {companyRegistrySchema,appointCompanyCeo,registerCompany} from '../node/company-registry.mjs';
import {initializeCompanyDeeds,readCompanyDeed} from '../node/company-deeds.mjs';
import {createCompanyDeedRoute} from '../node/company-deed-route.mjs';
import {createOrganisationKeys,organisationKeySchema} from '../node/organisation-keys.mjs';
import {createCompanyWorkspace} from '../node/company-workspace.mjs';
import {createPublicOrganisations} from '../node/public-organisations.mjs';
import {createPostbankAuthority,entityId} from '../node/postbank-authority.mjs';
import {PostbankService} from '../node/postbank-service.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs';
import {createOrganisationSettingsRoute} from '../node/organisation-settings-route.mjs';
import {companyFixture as fixture} from './company-deed-fixture.mjs';
test('Basic company registration is atomic and idempotent, gives one real owner and does not use keys or bank funds',async()=>{const f=await fixture();try{
const id=await f.create(),deed=await(await f.call(id)).json();assert.equal(deed.charterKind,'basic');assert.equal(deed.memberCount,1);assert.equal(deed.memberLimit,5);assert.equal(deed.members[0].role,'owner');assert.equal(deed.canUpgrade,true);
assert.equal((await f.call('',f.registration)).status,200);assert.equal((await f.db.first('SELECT COUNT(*) n FROM corrino_companies')).n,1);assert.equal((await f.call('',{...f.registration,requestId:randomUUID(),slug:'another-enterprise'})).status,409);assert.equal((await f.call('',{...f.registration,name:'Changed instruction'})).status,409);
assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);assert.equal((await f.call('',f.registration,'https://attacker.example')).status,403);
f.actor('Other');assert.equal((await f.call(id)).status,403);f.actor(null);assert.equal((await f.call(id)).status,401);
}finally{f.db.close();}});
test('the owner COM key upgrades exactly one company, retries safely, and never confers Royal status',async()=>{const f=await fixture();try{
const id=await f.create(),key=await f.keys.issue({accountId:f.people.Owner.id,keyType:'company-founding',scopeId:'original'}),body={action:'upgrade',code:key.code,version:1,requestId:randomUUID(),confirmed:true};
assert.equal((await f.call(id,body)).status,200);let view=await(await f.call(id)).json();assert.equal(view.charterKind,'original');assert.equal(view.memberLimit,25);assert.equal(view.version,2);assert.equal(view.canUpgrade,false);assert.equal((await f.call(id,body)).status,200);
assert.equal((await f.call(id,{...body,requestId:randomUUID()})).status,409);await initializeCompanyDeeds(f.db,{mysql:false});view=await(await f.call(id)).json();assert.equal(view.charterKind,'original');assert.equal(view.version,2);assert.equal((await f.keys.list(f.people.Owner.id))[0].status,'used');assert.equal((await f.db.first("SELECT COUNT(*) n FROM corrino_company_events WHERE action='key-upgrade'")).n,1);
assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);
}finally{f.db.close();}});
test('CEO management follows the register without taking the deed, counting twice or consuming an owner key',async()=>{const f=await fixture();try{
const id=await f.create();await appointCompanyCeo(f.db,{companyId:id,ceoId:f.people.Ceo.id,actorId:f.people.Owner.id,authorized:true});f.actor('Ceo');let view=await(await f.call(id)).json();assert.equal(view.role,'officer');assert.equal(view.memberCount,2);assert.equal(view.canUpgrade,false);
const ceoKey=await f.keys.issue({accountId:f.people.Ceo.id,keyType:'company-founding',scopeId:'original'});assert.equal((await f.call(id,{action:'upgrade',code:ceoKey.code,version:view.version,requestId:randomUUID(),confirmed:true})).status,409);assert.equal((await f.keys.list(f.people.Ceo.id))[0].status,'available');
await appointCompanyCeo(f.db,{companyId:id,ceoId:f.people.Owner.id,actorId:f.people.Owner.id,authorized:true});assert.equal((await f.call(id)).status,403);f.actor('Owner');view=await(await f.call(id)).json();assert.equal(view.memberCount,1);assert.equal(view.members[0].role,'owner');
const workspace=createCompanyWorkspace(f.db,{authenticate:async()=>f.people.Owner});const data=await(await workspace(new Request('https://cp.dunerealms.com/api/companies/workspace'))).json();assert.equal(data.companies[0].members.length,1);assert.equal(data.companies[0].memberLimit,5);
}finally{f.db.close();}});
test('company bank activation requires its own COM deed and public profiles show the actual owner and roster',async()=>{const f=await fixture();try{
const id=await f.create();await appointCompanyCeo(f.db,{companyId:id,ceoId:f.people.Ceo.id,actorId:f.people.Owner.id,authorized:true});
const authority=createPostbankAuthority(f.db,{bank:f.db,rightsFor:async()=>({nodes:['web.menu.game'],ranks:[]})}),service=new PostbankService(f.db,authority),entity=entityId('company',id),input={entityId:entity,packageKey:'pb_connect',termsVersion:BANK_VERSION,requestId:randomUUID(),accepted:true};
let context=await authority(f.people.Owner);assert.equal(context.entities.find(e=>e.id===entity).bankingRequirement,'company_key');await assert.rejects(service.activate(f.people.Owner,input),e=>e.status===403);
const key=await f.keys.issue({accountId:f.people.Owner.id,keyType:'company-founding',scopeId:'original'}),version=(await readCompanyDeed(f.db,id)).version;assert.equal((await f.call(id,{action:'upgrade',code:key.code,version,requestId:randomUUID(),confirmed:true})).status,200);context=await authority(f.people.Owner);assert.equal(context.entities.find(e=>e.id===entity).canActivate,true);await service.activate(f.people.Owner,input);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_activations')).n,1);
const api=createPublicOrganisations(f.db,{authenticate:async()=>null}),response=await api(new Request('https://www.dunerealms.com/api/public/companies/test-enterprise'));assert.equal(response.status,200);const publicData=(await response.json()).organisation;assert.equal(publicData.owner_username,'Owner');assert.equal(publicData.member_count,2);assert.equal(publicData.standing,'Keyed Company');assert.deepEqual(new Set(publicData.members.map(m=>m.username)),new Set(['Owner','Ceo']));assert.ok(!JSON.stringify(publicData).includes(key.code));assert.ok(!JSON.stringify(publicData).includes(f.people.Owner.id));
}finally{f.db.close();}});
test('existing registration stays pending, deed backfill preserves its establishment date and never rewrites ownership',async()=>{const f=await fixture();try{
const pending=await registerCompany(f.db,{slug:'pending-enterprise',name:'Pending Enterprise',founderId:f.people.Owner.id,actorId:f.people.Owner.id,authorized:true});assert.equal(pending.status,'pending');let deed=await readCompanyDeed(f.db,pending.id);assert.equal(deed.company.charter_kind,'basic');assert.equal(deed.memberCount,1);
const legacy=randomUUID();await f.db.query("INSERT INTO corrino_companies(id,slug,name,description,founded_by,status,created_at,updated_at) VALUES(?,'legacy-enterprise','Legacy Enterprise','',?,'active',123,123)",[legacy,f.people.Other.id]);await initializeCompanyDeeds(f.db,{mysql:false});deed=await readCompanyDeed(f.db,legacy);assert.equal(deed.company.owner_account_id,f.people.Other.id);assert.equal(deed.company.created_at,123);
const count=(await f.db.first('SELECT COUNT(*) n FROM corrino_company_events')).n;await initializeCompanyDeeds(f.db,{mysql:false});assert.equal((await f.db.first('SELECT COUNT(*) n FROM corrino_company_events')).n,count);
await f.db.query('UPDATE corrino_companies SET founded_by=?,ceo_account_id=? WHERE id=?',[f.people.Owner.id,f.people.Owner.id,legacy]);await initializeCompanyDeeds(f.db,{mysql:false});deed=await readCompanyDeed(f.db,legacy);assert.equal(deed.company.owner_account_id,f.people.Other.id);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,0);
}finally{f.db.close();}});
test('a failed deed write leaves no company or partial registration to replay',async()=>{const f=await fixture();try{
const query=f.db.query;f.db.query=async(sql,args)=>{if(sql.startsWith('INSERT INTO site_company_members'))throw Error('simulated write failure');return query(sql,args);};assert.equal((await f.call('',f.registration)).status,503);
for(const table of ['corrino_companies','site_company_deeds','site_company_members','corrino_company_events'])assert.equal((await f.db.first('SELECT COUNT(*) n FROM '+table)).n,0);
f.db.query=query;assert.equal((await f.call('',f.registration)).status,201);assert.equal((await f.db.first('SELECT COUNT(*) n FROM corrino_companies')).n,1);
}finally{f.db.close();}});
test('ordinary company members can read their welcome message without receiving identity or MOTD editing rights',async()=>{const f=await fixture();try{
const id=await f.create();f.db.sqlite.exec('CREATE TABLE organisation_motd(organisation_kind TEXT,organisation_id TEXT,message TEXT,updated_by TEXT,updated_at INT,PRIMARY KEY(organisation_kind,organisation_id));CREATE TABLE account_audit(id TEXT,actor_id TEXT,action TEXT,details TEXT,created_at INT);');await f.db.query('INSERT INTO site_company_members VALUES(?,?,1)',[id,f.people.Member.id]);
const api=createOrganisationSettingsRoute(f.db,{authenticate:async()=>f.currentUser(),access:async()=>({nodes:['web.menu.game']})}),call=body=>api(new Request('https://cp.dunerealms.com/api/organisations/company/'+id+'/settings',body?{method:'POST',headers:{origin:'https://cp.dunerealms.com','Content-Type':'application/json'},body:JSON.stringify(body)}:{}));
assert.equal((await call({action:'motd',revision:0,message:'Welcome to the company'})).status,200);f.actor('Member');const message=await(await call()).json();assert.equal(message.motd,'Welcome to the company');assert.equal(message.canEditIdentity,false);assert.equal(message.canEditMotd,false);assert.equal((await call({action:'motd',revision:message.motdRevision,message:'Forged'})).status,403);f.actor('Other');assert.equal((await call()).status,403);
}finally{f.db.close();}});
test('a CEO appointment cannot bypass the Basic population cap and valid changes invalidate stale deed versions',async()=>{const f=await fixture();try{
const id=await f.create();for(let n=0;n<4;n++){const member=randomUUID();await f.db.query("INSERT INTO site_accounts(id,username,role) VALUES(?,?,'player')",[member,'Existing'+n]);await f.db.query('INSERT INTO site_company_members VALUES(?,?,1)',[id,member]);}
await assert.rejects(appointCompanyCeo(f.db,{companyId:id,ceoId:f.people.Ceo.id,actorId:f.people.Owner.id,authorized:true}),/membership limit/);assert.equal((await readCompanyDeed(f.db,id)).version,1);assert.equal((await f.db.first('SELECT ceo_account_id FROM corrino_companies WHERE id=?',[id])).ceo_account_id,null);
await appointCompanyCeo(f.db,{companyId:id,ceoId:f.people.Owner.id,actorId:f.people.Owner.id,authorized:true});assert.equal((await readCompanyDeed(f.db,id)).version,2);assert.equal((await readCompanyDeed(f.db,id)).memberCount,5);
}finally{f.db.close();}});