web/website/tests/citizen-directory.test.mjs
2026-11-21 20:22:37 +01:00

71 lines
6.1 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import {createCitizenDirectory,directoryFilters} from '../node/citizen-directory.mjs';
import {ORGANISATION,initializeOrganisation} from '../node/organisation-model.mjs';
const id='49d2fe76-7977-4d49-bd39-e48fc8c648b8';
const row={id,username:'example',display_name:'Example',created_at:100,account_status:'active',minecraft_name:'Example',minecraft_uuid:id};
const assignment=(type,key,role)=>({id:'assignment',user_id:id,scope_type:type,scope_key:key,role_key:role,source_kind:'appointment',starts_at:1,ends_at:null});
function fixture({rows=[row],grants=[assignment('clan','clan-example','member'),assignment('branch','trust_safety','officer')],authenticated=true,allowed=true,active=false}={}){
const queries=[];
const db={organisationAccessEnabled:active,prepare(sql){let args=[];queries.push({sql,get args(){return args;}});return {bind(...v){args=v;return this;},async first(){return rows.find(r=>r.id===args[0])||null;},async all(){
if(sql.includes('FROM org_assignments WHERE'))return {results:grants.filter(g=>sql.includes("scope_type NOT IN")?!['organisation','department','branch'].includes(g.scope_type):['organisation','department','branch'].includes(g.scope_type))};
if(sql.includes('FROM staff_source_members WHERE'))return {results:[{source_name:'.bedrock',source_ref:'private-staff-source',imported_at:10}]};
return {results:rows};
}}}};
return {queries,api:createCitizenDirectory(db,{authenticate:async()=>authenticated?{id,role:'user'}:null,authorize:async()=>allowed,clock:()=>50})};
}
const req=(path='?context=users',method='GET')=>new Request('https://cp.dunerealms.com/api/admin/citizens'+path,{method});
test('directory reports actual activation in list, account and catalogue responses',async()=>{
for(const active of [false,true])for(const suffix of ['?context=staff','/'+id+'?context=staff','/catalogue?context=staff']){
const data=await (await fixture({active}).api(req(suffix))).json();
assert.equal(data.assignmentMode,active?'active':'preparing');
}
});
test('directory rejects guests and unprivileged users before database reads',async()=>{
for(const [options,status]of [[{authenticated:false},401],[{allowed:false},403]]){const f=fixture(options);assert.equal((await f.api(req())).status,status);assert.equal(f.queries.length,0);}
});
test('directory is read-only; catalog registration never seeds appointments or grants',async()=>{
assert.equal((await fixture().api(req('','POST'))).status,405);
const statements=[];await initializeOrganisation({prepare(sql){statements.push(sql);return{run:async()=>{}};}});
assert.ok(statements.every(sql=>sql.startsWith('CREATE TABLE IF NOT EXISTS')));
assert.equal(ORGANISATION.length,2);assert.equal(ORGANISATION.flatMap(d=>d.branches).length,9);
});
test('user detail never contains staff sources, legacy staff rank or staff assignments',async()=>{
const f=fixture();const response=await f.api(req('/'+id+'?context=users'));const data=await response.json();
assert.equal(response.status,200);assert.equal(data.account.assignments.length,1);assert.equal(data.account.assignments[0].scopeType,'clan');
assert.equal(data.account.staffSources,undefined);assert.equal(data.account.primaryRank,undefined);
assert.equal(f.queries.some(q=>q.sql.includes('FROM staff_source_members WHERE')),false);
});
test('staff detail only contains staff scopes and includes imported provenance',async()=>{
const response=await fixture().api(req('/'+id+'?context=staff'));const data=await response.json();
assert.equal(data.account.assignments.length,1);assert.equal(data.account.assignments[0].scopeLabel,'Trust & Safety');assert.equal(data.account.assignments[0].roleLabel,'Officer');
assert.equal(data.account.staffSources[0].name,'.bedrock');assert.equal(data.permissionsChanged,false);
});
test('invalid contexts and incompatible department/branch filters fail before SQL',async()=>{
for(const suffix of ['?context=owner','?context=users&branch=engineering','?context=staff&department=community_operations&branch=engineering','?page=0','?page=1;DROP','?q='+('x'.repeat(81))]){
const f=fixture();assert.equal((await f.api(req(suffix))).status,400,suffix);assert.equal(f.queries.length,0);
}
});
test('SQL search is parameterised and treats wildcard characters literally',()=>{
const f=directoryFilters(new URL("https://cp.dunerealms.com/?q=%25_%3D'%20OR%201%3D1"));
assert.ok(!f.where.includes("OR 1=1"));assert.ok(f.where.includes("ESCAPE '='"));assert.ok(f.values[0].includes('=%=_=='));assert.equal(f.values.length,4);
});
test('staff cohort and scoped filters use parameterised fresh active assignment checks',()=>{
const f=directoryFilters(new URL('https://cp.dunerealms.com/?context=staff&department=dunerealms_operations&branch=engineering'),500);
assert.ok(f.where.includes('staff_source_members'));assert.ok(f.where.includes('cp_account_ranks'));assert.ok(f.where.includes('starts_at<=?'));assert.ok(f.where.includes('service.game_link_exempt=1'));
assert.deepEqual(f.values.slice(-3),['engineering',500,500]);assert.ok(!f.where.includes("scope_key IN ('engineering')"));
});
test('directory pagination uses an extra sentinel record, not row count guessing',async()=>{
const rows=Array.from({length:26},(_,i)=>({...row,id:String(i)}));const f=fixture({rows,grants:[]});const data=await (await f.api(req('?page=2'))).json();
assert.equal(data.accounts.length,25);assert.equal(data.hasMore,true);assert.equal(data.page,2);assert.deepEqual(f.queries[0].args.slice(-2),[26,25]);
});
test('empty and missing accounts are handled explicitly',async()=>{
const f=fixture({rows:[]});assert.equal((await (await f.api(req())).json()).hasMore,false);assert.equal((await f.api(req('/'+id))).status,404);
});
test('catalogue respects the same user/staff context split',async()=>{
const api=fixture().api;
const users=await (await api(req('/catalogue?context=users'))).json();assert.equal(users.departments.length,0);assert.equal(users.roles.branch,undefined);assert.ok(users.roles.clan);
const staff=await (await api(req('/catalogue?context=staff'))).json();assert.equal(staff.departments.length,2);assert.equal(staff.roles.clan,undefined);assert.ok(staff.roles.branch);
});