Merge pull request 'Protect hidden smuggler institutions and bind secondary quest affiliations' (#455) from feature/dev-workload-resume-20261121 into main
All checks were successful
DuneRealms Web CI / web (push) Successful in 3m16s
All checks were successful
DuneRealms Web CI / web (push) Successful in 3m16s
This commit is contained in:
commit
40d33ca9cd
18 changed files with 218 additions and 62 deletions
11
docs/design/CLANDESTINE-INSTITUTIONS.md
Normal file
11
docs/design/CLANDESTINE-INSTITUTIONS.md
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
# Protected smuggler institutions — ticket 412
|
||||
|
||||
The Unmarked Caravan is a real protected clan; Tuek Hidden Exchange is a real protected company. Their reserved identities are declared in `clandestine-identity.mjs`. They use the existing clan/company registries, deeds, protected-institution guards and one ordinary consumed STAFF-LINK charter. No replacement organisation, account, bank or quest engine is introduced.
|
||||
|
||||
The current Esmar Tuek system identity is the permanent technical custodian. Its existing non-login system role and scoped quest capabilities remain unchanged. No ordinary account is moved, promoted or given a synthetic game identity by this operation. The charter refuses identity/name collisions and an already-affiliated custodian; it never adopts an unrelated organisation. Both institutions, their deeds and the audit are committed atomically. An interruption retains an unconsumed key and retries that same key. This is an explicitly run current-owner server operation, never a startup data mutation or browser-issued developer key.
|
||||
|
||||
Both institutions are omitted from public company/clan registers, direct public profiles, ordinary CP list/deed routes and the public organisation network. Ordinary forum provisioning skips them. Their permanent protected identities cannot be sold, archived or reassigned through ordinary management. Staff client administration does not bypass the scoped charter to appoint a new hidden-company CEO. The charter creates no mailbox, bank account, forum, game clan or NPC synchronization; none of those effects is claimed.
|
||||
|
||||
Completing the existing verified `POL-SMUGGLERS-01` introduction adds two secondary affiliation records in the same transaction as the original QST claim. The consumed QST is the affiliation source: there is no second membership key. The normal primary clan, normal company membership, votes, bank authority and game affiliation remain untouched. The only secondary capability is `quest.smuggling`; the records grant no PvP, bank management, staff, office or election authority. The authenticated player's Reputation journal shows the affiliation using its existing layout, without a new control panel.
|
||||
|
||||
Affiliation reads require the matching actual quest claim and consumed/unrevoked QST plus the current protected institution charter. Revoking evidence hides the active affiliation while retaining history. A copied row, unconsumed key, generated instruction or browser assertion does not establish membership. Original system accounts remain excluded from AD and ordinary player rewards. The future game producer must supply real quest evidence; no introduction or player membership is fabricated for production verification.
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
import {isClandestineInstitution} from '../node/clandestine-identity.mjs';
|
||||
import {membershipRequest,membershipReview,MembershipError} from '../node/membership-recruitment.mjs';
|
||||
import {JarvisError} from '../node/jarvis-listings.mjs';
|
||||
import {JARVIS_CLAN_REQUEST_SCHEMA} from '../node/jarvis-clan-requests.mjs';
|
||||
|
|
@ -37,7 +38,7 @@ export function createClans(db,{origin='https://cp.dunerealms.com',authenticate=
|
|||
const publicClan=row=>{const {owner_id,...safe}=row;return {...safe,homeworldName:CLAN_HOMEWORLDS.find(w=>w.key===row.home_world)?.name||null,realm:CLAN_HOMEWORLDS.find(w=>w.key===row.home_world)?.realm||null,emblem:clanEmblemUrl(row.id,row.emblemVersion||0)};};
|
||||
return async request=>{
|
||||
const url=new URL(request.url),match=url.pathname.match(/^\/api\/clans(?:\/([a-f0-9-]{36}))?$/i);
|
||||
if(!match)return json({message:'Not found'},404);
|
||||
if(!match||isClandestineInstitution('clan',match[1]))return json({message:'Not found'},404);
|
||||
if(!['GET','POST'].includes(request.method))return json({message:'Method not allowed'},405);
|
||||
const user=await authenticate(request);if(!user)return json({message:'Sign in to use the Clan Center.'},401);
|
||||
const rights=await access(user);if(!rights.nodes.includes('web.menu.game'))return json({message:'Game account access is required.'},403);
|
||||
|
|
@ -47,7 +48,7 @@ export function createClans(db,{origin='https://cp.dunerealms.com',authenticate=
|
|||
if(!match[1]){
|
||||
const {results}=await db.prepare(`SELECT c.id,c.name,c.tag,c.description,c.home_world,c.version,c.created_at,(SELECT a.username FROM site_accounts a WHERE a.id=c.owner_id) owner_username,(SELECT a.display_name FROM site_accounts a WHERE a.id=c.owner_id) owner_name,COALESCE((SELECT ch.charter_kind FROM site_clan_charters ch WHERE ch.clan_id=c.id),'basic') charter_kind,i.institution_key,i.member_limit,(SELECT COUNT(*) FROM site_clan_members m WHERE m.clan_id=c.id) AS member_count FROM site_clans c LEFT JOIN site_clan_institutions i ON i.clan_id=c.id WHERE c.active=1 ORDER BY c.name_key,c.id LIMIT 500`).all();
|
||||
const {results:applications}=await db.prepare("SELECT r.clan_id,r.status,c.name,c.tag FROM site_clan_requests r JOIN site_clans c ON c.id=r.clan_id WHERE r.user_id=? AND r.status='pending' AND c.active=1 ORDER BY r.created_at DESC").bind(user.id).all();
|
||||
return json({homeworlds:CLAN_HOMEWORLDS,clans:results.map(row=>({...row,memberLimit:clanMemberLimit(row.charter_kind,row.institution_key?row.member_limit:null),homeworldName:CLAN_HOMEWORLDS.find(w=>w.key===row.home_world)?.name||null,realm:CLAN_HOMEWORLDS.find(w=>w.key===row.home_world)?.realm||null,emblem:clanEmblemUrl(row.id)})),membership:own,applications,linked,username:user.username});
|
||||
return json({homeworlds:CLAN_HOMEWORLDS,clans:results.filter(row=>!isClandestineInstitution('clan',row.id)).map(row=>({...row,memberLimit:clanMemberLimit(row.charter_kind,row.institution_key?row.member_limit:null),homeworldName:CLAN_HOMEWORLDS.find(w=>w.key===row.home_world)?.name||null,realm:CLAN_HOMEWORLDS.find(w=>w.key===row.home_world)?.realm||null,emblem:clanEmblemUrl(row.id)})),membership:own,applications,linked,username:user.username});
|
||||
}
|
||||
const record=await clan(match[1]);if(!record)return json({message:'Clan not found.'},404);
|
||||
const charter=await institution(record.id);record.institution=charter?{key:charter.institution_key,memberLimit:Number(charter.member_limit),franchiseTerms:Number(charter.franchise_terms),protected:true,recruitmentOpen:false}:null;
|
||||
|
|
|
|||
|
|
@ -48,6 +48,7 @@ export function mountPersonalProgression(host,{view='missions',fetcher=fetch,api
|
|||
if(data.state!=='active')return;
|
||||
const stats=el('div',undefined,'progression-stats');stats.append(el('strong',(data.xpType==='pol'?'Reputation level ':'Personal level ')+data.profile.level+(data.season.levelCap===null?' · uncapped':' / '+data.season.levelCap)),el('span',data.profile.effectiveXP.toLocaleString()+(data.xpType==='pol'?' reputation':' seasonal XP')),el('span','Season ends '+date(data.season.endsAt)));
|
||||
const progress=el('progress');progress.max=data.season.levelCap;progress.value=data.profile.level;progress.setAttribute('aria-label','Season level');if(data.season.levelCap!==null)stats.append(progress);body.append(stats);
|
||||
if(data.affiliations?.length){const affiliation=el('aside',undefined,'progression-intro');affiliation.append(el('strong','The Unmarked Caravan'),el('p','Your smuggler clan and company affiliations are secondary. Your ordinary affiliations stay in place.'));body.append(affiliation);}
|
||||
const select=el('select');select.setAttribute('aria-label','Mission branch');
|
||||
const availableBranches=data.branches||branches;for(const b of availableBranches){if(!data.quests.some(q=>q.branch===b.id))continue;const option=el('option',b.title);option.value=b.id;select.append(option);}
|
||||
if(!data.quests.some(q=>q.branch===branch))branch=data.quests[0]?.branch;
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ export const MASTER_KEY_TEMPLATES=[
|
|||
{id:'claims',label:'Home Blocks',actions:[action('claims.remove-homeblock','Remove Home Block with staff overwrite','staff-claim',[field('kind','Organisation kind'),field('id','Organisation'),field('expectedRevision','Current claim revision','number',{min:1}),field('reason','Staff reason')],{webIssue:false,domainAdapter:'staffHomeBlockKeys',executionStatus:'staff-key-consumer',effect:'Remove only the Home Block marker through existing staff overwrite authority. Preserve estates, balances, rosters and history. Existing rebellion checks then deny the chain; no control panel or timer.'})]},
|
||||
{id:'state',label:'Entity state',actions:[action('state.estate-freeze','Freeze estate from lore-death ESK','entity-state',[field('keyId','Verified lore-death ESK'),reference],{domainAdapter:'PostbankEstates.freeze',executionStatus:'bank-staff-consumer',effect:'Restrict existing personal accounts using a verified lore-death ESK; no balance changes.'}),action('state.estate-unlock','Unlock ESK estate','entity-state',[field('keyId','Existing ESK'),field('revision','Current bank effect revision','number',{min:1}),reference],{domainAdapter:'PostbankEstates.unlock',executionStatus:'bank-staff-consumer',effect:'Bank staff restore only the accounts held by the named ESK. Original death evidence remains unchanged.'}),action('state.record','Entity State Key','entity-state',[field('eventId','Unique source event ID'),field('action','State event'),field('targetUuid','Target entity UUID'),field('targetKind','Player or mob'),field('entityType','Entity type'),field('actorUuid','Killer / actor UUID','text',{required:false}),field('cause','Cause / reason'),field('scope','Server / lore scope'),field('world','World'),field('occurredAt','Event timestamp','number',{min:0}),reference],{recordOnly:true,domainAdapter:'entityStateKeys',executionStatus:'verified-service-record',artwork:'esk-key-v1.png',effect:'Record a verified death, respawn, ban or unban. Shared quest/contract/deed evidence with separate once-only consumer receipts. No Minecraft producer or ban migration in this batch.'})]},
|
||||
{id:'progression',label:'Progression & XP',actions:[
|
||||
action('progression.smuggler-institutions','Protected hidden smuggler institutions','staff-parent-link',[],{webIssue:false,domainAdapter:'clandestineInstitutions.provision',executionStatus:'current-owner-server-operator',effect:'Create the fixed protected clan and company under the current Esmar Tuek system identity. A verified introduction QST grants secondary quest affiliations only; never replace a player clan/company or grant PvP, bank, staff or office authority.'}),
|
||||
action('progression.pol-activity','Verified Reputation activity','quest-milestone',[field('eventId','Unique domain event'),field('accountId','Current player account'),field('minecraftUuid','Current linked player UUID'),field('seasonId','Current season'),field('metric','Registered objective metric'),field('quantity','Verified quantity','number',{min:1}),field('reference','Original evidence reference')],{webIssue:false,recordOnly:true,domainAdapter:'polActivityEvents.record',executionStatus:'trusted-domain-producer-only',effect:'Bind actual committed activity to the current player, season and quest-giver SID. Reuse existing QSM evidence and POL claims; a browser cannot assert progress. PvP, mob and death objectives require original production Minecraft ESK evidence instead.'}),
|
||||
action('progression.pol-repeatables','Ongoing Reputation quest policy','progression-policy',[field('season','Season'),field('policyVersion','Policy version','number',{min:2})],{webIssue:false,recordOnly:true,domainAdapter:'ensurePOLRepeatablePolicy',executionStatus:'recorded-system-policy',effect:'Configure repeating PvP, mob, death, spice and smuggling episodes through existing QST claims. The bonus grows by 2% per completed round to a 5x cap. No default DM is minted; unverified game objectives stay pending.'}),
|
||||
action('xp.correct','Approved XP correction','xp-correction',[field('recipient','Recipient'),field('amountXP','XP amount','number',{min:1}),field('caseReference','Approved support case')]),
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import {initializeSecondaryAffiliations} from '../node/clandestine-institutions.mjs';
|
||||
import {initializePOLActivityEvents} from '../node/pol-activity-events.mjs';
|
||||
import {createPOLActivityAPI} from '../node/pol-activity-api.mjs';
|
||||
import {openStarterKitDelivery} from '../node/starter-kit-delivery.mjs';
|
||||
|
|
@ -467,7 +468,7 @@ export async function startPanel(settings=process.env){
|
|||
inventoryPool.on('error',()=>console.error('Inventory database connection unavailable.'));
|
||||
}
|
||||
const bankDatabase=await openPostbankDatabase(settings);
|
||||
const db=await openDatabase(settings);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;await initializeProgression(db);await initializeStarterKitEvents(db);db.starterKitEventsEnabled=true;await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await ensureStarterKitRewardPolicy(db,organisationKeys).catch(()=>console.error('Starter kit reward policy requires review; existing custom configuration was preserved'));await initializePOLProgression(db);await initializePOLActivityEvents(db);db.polActivityEventsEnabled=true;await initializeRebellionRewards(db);await ensurePOLProgressionPolicy(db,organisationKeys);await ensurePOLRepeatablePolicy(db,organisationKeys);db.polRepeatablesEnabled=true;const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const starterKitDelivery=await openStarterKitDelivery(db,settings);const boardRuntime=await openBoardKeyRuntime(db,organisationKeys,settings);const handle=createPanel(db,settings,{boardRuntime,inventoryPool,bankDatabase,organisationKeys,deedPurchases,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com';
|
||||
const db=await openDatabase(settings);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;await initializeProgression(db);await initializeStarterKitEvents(db);db.starterKitEventsEnabled=true;await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await ensureStarterKitRewardPolicy(db,organisationKeys).catch(()=>console.error('Starter kit reward policy requires review; existing custom configuration was preserved'));await initializePOLProgression(db);await initializeSecondaryAffiliations(db);await initializePOLActivityEvents(db);db.polActivityEventsEnabled=true;await initializeRebellionRewards(db);await ensurePOLProgressionPolicy(db,organisationKeys);await ensurePOLRepeatablePolicy(db,organisationKeys);db.polRepeatablesEnabled=true;const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const starterKitDelivery=await openStarterKitDelivery(db,settings);const boardRuntime=await openBoardKeyRuntime(db,organisationKeys,settings);const handle=createPanel(db,settings,{boardRuntime,inventoryPool,bankDatabase,organisationKeys,deedPurchases,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com';
|
||||
await initializeInternalMailAccess(db);const stopElectionClock=startElectionClock(db);const stopOfficeLedger=startOfficeLedger(db);
|
||||
const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db,{jarvisStore:bankDatabase}),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings,{extraTasks:[{key:'starter_kit_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>starterKitDelivery.drain()},...(boardRuntime?[{key:'board_keys',slot:now=>Math.floor(now/60000)*60000,run:()=>boardRuntime.drain()}]:[]),...(bankDatabase?[{key:'rebellion_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createRebellionRewards(db,bankDatabase,{sourceAccount:settings.REBELLION_REWARD_SOURCE_ACCOUNT,sourceOwnerId:settings.REBELLION_REWARD_SOURCE_OWNER_ID,useWebsiteTreasury:settings.REBELLION_REWARD_FUND==='website-treasury'}).drain()},...(deedPurchases?[{key:'deed_purchases',slot:now=>Math.floor(now/60000)*60000,run:()=>deedPurchases.drain()}]:[]),{key:'server_projects',slot:now=>Math.floor(now/60000)*60000,run:()=>createServerProjectRuntime(db,bankDatabase,organisationKeys).drain()},{key:'progression_completion',slot:now=>Math.floor(now/60000)*60000,run:async()=>{const completed=await progressionRuntime.quests.processCompletions();const news=await progressionRuntime.announcements.drain();return {completed,news};}},{key:'naib_council',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await reconcileNaibChairs(db);return createNaibCouncil(db).reconcile();}},{key:'jarvis_promotions',slot:now=>Math.floor(now/15000)*15000,run:()=>promotionDelivery.drain()},{key:'political_jobs',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await createPoliticalJobs(db,bankDatabase).reconcile();return drainPoliticalJobNotifications(db,{broker:internalMailBroker,eligible:internalMailEligible});}},{key:'order_membership',slot:now=>Math.floor(now/60000)*60000,run:()=>reconcileCrysknifeCompany(db,organisationKeys)},{key:'office_auctions',slot:now=>Math.floor(now/60000)*60000,run:()=>officeAuctionRuntime.process()},{key:'jarvis_settlement',slot:now=>standardCycle(now).cutoff,async run(cutoff){const payments=createJarvisPayments(bankDatabase,createPostbankAuthority(db,{bank:bankDatabase}));for(let i=0;i<40;i++){const result=await payments.settle(cutoff);if(result.failed)return result;if(result.attempted<100)return result;}return {failed:1};}}]:[])]});
|
||||
const security={'X-Robots-Tag':'noindex, nofollow, noarchive','X-Content-Type-Options':'nosniff','Referrer-Policy':'no-referrer','Cache-Control':'no-store','Content-Security-Policy':"default-src 'self'; script-src 'self' https://www.dunerealms.com; style-src 'self' https://www.dunerealms.com https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://www.dunerealms.com; img-src 'self' data: https://www.dunerealms.com https://support.dunerealms.com; frame-src 'self' https://luckperms.net https://www.dunerealms.com https://support.dunerealms.com https://forums.dunerealms.com https://clans.dunerealms.com https://corp.dunerealms.com https://wiki.dunerealms.com; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'self' https://www.dunerealms.com https://dunerealms.com https://clans.dunerealms.com"};
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"schemaVersion": 1,
|
||||
"sourceHash": "b09af9b92321e69f6d3dbafd9b00fcbfa96f532dc6f000d60fdcd3d725562a31",
|
||||
"sourceHash": "4c70fe3bbd0cfa54b9886ffba870101bc91ed71c6033fdd73a7ef74181566655",
|
||||
"actions": [
|
||||
{
|
||||
"id": "clan.clear-protected-rosters",
|
||||
|
|
@ -778,6 +778,25 @@
|
|||
"webIssue": false,
|
||||
"recordOnly": true
|
||||
},
|
||||
{
|
||||
"id": "progression.smuggler-institutions",
|
||||
"label": "Progression & XP · Protected hidden smuggler institutions",
|
||||
"version": 1,
|
||||
"keyType": "staff-parent-link",
|
||||
"fields": [
|
||||
{
|
||||
"name": "ticketId",
|
||||
"label": "Ban / support ticket ID",
|
||||
"type": "text",
|
||||
"required": true,
|
||||
"maxLength": 80
|
||||
}
|
||||
],
|
||||
"effect": "Create the fixed protected clan and company under the current Esmar Tuek system identity. A verified introduction QST grants secondary quest affiliations only; never replace a player clan/company or grant PvP, bank, staff or office authority.",
|
||||
"fixedTargets": [],
|
||||
"webIssue": false,
|
||||
"recordOnly": false
|
||||
},
|
||||
{
|
||||
"id": "progression.pol-activity",
|
||||
"label": "Progression & XP · Verified Reputation activity",
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import {isClandestineInstitution} from './clandestine-identity.mjs';
|
||||
import {createHash} from 'node:crypto';
|
||||
import {PUBLIC_OFFICES} from './public-government.mjs';
|
||||
import {politicalOfficeId} from './political-office-charters.mjs';
|
||||
|
|
@ -24,8 +25,8 @@ export async function boardSourceObservations(db,{clock=Date.now}={}){
|
|||
for(const rows of [clans,companies,terms,overrides])bounded(rows,500);for(const rows of [clanMembers,companyMembers,appointments,orderMembers])bounded(rows,5000);bounded(charters,100);bounded(orders,100);bounded(known,1000);
|
||||
const saved=new Map(known.map(r=>[r.organisation_kind+':'+r.organisation_id,r.watch_fingerprint])),clanRoster=group(clanMembers,'clan_id'),companyRoster=group(companyMembers,'company_id'),orderRoster=group(orderMembers,'order_id'),delegations=new Map(overrides.map(r=>[r.organisation_kind+':'+r.organisation_id,r])),result=[];
|
||||
const add=(kind,id,parts)=>{const identity=kind+':'+id,fingerprint=digest([...parts,delegations.get(identity)||null]);if(saved.get(identity)!==fingerprint)result.push({kind,id,watchFingerprint:fingerprint});};
|
||||
for(const row of clans)if(Number(row.active)===1||saved.has('clan:'+row.id))add('clan',row.id,[row,clanRoster.get(row.id)||[]]);
|
||||
for(const row of companies)if(['active','converted-order'].includes(row.status)||saved.has('company:'+row.id)){const order=orders.find(o=>o.legacy_company_id===row.id);add('company',row.id,[row,companyRoster.get(row.id)||[],order||null,order?orderRoster.get(order.id)||[]:[],order?terms:[]]);}
|
||||
for(const row of clans)if(!isClandestineInstitution('clan',row.id)&&(Number(row.active)===1||saved.has('clan:'+row.id)))add('clan',row.id,[row,clanRoster.get(row.id)||[]]);
|
||||
for(const row of companies)if(!isClandestineInstitution('company',row.id)&&(['active','converted-order'].includes(row.status)||saved.has('company:'+row.id))){const order=orders.find(o=>o.legacy_company_id===row.id);add('company',row.id,[row,companyRoster.get(row.id)||[],order||null,order?orderRoster.get(order.id)||[]:[],order?terms:[]]);}
|
||||
for(const office of PUBLIC_OFFICES){const id=politicalOfficeId(office.key),active=terms.filter(t=>t.kind===office.kind&&t.faction===office.faction&&t.office===office.office);if(!active.length&&!saved.has('politics:'+id)&&!(office.kind==='naib_chair'&&clans.some(c=>Number(c.active)===1&&c.home_world==='arrakduin')))continue;add('politics',id,[charters.find(c=>c.office_key===office.key)||null,active,appointments.filter(a=>a.office_key===office.key),office.kind==='naib_chair'?clans:[],office.kind==='naib_chair'?clanMembers:[]]);}
|
||||
return result;
|
||||
}
|
||||
|
|
|
|||
5
website/node/clandestine-identity.mjs
Normal file
5
website/node/clandestine-identity.mjs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
// Reserved institution identities, not account permissions or secret credentials.
|
||||
export const SMUGGLER_CLAN_ID='b8a5e927-bf75-5f2c-851a-5c025d98b009';
|
||||
export const SMUGGLER_COMPANY_ID='e0e65286-e00f-57ed-83cf-43d1fb9d24df';
|
||||
export const isClandestineInstitution=(kind,id)=>['clan','company'].includes(kind)&&String(id||'').toLowerCase()===(kind==='clan'?SMUGGLER_CLAN_ID:SMUGGLER_COMPANY_ID);
|
||||
export const SMUGGLER_COMPANY_SLUG='tuek-hidden-exchange';
|
||||
48
website/node/clandestine-institutions.mjs
Normal file
48
website/node/clandestine-institutions.mjs
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import {randomUUID} from 'node:crypto';
|
||||
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
|
||||
import {createSystemCharacters} from './system-characters.mjs';
|
||||
import {recordInitialCompanyDeed} from './company-deeds.mjs';
|
||||
import {SMUGGLER_CLAN_ID,SMUGGLER_COMPANY_ID} from './clandestine-identity.mjs';
|
||||
const scope='institution:smugglers:v1',requestId='f905b561-73e4-59c3-a5cf-c06e82100fc1';
|
||||
export const SECONDARY_AFFILIATION_SCHEMA='CREATE TABLE IF NOT EXISTS jarvis_secondary_affiliations(account_id CHAR(36) NOT NULL,organisation_kind VARCHAR(12) NOT NULL,organisation_id CHAR(36) NOT NULL,source_key_id CHAR(36) NOT NULL,joined_at BIGINT NOT NULL,PRIMARY KEY(account_id,organisation_kind,organisation_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4';
|
||||
export async function initializeSecondaryAffiliations(db){await db.query(SECONDARY_AFFILIATION_SCHEMA);db.secondaryAffiliationsEnabled=true;}
|
||||
const first=async(db,sql,args=[])=>(await db.query(sql,args))[0]||null;
|
||||
async function custodian(store,keys){const identity=await createSystemCharacters(store,keys,{authorizeOperator:async()=>false}).inspect('esmar_tuek');if(!identity?.capabilities.includes('quest.issue'))throw Error('Current smuggler system identity required');return identity;}
|
||||
export async function readSmugglerInstitutions(store,keys,{lock=false}={}){
|
||||
const identity=await custodian(store,keys),row=await first(store,"SELECT k.id,k.used_at,k.revoked_at FROM organisation_keys k JOIN site_clan_charters ch ON ch.key_id=k.id AND ch.clan_id=? JOIN site_clan_institutions ci ON ci.clan_id=ch.clan_id AND ci.institution_key='smugglers' JOIN site_company_deeds d ON d.original_key_id=k.id AND d.company_id=? JOIN site_company_institutions i ON i.company_id=d.company_id AND i.institution_key='smugglers' JOIN site_clans c ON c.id=ch.clan_id AND c.active=1 JOIN corrino_companies co ON co.id=d.company_id AND co.status='active' WHERE k.account_id=? AND k.key_type='staff-parent-link' AND k.scope_id=? AND k.expires_at IS NULL AND ch.charter_kind='royal' AND d.charter_kind='royal' AND k.target_id=? AND c.owner_id=? AND ci.custodian_user_id=? AND d.owner_account_id=?"+(lock?' FOR UPDATE':''),[SMUGGLER_CLAN_ID,SMUGGLER_COMPANY_ID,STAFF_OFFICE_ACCOUNT_ID,scope,SMUGGLER_CLAN_ID,identity.id,identity.id,identity.id]);
|
||||
if(!row||row.used_at===null||row.revoked_at!==null)return null;return {keyId:row.id,custodianId:identity.id,clanId:SMUGGLER_CLAN_ID,companyId:SMUGGLER_COMPANY_ID,hidden:true,protected:true};
|
||||
}
|
||||
export function createClandestineInstitutions(db,keys,{authorizeOperator,clock=Date.now}={}){
|
||||
if(typeof authorizeOperator!=='function')throw TypeError('Current institution operator required');
|
||||
return Object.freeze({async provision(actor){
|
||||
const verify=async tx=>{if(await authorizeOperator(actor,tx)!==true)throw Error('Current institution operator required');const identity=await custodian(tx,keys);const key=await tx.first('SELECT revoked_at FROM organisation_keys WHERE id=? FOR UPDATE',[identity.keyId]);if(!key||key.revoked_at!==null)throw Error('System custodian changed');return identity;};
|
||||
const grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-parent-link',scopeId:scope,authorize:verify}),key=(await keys.list(STAFF_OFFICE_ACCOUNT_ID)).find(k=>k.id===grant.id);
|
||||
let applied=false;if(key?.status==='available'){const result=await keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-parent-link',code:key.code,targetId:SMUGGLER_CLAN_ID,requestId,apply:async tx=>{
|
||||
const identity=await verify(tx),now=clock();
|
||||
if(await tx.first("SELECT id FROM site_clans WHERE id=? OR name_key='the unmarked caravan' OR tag='SMUG' FOR UPDATE",[SMUGGLER_CLAN_ID])||await tx.first("SELECT id FROM corrino_companies WHERE id=? OR slug='tuek-hidden-exchange' FOR UPDATE",[SMUGGLER_COMPANY_ID]))throw Error('Reserved institution identity collision; nothing was adopted');
|
||||
if(await tx.first('SELECT clan_id FROM site_clan_members WHERE user_id=? FOR UPDATE',[identity.id]))throw Error('System custodian already has a primary clan');
|
||||
await tx.query("INSERT INTO site_clans(id,name,name_key,tag,description,owner_id,active,version,created_at,updated_at,home_world) VALUES(?,'The Unmarked Caravan','the unmarked caravan','SMUG','Protected hidden smuggler institution. Secondary quest affiliations confer no ordinary clan authority.',?,1,1,?,?,'arrakduin')",[SMUGGLER_CLAN_ID,identity.id,now,now]);
|
||||
await tx.query("INSERT INTO site_clan_members(user_id,minecraft_uuid,clan_id,clan_role,joined_at) VALUES(?,?,?,'owner',?)",[identity.id,identity.minecraftUuid,SMUGGLER_CLAN_ID,now]);
|
||||
await tx.query('INSERT INTO site_clan_deeds(clan_id,updated_at) VALUES(?,?)',[SMUGGLER_CLAN_ID,now]);
|
||||
await tx.query("INSERT INTO site_clan_charters(clan_id,original_account_id,key_id,charter_kind,created_at) VALUES(?,?,?,'royal',?)",[SMUGGLER_CLAN_ID,identity.id,grant.id,now]);
|
||||
await tx.query("INSERT INTO site_clan_institutions(clan_id,institution_key,member_limit,franchise_terms,recruitment_open,custodian_user_id) VALUES(?,'smugglers',5,5,0,?)",[SMUGGLER_CLAN_ID,identity.id]);
|
||||
await tx.query("INSERT INTO corrino_companies(id,slug,name,description,founded_by,ceo_account_id,status,created_at,updated_at) VALUES(?,'tuek-hidden-exchange','Tuek Hidden Exchange','Protected hidden smuggler company. Secondary affiliations grant no PvP or bank authority.',?,NULL,'active',?,?)",[SMUGGLER_COMPANY_ID,identity.id,now,now]);
|
||||
await recordInitialCompanyDeed(tx,{id:SMUGGLER_COMPANY_ID,founded_by:identity.id,created_at:now},now);
|
||||
await tx.query("UPDATE site_company_deeds SET charter_kind='royal',original_key_id=? WHERE company_id=?",[grant.id,SMUGGLER_COMPANY_ID]);
|
||||
await tx.query("INSERT INTO site_company_institutions(company_id,institution_key) VALUES(?,'smugglers')",[SMUGGLER_COMPANY_ID]);
|
||||
await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),actor.id,'hidden-smuggler-institutions',JSON.stringify({keyId:grant.id,clanId:SMUGGLER_CLAN_ID,companyId:SMUGGLER_COMPANY_ID,systemCustodian:identity.id,ticketId:412,ordinaryAccountsMoved:0}),now]);
|
||||
}});applied=!result.replayed;}
|
||||
const current=await readSmugglerInstitutions(db,keys);if(!current||current.keyId!==grant.id)throw Error('Protected institution charter requires review');return {...current,created:applied};
|
||||
}});
|
||||
}
|
||||
export async function grantSmugglerAffiliations(tx,keys,actor,{clock=Date.now}={}){
|
||||
const institutions=await readSmugglerInstitutions(tx,keys,{lock:true});if(!institutions)throw Error('Protected smuggler institutions are unavailable');
|
||||
const quest=await first(tx,"SELECT s.key_id FROM jarvis_pol_quest_states s JOIN organisation_keys k ON k.id=s.key_id WHERE s.account_id=? AND s.definition_id='POL-SMUGGLERS-01' AND k.key_type='quest' AND k.account_id=s.account_id AND k.scope_id=CONCAT(s.season_id,':POL_POL-SMUGGLERS-01') AND k.revoked_at IS NULL FOR UPDATE",[actor.id]);if(!quest)throw Error('Bound smuggler introduction quest required');
|
||||
for(const [kind,id]of [['clan',SMUGGLER_CLAN_ID],['company',SMUGGLER_COMPANY_ID]])await tx.query('INSERT INTO jarvis_secondary_affiliations(account_id,organisation_kind,organisation_id,source_key_id,joined_at) VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE account_id=VALUES(account_id)',[actor.id,kind,id,quest.key_id,clock()]);
|
||||
return {sourceKeyId:quest.key_id,primaryAffiliationChanged:false};
|
||||
}
|
||||
export async function readSmugglerAffiliations(db,keys,accountId){
|
||||
const rows=await db.query("SELECT a.organisation_kind,a.organisation_id,a.joined_at FROM jarvis_secondary_affiliations a JOIN organisation_keys k ON k.id=a.source_key_id AND k.account_id=a.account_id AND k.key_type='quest' AND k.used_at IS NOT NULL AND k.revoked_at IS NULL JOIN jarvis_pol_quest_claims q ON q.key_id=k.id AND q.account_id=a.account_id JOIN jarvis_pol_quest_states s ON s.key_id=k.id AND s.definition_id='POL-SMUGGLERS-01' WHERE a.account_id=? AND ((a.organisation_kind='clan' AND a.organisation_id=?) OR (a.organisation_kind='company' AND a.organisation_id=?)) ORDER BY a.organisation_kind",[accountId,SMUGGLER_CLAN_ID,SMUGGLER_COMPANY_ID]);
|
||||
if(!rows.length||!await readSmugglerInstitutions(db,keys))return [];
|
||||
return rows.map(r=>({kind:r.organisation_kind,id:r.organisation_id,secondary:true,hidden:true,capabilities:['quest.smuggling'],pvp:false,bankManagement:false,joinedAt:Number(r.joined_at)}));
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
import {isClandestineInstitution} from './clandestine-identity.mjs';
|
||||
import {createCompanySubsidiary} from './company-subsidiaries.mjs';
|
||||
import {randomUUID,createHash} from 'node:crypto';
|
||||
import {identity} from './auth.mjs';
|
||||
|
|
@ -14,7 +15,7 @@ export function createCompanyDeedRoute(db,{keys=null,origin='https://cp.dunereal
|
|||
if(!(await access(user)).nodes.includes('web.menu.game'))return reply({message:'Game account access required.'},403);
|
||||
if(request.method==='POST'&&request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403);
|
||||
try{
|
||||
const id=match[1];if(id&&!companyId(id))throw fault('Choose a valid company.',400);
|
||||
const id=match[1];if(isClandestineInstitution('company',id))throw fault('Company deed not found.',404);if(id&&!companyId(id))throw fault('Choose a valid company.',400);
|
||||
if(request.method==='GET'){if(!id)throw fault('Choose a company.',400);return reply(companyDeedView(await readCompanyDeed(db,id),user.id));}
|
||||
const raw=await request.text();if(raw.length>6000)throw fault('Request too large.',413);let body;try{body=JSON.parse(raw);}catch{throw fault('Invalid request.',400);}
|
||||
if(!body||typeof body!=='object'||Array.isArray(body)||body.confirmed!==true)throw fault('Review and confirm the company instruction.',400);
|
||||
|
|
|
|||
|
|
@ -1,51 +1,53 @@
|
|||
// Corrino Group company registry foundation. No shares or financial transfers occur here.
|
||||
import {isClandestineInstitution} from './clandestine-identity.mjs';
|
||||
// Corrino Group company registry foundation. No shares or financial transfers occur here.
|
||||
import {recordInitialCompanyDeed} from './company-deeds.mjs';
|
||||
import {clanMemberLimit} from './clan-membership-policy.mjs';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
export const companyRegistrySchema=Object.freeze([
|
||||
`CREATE TABLE IF NOT EXISTS corrino_companies (id CHAR(36) PRIMARY KEY, slug VARCHAR(64) NOT NULL UNIQUE, name VARCHAR(120) NOT NULL, description VARCHAR(1000) NOT NULL DEFAULT '', founded_by CHAR(36) NOT NULL, ceo_account_id CHAR(36) NULL, status VARCHAR(24) NOT NULL DEFAULT 'pending', created_at BIGINT NOT NULL, updated_at BIGINT NOT NULL, INDEX company_status(status,name)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
||||
`CREATE TABLE IF NOT EXISTS corrino_company_events (id CHAR(36) PRIMARY KEY, company_id CHAR(36) NOT NULL, action VARCHAR(32) NOT NULL, actor_id CHAR(36) NOT NULL, details_json TEXT NULL, created_at BIGINT NOT NULL, INDEX company_event_history(company_id,created_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
|
||||
]);
|
||||
export async function initializeCompanyRegistry(db){for(const sql of companyRegistrySchema)await db.prepare(sql).run();}
|
||||
export function validateCompanyInput({slug,name,description=''}){
|
||||
if(typeof slug!=='string'||!/^[a-z][a-z0-9-]{2,63}$/.test(slug)||typeof name!=='string'||!name.trim()||name.length>120||typeof description!=='string'||description.length>1000)throw new TypeError('Invalid company details');
|
||||
return {slug,name:name.trim(),description:description.trim()};
|
||||
}
|
||||
// Caller must verify the actor has explicit company-management permission.
|
||||
const accountIdPattern=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
// Transactional checks prevent registering nonexistent founders and stale CEO changes.
|
||||
export async function registerCompany(db,{slug,name,description='',founderId,actorId,authorized=false}){
|
||||
if(authorized!==true||![founderId,actorId].every(v=>typeof v==='string'&&accountIdPattern.test(v)))throw new Error('Company registration not authorized');
|
||||
if(typeof db.transaction!=='function')throw new Error('Transactional database required');
|
||||
const input=validateCompanyInput({slug,name,description}),id=randomUUID(),now=Date.now();
|
||||
return db.transaction(async tx=>{
|
||||
const founder=await tx.first('SELECT id FROM site_accounts WHERE id=?',[founderId]);
|
||||
if(!founder)throw new Error('Founder account not found');
|
||||
await tx.query('INSERT INTO corrino_companies(id,slug,name,description,founded_by,status,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?)',[id,input.slug,input.name,input.description,founderId,'pending',now,now]);
|
||||
import {randomUUID} from 'node:crypto';
|
||||
export const companyRegistrySchema=Object.freeze([
|
||||
`CREATE TABLE IF NOT EXISTS corrino_companies (id CHAR(36) PRIMARY KEY, slug VARCHAR(64) NOT NULL UNIQUE, name VARCHAR(120) NOT NULL, description VARCHAR(1000) NOT NULL DEFAULT '', founded_by CHAR(36) NOT NULL, ceo_account_id CHAR(36) NULL, status VARCHAR(24) NOT NULL DEFAULT 'pending', created_at BIGINT NOT NULL, updated_at BIGINT NOT NULL, INDEX company_status(status,name)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
||||
`CREATE TABLE IF NOT EXISTS corrino_company_events (id CHAR(36) PRIMARY KEY, company_id CHAR(36) NOT NULL, action VARCHAR(32) NOT NULL, actor_id CHAR(36) NOT NULL, details_json TEXT NULL, created_at BIGINT NOT NULL, INDEX company_event_history(company_id,created_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
|
||||
]);
|
||||
export async function initializeCompanyRegistry(db){for(const sql of companyRegistrySchema)await db.prepare(sql).run();}
|
||||
export function validateCompanyInput({slug,name,description=''}){
|
||||
if(typeof slug!=='string'||!/^[a-z][a-z0-9-]{2,63}$/.test(slug)||typeof name!=='string'||!name.trim()||name.length>120||typeof description!=='string'||description.length>1000)throw new TypeError('Invalid company details');
|
||||
return {slug,name:name.trim(),description:description.trim()};
|
||||
}
|
||||
// Caller must verify the actor has explicit company-management permission.
|
||||
const accountIdPattern=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
// Transactional checks prevent registering nonexistent founders and stale CEO changes.
|
||||
export async function registerCompany(db,{slug,name,description='',founderId,actorId,authorized=false}){
|
||||
if(authorized!==true||![founderId,actorId].every(v=>typeof v==='string'&&accountIdPattern.test(v)))throw new Error('Company registration not authorized');
|
||||
if(typeof db.transaction!=='function')throw new Error('Transactional database required');
|
||||
const input=validateCompanyInput({slug,name,description}),id=randomUUID(),now=Date.now();
|
||||
return db.transaction(async tx=>{
|
||||
const founder=await tx.first('SELECT id FROM site_accounts WHERE id=?',[founderId]);
|
||||
if(!founder)throw new Error('Founder account not found');
|
||||
await tx.query('INSERT INTO corrino_companies(id,slug,name,description,founded_by,status,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?)',[id,input.slug,input.name,input.description,founderId,'pending',now,now]);
|
||||
if(db.companyDeedsEnabled)await recordInitialCompanyDeed(tx,{id,founded_by:founderId},now);
|
||||
await tx.query('INSERT INTO corrino_company_events(id,company_id,action,actor_id,details_json,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),id,'register',actorId,JSON.stringify({founderId}),now]);
|
||||
return {id,status:'pending'};
|
||||
});
|
||||
}
|
||||
export async function appointCompanyCeo(db,{companyId,ceoId,actorId,authorized=false}){
|
||||
if(authorized!==true||![companyId,ceoId,actorId].every(v=>typeof v==='string'&&accountIdPattern.test(v)))throw new Error('CEO appointment not authorized');
|
||||
if(typeof db.transaction!=='function')throw new Error('Transactional database required');
|
||||
return db.transaction(async tx=>{
|
||||
const company=await tx.first('SELECT id,ceo_account_id FROM corrino_companies WHERE id=? FOR UPDATE',[companyId]);
|
||||
if(!company)throw new Error('Company not found');
|
||||
const account=await tx.first('SELECT id FROM site_accounts WHERE id=?',[ceoId]);
|
||||
if(!account)throw new Error('CEO account not found');
|
||||
if(company.ceo_account_id===ceoId)return {companyId,ceoId,changed:false};
|
||||
if(db.companyDeedsEnabled){
|
||||
const deed=await tx.first('SELECT charter_kind FROM site_company_deeds WHERE company_id=? FOR UPDATE',[companyId]);if(!deed)throw new Error('Company deed not found');
|
||||
const count=await tx.first('SELECT COUNT(*) total FROM site_company_members WHERE company_id=?',[companyId]),member=await tx.first('SELECT user_id FROM site_company_members WHERE company_id=? AND user_id=?',[companyId,ceoId]);
|
||||
if(Number(count.total)+(member?0:1)>clanMemberLimit(deed.charter_kind))throw new TypeError('The CEO must fit within the company membership limit.');
|
||||
}
|
||||
const now=Date.now();
|
||||
await tx.query('UPDATE corrino_companies SET ceo_account_id=?,updated_at=? WHERE id=?',[ceoId,now,companyId]);
|
||||
if(db.companyDeedsEnabled)await tx.query('UPDATE site_company_deeds SET version=version+1,updated_at=? WHERE company_id=?',[now,companyId]);
|
||||
await tx.query('INSERT INTO corrino_company_events(id,company_id,action,actor_id,details_json,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),companyId,'appoint-ceo',actorId,JSON.stringify({ceoId,previousCeoId:company.ceo_account_id||null}),now]);
|
||||
return {companyId,ceoId,changed:true};
|
||||
});
|
||||
}
|
||||
export async function listPublicCompanies(db){const {results=[]}=await db.prepare("SELECT c.id,c.slug,c.name,c.description,a.username AS ceo FROM corrino_companies c LEFT JOIN site_accounts a ON a.id=c.ceo_account_id WHERE c.status='active' ORDER BY c.name").all();return results;}
|
||||
await tx.query('INSERT INTO corrino_company_events(id,company_id,action,actor_id,details_json,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),id,'register',actorId,JSON.stringify({founderId}),now]);
|
||||
return {id,status:'pending'};
|
||||
});
|
||||
}
|
||||
export async function appointCompanyCeo(db,{companyId,ceoId,actorId,authorized=false}){
|
||||
if(authorized!==true||![companyId,ceoId,actorId].every(v=>typeof v==='string'&&accountIdPattern.test(v)))throw new Error('CEO appointment not authorized');
|
||||
if(isClandestineInstitution('company',companyId))throw new Error('Protected institution management requires its scoped key');
|
||||
if(typeof db.transaction!=='function')throw new Error('Transactional database required');
|
||||
return db.transaction(async tx=>{
|
||||
const company=await tx.first('SELECT id,ceo_account_id FROM corrino_companies WHERE id=? FOR UPDATE',[companyId]);
|
||||
if(!company)throw new Error('Company not found');
|
||||
const account=await tx.first('SELECT id FROM site_accounts WHERE id=?',[ceoId]);
|
||||
if(!account)throw new Error('CEO account not found');
|
||||
if(company.ceo_account_id===ceoId)return {companyId,ceoId,changed:false};
|
||||
if(db.companyDeedsEnabled){
|
||||
const deed=await tx.first('SELECT charter_kind FROM site_company_deeds WHERE company_id=? FOR UPDATE',[companyId]);if(!deed)throw new Error('Company deed not found');
|
||||
const count=await tx.first('SELECT COUNT(*) total FROM site_company_members WHERE company_id=?',[companyId]),member=await tx.first('SELECT user_id FROM site_company_members WHERE company_id=? AND user_id=?',[companyId,ceoId]);
|
||||
if(Number(count.total)+(member?0:1)>clanMemberLimit(deed.charter_kind))throw new TypeError('The CEO must fit within the company membership limit.');
|
||||
}
|
||||
const now=Date.now();
|
||||
await tx.query('UPDATE corrino_companies SET ceo_account_id=?,updated_at=? WHERE id=?',[ceoId,now,companyId]);
|
||||
if(db.companyDeedsEnabled)await tx.query('UPDATE site_company_deeds SET version=version+1,updated_at=? WHERE company_id=?',[now,companyId]);
|
||||
await tx.query('INSERT INTO corrino_company_events(id,company_id,action,actor_id,details_json,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),companyId,'appoint-ceo',actorId,JSON.stringify({ceoId,previousCeoId:company.ceo_account_id||null}),now]);
|
||||
return {companyId,ceoId,changed:true};
|
||||
});
|
||||
}
|
||||
export async function listPublicCompanies(db){const {results=[]}=await db.prepare("SELECT c.id,c.slug,c.name,c.description,a.username AS ceo FROM corrino_companies c LEFT JOIN site_accounts a ON a.id=c.ceo_account_id WHERE c.status='active' ORDER BY c.name").all();return results.filter(row=>!isClandestineInstitution('company',row.id));}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import {isClandestineInstitution} from './clandestine-identity.mjs';
|
||||
import {passiveOrderRecords} from './political-passive-orders.mjs';
|
||||
import {readGovernmentOffices} from './public-government.mjs';import {identity} from './auth.mjs';
|
||||
export const NETWORK_LAYOUT_SCHEMA=`CREATE TABLE IF NOT EXISTS site_network_layouts(owner_id CHAR(36) PRIMARY KEY,revision INT NOT NULL,positions_json TEXT NOT NULL,updated_at BIGINT NOT NULL)`;
|
||||
|
|
@ -19,8 +20,8 @@ export function projectOwnershipNetwork({clans,companies,owner,offices=[],orders
|
|||
}
|
||||
export async function readOrganisationNetwork(central,{kind,id,ownerId=null,clock=Date.now}){
|
||||
if(kind&&!validKind(kind))throw Error('Choose an ownership network');
|
||||
const clans=(await central.prepare('SELECT c.id,c.name,c.tag,c.owner_id,d.parent_clan_id AS parent_id FROM site_clans c LEFT JOIN site_clan_deeds d ON d.clan_id=c.id WHERE c.active=1 ORDER BY c.id LIMIT 1001').all()).results;
|
||||
const companies=(await central.prepare("SELECT c.id,c.name,c.slug,d.owner_account_id AS owner_id,r.parent_company_id AS parent_id,e.parent_id AS parent_office FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id LEFT JOIN site_company_relations r ON r.company_id=c.id LEFT JOIN jarvis_entity_relations e ON e.child_kind='company' AND e.child_id=c.id AND e.parent_kind='politics' WHERE c.status='active' ORDER BY c.id LIMIT 1001").all()).results;
|
||||
const clans=(await central.prepare('SELECT c.id,c.name,c.tag,c.owner_id,d.parent_clan_id AS parent_id FROM site_clans c LEFT JOIN site_clan_deeds d ON d.clan_id=c.id WHERE c.active=1 ORDER BY c.id LIMIT 1001').all()).results.filter(row=>!isClandestineInstitution('clan',row.id));
|
||||
const companies=(await central.prepare("SELECT c.id,c.name,c.slug,d.owner_account_id AS owner_id,r.parent_company_id AS parent_id,e.parent_id AS parent_office FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id LEFT JOIN site_company_relations r ON r.company_id=c.id LEFT JOIN jarvis_entity_relations e ON e.child_kind='company' AND e.child_id=c.id AND e.parent_kind='politics' WHERE c.status='active' ORDER BY c.id LIMIT 1001").all()).results.filter(row=>!isClandestineInstitution('company',row.id));
|
||||
if(clans.length>1000||companies.length>1000)throw Error('Ownership network needs paginated reconciliation');
|
||||
const relations=(await central.prepare('SELECT child_kind,child_id,parent_kind,parent_id FROM jarvis_entity_relations LIMIT 2001').all()).results;if(relations.length>2000)throw Error('Ownership relations need paginated reconciliation');
|
||||
const graph=networkGraph(clans,companies,relations),offices=await readGovernmentOffices(central,clock());
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import {grantSmugglerAffiliations,readSmugglerAffiliations} from './clandestine-institutions.mjs';
|
||||
import {createPOLProgression} from './progression-pol.mjs';
|
||||
import {createSystemCharacters} from './system-characters.mjs';
|
||||
import {POL_QUEST_BRANCHES,POL_QUEST_DEFINITIONS} from '../control-panel/public/cp-v2/cp-v2-pol-quest-catalogue.mjs';
|
||||
|
|
@ -33,7 +34,8 @@ export function createPOLProgressionRuntime(central,keys,{clock=Date.now,verifyO
|
|||
if(typeof verifyObservation==='function')return true;
|
||||
// polStore already rewrites the fixed table namespace. The evidence tables
|
||||
// and original account/key stores are deliberately outside that rewrite.
|
||||
const proof=await evidence(actor,polStore,{lock:true});return !!proof&&(proof.totals.get(definition.metric)||0)>=definition.target;
|
||||
const proof=await evidence(actor,polStore,{lock:true});if(!proof||(proof.totals.get(definition.metric)||0)<definition.target)return false;
|
||||
if(central.secondaryAffiliationsEnabled&&definition.id==='POL-SMUGGLERS-01')await grantSmugglerAffiliations(polStore,keys,actor,{clock});return true;
|
||||
}
|
||||
};
|
||||
const engine=createPOLProgression(central,keys,adapters);
|
||||
|
|
@ -43,7 +45,7 @@ export function createPOLProgressionRuntime(central,keys,{clock=Date.now,verifyO
|
|||
async claim(actor,input){return (await engineFor(actor,input.definitionId)).engine.claim(actor,input);},
|
||||
async observe(actor,input){return (await engineFor({id:input.accountId})).engine.observe(actor,input);},
|
||||
async list(actor){const current=await engineFor(actor),result=await current.engine.list(actor),proof=typeof verifyObservation==='function'||result.state!=='active'?null:await evidence(actor);
|
||||
return {...result,quests:result.quests.map(q=>{const d=current.definitions.find(d=>d.id===q.id),verified=typeof verifyObservation==='function'||!!proof&&(proof.totals.get(q.metric)||0)>=q.target,derived=!!d.repeatable&&q.revision===null;return {...q,xp:derived?d.xp:q.xp,revision:derived?1:q.revision,rewardConfigured:derived||q.rewardConfigured,canClaim:(q.canClaim||derived&&q.state==='completed')&&verified,...(q.state==='completed'&&!verified?{state:q.keyId?'active':'not-started'}:{})};}),xpType:'pol',branches:[...POL_QUEST_BRANCHES.map(b=>({id:b.id,title:b.title,theme:b.theme})),...(central.polRepeatablesEnabled?[{id:'repeatables',title:'Ongoing duties',theme:'Verified repeating objectives'}]:[])]};
|
||||
return {...result,affiliations:central.secondaryAffiliationsEnabled?await readSmugglerAffiliations(central,keys,actor.id):[],quests:result.quests.map(q=>{const d=current.definitions.find(d=>d.id===q.id),verified=typeof verifyObservation==='function'||!!proof&&(proof.totals.get(q.metric)||0)>=q.target,derived=!!d.repeatable&&q.revision===null;return {...q,xp:derived?d.xp:q.xp,revision:derived?1:q.revision,rewardConfigured:derived||q.rewardConfigured,canClaim:(q.canClaim||derived&&q.state==='completed')&&verified,...(q.state==='completed'&&!verified?{state:q.keyId?'active':'not-started'}:{})};}),xpType:'pol',branches:[...POL_QUEST_BRANCHES.map(b=>({id:b.id,title:b.title,theme:b.theme})),...(central.polRepeatablesEnabled?[{id:'repeatables',title:'Ongoing duties',theme:'Verified repeating objectives'}]:[])]};
|
||||
}
|
||||
});
|
||||
async function collect(actor){
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import {isClandestineInstitution} from './clandestine-identity.mjs';
|
||||
import {readOrganisationNetwork} from './organisation-network.mjs';
|
||||
import {readClanDeed,publicDeed,DeedError} from './clan-deeds.mjs';
|
||||
import {clanTitles} from '../control-panel/public/clan-titles.mjs';
|
||||
|
|
@ -6,7 +7,7 @@ export function createPublicClans(db){return async request=>{
|
|||
const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'no-store','Access-Control-Allow-Origin':'*','X-Content-Type-Options':'nosniff'}}),url=new URL(request.url),tag=url.pathname.split('/').at(-1);
|
||||
if(!['GET','HEAD'].includes(request.method))return reply({message:'Method not allowed.'},405);
|
||||
if(!/^[A-Z0-9]{2,6}$/i.test(tag)||url.search)return reply({message:'Clan not found.'},404);
|
||||
const row=await db.prepare('SELECT id FROM site_clans WHERE tag=? AND active=1').bind(tag.toUpperCase()).first();if(!row)return reply({message:'Clan not found.'},404);
|
||||
const row=await db.prepare('SELECT id FROM site_clans WHERE tag=? AND active=1').bind(tag.toUpperCase()).first();if(!row||isClandestineInstitution('clan',row.id))return reply({message:'Clan not found.'},404);
|
||||
try{const deed=await readClanDeed(db,row.id,{includePolitics:true}),clan=deed.clan,count=await db.prepare('SELECT COUNT(*) total FROM site_clan_members WHERE clan_id=?').bind(clan.id).first();
|
||||
const result={clan:{id:clan.id,name:clan.name,tag:clan.tag,description:clan.description,homeWorld:clan.home_world,createdAt:Number(clan.created_at),colors:deed.colors,memberCount:Number(count.total),emblem:clanEmblemUrl(clan.id)},members:deed.candidates.filter(m=>m.clan_id===clan.id).map(m=>({username:m.username,title:m.clan_role==='owner'?clanTitles({home_world:clan.home_world,charterKind:deed.kind,institution:clan.institution_key}).owner:m.clan_role==='officer'?'Officer':'Member'})),deed:publicDeed(deed),titles:clanTitles({home_world:clan.home_world,charterKind:deed.kind,institution:clan.institution_key})};
|
||||
if(db.networkLayoutsEnabled)try{result.network={state:'available',...(await readOrganisationNetwork(db,{kind:'clan',id:clan.id})).network,source:{kind:'clan',id:clan.id}};}catch{result.network={state:'unavailable'};}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import {isClandestineInstitution,SMUGGLER_COMPANY_SLUG} from './clandestine-identity.mjs';
|
||||
import {passiveOrderRecords} from './political-passive-orders.mjs';
|
||||
import {naibSeats} from './naib-membership.mjs';
|
||||
import {readOrganisationNetwork} from './organisation-network.mjs';
|
||||
|
|
@ -13,10 +14,10 @@ export async function readPublicOrganisations(db,kind,now=Date.now()){
|
|||
if(db.companyDeedsEnabled){
|
||||
const {results=[]}=await db.prepare("SELECT c.id,c.slug,c.name,c.description,c.created_at,d.charter_kind,i.institution_key,a.username AS owner_username,a.display_name AS owner_name,memorial.slug AS owner_memorial,(SELECT COUNT(*) FROM site_company_members m WHERE m.company_id=c.id)+CASE WHEN c.ceo_account_id IS NOT NULL AND EXISTS(SELECT 1 FROM site_accounts x WHERE x.id=c.ceo_account_id) AND NOT EXISTS(SELECT 1 FROM site_company_members m WHERE m.company_id=c.id AND m.user_id=c.ceo_account_id) THEN 1 ELSE 0 END AS member_count FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id LEFT JOIN site_company_institutions i ON i.company_id=c.id LEFT JOIN site_memorials memorial ON memorial.user_id=d.owner_account_id LEFT JOIN site_accounts a ON a.id=d.owner_account_id AND (a.password_hash NOT LIKE '!%' OR memorial.slug IS NOT NULL) WHERE c.status='active' ORDER BY c.name").all();
|
||||
const {results:members=[]}=await db.prepare("SELECT c.id company_id,u.username,u.display_name,CASE WHEN u.id=d.owner_account_id THEN 'Company owner' WHEN u.id=c.ceo_account_id THEN 'Chief Executive' ELSE 'Member' END title FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id JOIN site_accounts u ON (u.id=c.ceo_account_id OR EXISTS(SELECT 1 FROM site_company_members m WHERE m.company_id=c.id AND m.user_id=u.id)) WHERE c.status='active' AND u.password_hash NOT LIKE '!%' ORDER BY c.id,u.username").all();
|
||||
return results.map(({id,...c})=>({...c,id:c.slug,tag:c.slug,member_count:Number(c.member_count),emblem:companyEmblemUrl(id),standing:{basic:'Basic Company',original:'Keyed Company',royal:'Royal Company'}[c.charter_kind]||'Company',realm:'Spacing Guild · Commerce',members:members.filter(m=>m.company_id===id).map(m=>({username:m.username,name:m.display_name||m.username,title:m.title}))}));
|
||||
return results.filter(row=>!isClandestineInstitution('company',row.id)).map(({id,...c})=>({...c,id:c.slug,tag:c.slug,member_count:Number(c.member_count),emblem:companyEmblemUrl(id),standing:{basic:'Basic Company',original:'Keyed Company',royal:'Royal Company'}[c.charter_kind]||'Company',realm:'Spacing Guild · Commerce',members:members.filter(m=>m.company_id===id).map(m=>({username:m.username,name:m.display_name||m.username,title:m.title}))}));
|
||||
}
|
||||
const {results=[]}=await db.prepare("SELECT c.slug,c.name,c.description,c.created_at,a.username AS owner_username,a.display_name AS owner_name FROM corrino_companies c LEFT JOIN site_accounts a ON a.id=c.ceo_account_id AND a.password_hash NOT LIKE '!%' WHERE c.status='active' ORDER BY c.name").all();
|
||||
return results.map(c=>({...c,id:c.slug,tag:c.slug,emblem:assets+'guild.webp',standing:'Registered company',realm:'Spacing Guild · Commerce',member_count:null,members:c.owner_username?[{username:c.owner_username,title:'Chief Executive'}]:[]}));
|
||||
return results.filter(row=>row.slug!==SMUGGLER_COMPANY_SLUG).map(c=>({...c,id:c.slug,tag:c.slug,emblem:assets+'guild.webp',standing:'Registered company',realm:'Spacing Guild · Commerce',member_count:null,members:c.owner_username?[{username:c.owner_username,title:'Chief Executive'}]:[]}));
|
||||
}
|
||||
export function createPublicOrganisations(db,{clock=Date.now,authenticate=r=>identity(r,db)}={}){return async request=>{
|
||||
const url=new URL(request.url),match=/^\/api\/public\/(companies|political-houses)(?:\/([a-z0-9_-]{1,64}))?\/?$/i.exec(url.pathname);
|
||||
|
|
|
|||
26
website/ops/provision-smuggler-institutions.mjs
Normal file
26
website/ops/provision-smuggler-institutions.mjs
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
import {readFileSync,realpathSync} from 'node:fs';import {fileURLToPath} from 'node:url';import {createHash} from 'node:crypto';
|
||||
import mysql from 'mysql2/promise';
|
||||
import {OFFICIAL_ACCOUNT} from '../node/official-account.mjs';
|
||||
import {createClandestineInstitutions,readSmugglerInstitutions} from '../node/clandestine-institutions.mjs';
|
||||
if(process.geteuid?.()!==0)throw Error('A root server operator is required');
|
||||
const args=process.argv.slice(2);if(args.length>1||args.length===1&&args[0]!=='--apply')throw Error('Choose read-only inspection or --apply');
|
||||
const root=realpathSync(fileURLToPath(new URL('..',import.meta.url)));if(root!==realpathSync('/home/dunerealms/apps/dunerealms/current'))throw Error('Run the reviewed current published operator');
|
||||
process.loadEnvFile('/home/dunerealms/.config/dunerealms.env');const e=process.env,config=JSON.parse(readFileSync('/home/dunerealms/.config/integrations.json'));
|
||||
const native=await mysql.createConnection({host:config.host,user:config.username,password:config.password,database:config.database});
|
||||
try{const [rows]=await native.execute('SELECT approval,title FROM dune_dev_tasks WHERE ticket_id=412');if(rows.length!==1||rows[0].title!=='Implement POL XP, House questmasters and clandestine quests using existing J.A.R.V.I.S. flows'||args.length&&rows[0].approval!=='approved')throw Error('Current approved ticket 412 required');}finally{await native.end();}
|
||||
const raw=await mysql.createConnection({host:e.DB_HOST||'127.0.0.1',port:Number(e.DB_PORT||3306),user:e.DB_USER,password:e.DB_PASSWORD,database:e.DB_NAME});
|
||||
const reader={query:async(sql,args=[])=>{if(!/^SELECT /i.test(sql))throw Error('Inspection is read-only');return(await raw.execute(sql,args))[0];}};
|
||||
const authorizeOperator=async(actor,store)=>(await store.query("SELECT p.principal_kind FROM org_control_principals p JOIN site_accounts a ON a.id=p.user_id WHERE p.user_id=? AND p.principal_kind='owner' AND a.username='unimatrix999' AND a.password_hash NOT LIKE '!%'",[actor.id])).length===1;
|
||||
const memberHash=async store=>createHash('sha256').update(JSON.stringify([
|
||||
await store.query("SELECT m.* FROM site_clan_members m JOIN site_accounts a ON a.id=m.user_id WHERE a.role<>'system_account' ORDER BY m.user_id"),
|
||||
await store.query("SELECT m.* FROM site_company_members m JOIN site_accounts a ON a.id=m.user_id WHERE a.role<>'system_account' ORDER BY m.company_id,m.user_id")
|
||||
])).digest('hex');
|
||||
let db;
|
||||
try{
|
||||
const actor={id:OFFICIAL_ACCOUNT.ownerId};if(!await authorizeOperator(actor,reader))throw Error('Current owner principal required');
|
||||
if(!args.length){const current=await readSmugglerInstitutions(reader,null);console.log(JSON.stringify({ticketId:412,readOnly:true,release:root.split('/').at(-1),existing:!!current,...(current||{})}));}
|
||||
else{
|
||||
const before=await memberHash(reader),{openDatabase}=await import('../node/mysql.mjs'),{openOrganisationKeyService}=await import('../node/organisation-key-service.mjs');db=await openDatabase(e);const keys=await openOrganisationKeyService(db,e),result=await createClandestineInstitutions(db,keys,{authorizeOperator}).provision(actor),after=await memberHash(reader);
|
||||
console.log(JSON.stringify({ticketId:412,applied:true,release:root.split('/').at(-1),...result,ordinaryMembershipHashBefore:before,ordinaryMembershipHashAfter:after,ordinaryMembershipsUnchanged:before===after,gameSynchronizationPerformed:false}));
|
||||
}
|
||||
}finally{await db?.close();await raw.end();}
|
||||
|
|
@ -7,6 +7,7 @@ import {createBoardDeedResolver} from '../node/board-deed-source.mjs';
|
|||
import {initializeClanCharters} from '../node/clan-charters.mjs';
|
||||
import {initializePassiveOrders} from '../node/political-passive-orders.mjs';
|
||||
import {POLITICAL_APPOINTMENT_SCHEMA} from '../node/political-appointments.mjs';
|
||||
import {SMUGGLER_COMPANY_ID} from '../node/clandestine-identity.mjs';
|
||||
test('background source observation skips unchanged full deeds and catches roster, rename and archive changes without touching original keys',async()=>{
|
||||
const f=await fixture();try{
|
||||
await f.db.query('ALTER TABLE site_clans ADD COLUMN version INTEGER DEFAULT 1');await f.db.query('ALTER TABLE site_clan_members ADD COLUMN joined_at BIGINT DEFAULT 1');
|
||||
|
|
@ -21,5 +22,7 @@ test('background source observation skips unchanged full deeds and catches roste
|
|||
await f.db.query("UPDATE corrino_companies SET name='Renamed' WHERE id=?",[id]);change=select(await boardSourceObservations(f.db,{clock:f.now}));assert.ok(change);await boards.refresh(change.kind,change.id,change);
|
||||
await f.db.query("UPDATE corrino_companies SET status='archived' WHERE id=?",[id]);change=select(await boardSourceObservations(f.db,{clock:f.now}));assert.ok(change);const archived=await boards.refresh(change.kind,change.id,change);assert.equal(archived.desired.organisation.lifecycle,'archived');assert.equal(archived.keyId,first.keyId);
|
||||
assert.equal(select(await boardSourceObservations(f.db,{clock:f.now})),undefined);
|
||||
await f.db.query("INSERT INTO corrino_companies(id,slug,name,founded_by,status,created_at,updated_at) VALUES(?,'hidden-fixture','Hidden institution',?,'active',1,1)",[SMUGGLER_COMPANY_ID,f.people.Owner.id]);
|
||||
assert.equal((await boardSourceObservations(f.db,{clock:f.now})).some(r=>r.id===SMUGGLER_COMPANY_ID),false,'hidden institutions never trigger ordinary forum publication');
|
||||
}finally{f.db.close();}
|
||||
});
|
||||
|
|
|
|||
31
website/tests/clandestine-institutions.test.mjs
Normal file
31
website/tests/clandestine-institutions.test.mjs
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';
|
||||
import {systemCharacterFixture} from './system-character-fixture.mjs';
|
||||
import {initializeClanDeeds} from '../node/clan-deeds.mjs';import {initializeClanCharters} from '../node/clan-charters.mjs';import {CLAN_INSTITUTION_SCHEMA,institutionalClanDenial} from '../control-panel/clan-institutions.mjs';
|
||||
import {createClandestineInstitutions,initializeSecondaryAffiliations,readSmugglerAffiliations,grantSmugglerAffiliations} from '../node/clandestine-institutions.mjs';
|
||||
import {SMUGGLER_CLAN_ID,SMUGGLER_COMPANY_ID} from '../node/clandestine-identity.mjs';
|
||||
import {initializePOLProgression,ensurePOLProgressionPolicy} from '../node/progression-pol.mjs';import {initializePOLActivityEvents,createPOLActivityEvents} from '../node/pol-activity-events.mjs';import {createPOLProgressionRuntime} from '../node/progression-pol-runtime.mjs';
|
||||
import {listPublicCompanies,appointCompanyCeo} from '../node/company-registry.mjs';import {createPublicOrganisations} from '../node/public-organisations.mjs';import {createPublicClans} from '../node/public-clans.mjs';import {createClans} from '../control-panel/clans.mjs';
|
||||
async function setup(){const f=await systemCharacterFixture();f.db.sqlite.exec("DROP TABLE site_clan_members;DROP TABLE site_clans;CREATE TABLE site_clans(id TEXT PRIMARY KEY,name TEXT,name_key TEXT UNIQUE,tag TEXT UNIQUE,description TEXT DEFAULT '',owner_id TEXT,active INT,version INT DEFAULT1,created_at INT,updated_at INT,home_world TEXT);CREATE TABLE site_clan_members(user_id TEXT PRIMARY KEY,minecraft_uuid TEXT,clan_id TEXT,clan_role TEXT,joined_at INT);".replace('DEFAULT1','DEFAULT 1'));
|
||||
await initializeClanDeeds(f.db,{mysql:false});await initializeClanCharters(f.db,{mysql:false});await f.db.query(CLAN_INSTITUTION_SCHEMA);await initializeSecondaryAffiliations(f.db);await initializePOLProgression(f.db);await ensurePOLProgressionPolicy(f.db,f.keys,{clock:()=>2000});await initializePOLActivityEvents(f.db);f.db.polActivityEventsEnabled=true;await f.characters.provision(f.people.Owner,'esmar_tuek');const service=createClandestineInstitutions(f.db,f.keys,{clock:()=>2000,authorizeOperator:async a=>a.id===f.people.Owner.id}),member=f.people.Member,mc=randomUUID(),normalClan=randomUUID();await f.db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[mc,member.id]);await f.db.query("INSERT INTO site_clans(id,name,name_key,tag,owner_id,active,created_at,home_world) VALUES(?,'Normal clan','normal clan','NORM',?,1,2000,'kaladam')",[normalClan,member.id]);await f.db.query("INSERT INTO site_clan_members VALUES(?,?,?,'owner',2000)",[member.id,mc,normalClan]);f.actor('Member');const normalCompany=await f.create();return {...f,service,member,mc,normalClan,normalCompany};}
|
||||
test('one recorded institution charter creates both protected hidden organisations with a non-login system custodian, once',async()=>{
|
||||
const f=await setup();try{
|
||||
await assert.rejects(f.service.provision(f.member),/operator/);const one=await f.service.provision(f.people.Owner),two=await f.service.provision(f.people.Owner);assert.equal(one.created,true);assert.equal(two.created,false);assert.equal(one.keyId,two.keyId);assert.equal(one.clanId,SMUGGLER_CLAN_ID);assert.equal(one.companyId,SMUGGLER_COMPANY_ID);
|
||||
assert.equal((await f.db.first('SELECT COUNT(*) n FROM site_clan_institutions')).n,1);assert.equal((await f.db.first('SELECT role FROM site_accounts WHERE id=?',[one.custodianId])).role,'system_account');assert.equal((await f.db.first('SELECT clan_id FROM site_clan_members WHERE user_id=?',[f.member.id])).clan_id,f.normalClan);assert.deepEqual((await f.db.query('SELECT company_id FROM site_company_members WHERE user_id=?',[f.member.id])).map(r=>r.company_id),[f.normalCompany]);assert.match(institutionalClanDenial({institution_key:'smugglers'},'archive'),/permanent/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,0);
|
||||
await assert.rejects(appointCompanyCeo(f.db,{companyId:SMUGGLER_COMPANY_ID,ceoId:f.member.id,actorId:f.people.Owner.id,authorized:true}),/scoped key/);
|
||||
}finally{f.db.close();}
|
||||
});
|
||||
test('interrupted composite charter rolls back both institutions and retry uses the same original key',async()=>{
|
||||
const f=await setup();try{
|
||||
f.db.sqlite.exec("CREATE TRIGGER fail_hidden_company BEFORE INSERT ON corrino_companies WHEN NEW.id='"+SMUGGLER_COMPANY_ID+"' BEGIN SELECT RAISE(ABORT,'injected institution failure'); END;");
|
||||
await assert.rejects(f.service.provision(f.people.Owner));assert.equal((await f.db.first('SELECT COUNT(*) n FROM site_clans WHERE id=?',[SMUGGLER_CLAN_ID])).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM corrino_companies WHERE id=?',[SMUGGLER_COMPANY_ID])).n,0);const original=await f.db.first("SELECT id,used_at FROM organisation_keys WHERE scope_id='institution:smugglers:v1'");assert.equal(original.used_at,null);f.db.sqlite.exec('DROP TRIGGER fail_hidden_company');const applied=await f.service.provision(f.people.Owner);assert.equal(applied.keyId,original.id);assert.equal(applied.created,true);assert.equal((await f.db.first("SELECT COUNT(*) n FROM organisation_keys WHERE scope_id='institution:smugglers:v1'")).n,1);
|
||||
}finally{f.db.close();}
|
||||
});
|
||||
test('normal public and CP list/direct routes cannot reveal reserved institutions, even when their IDs or tags are known',async()=>{
|
||||
const f=await setup();try{await f.service.provision(f.people.Owner);assert.deepEqual((await listPublicCompanies(f.db)).map(c=>c.id),[f.normalCompany]);const companies=createPublicOrganisations(f.db,{authenticate:async()=>f.member});const list=await(await companies(new Request('https://www.dunerealms.com/api/public/companies'))).json();assert.ok(!JSON.stringify(list).includes('Tuek Hidden'));assert.equal((await companies(new Request('https://www.dunerealms.com/api/public/companies/tuek-hidden-exchange'))).status,404);assert.equal((await createPublicClans(f.db)(new Request('https://www.dunerealms.com/api/clans/SMUG'))).status,404);assert.equal((await createClans(f.db)(new Request('https://cp.dunerealms.com/api/clans/'+SMUGGLER_CLAN_ID))).status,404);assert.equal((await f.call(SMUGGLER_COMPANY_ID)).status,404);
|
||||
}finally{f.db.close();}
|
||||
});
|
||||
test('verified introduction QST grants secondary affiliations without changing primary clan/company, permissions or money',async()=>{
|
||||
const f=await setup();try{await f.service.provision(f.people.Owner);await assert.rejects(f.db.transaction(tx=>grantSmugglerAffiliations(tx,f.keys,f.member)),/introduction/);const producer={},source=createPOLActivityEvents(f.db,f.keys,{clock:()=>2000,authorizeProducer:async a=>a===producer});await source.record(producer,{eventId:randomUUID(),accountId:f.member.id,minecraftUuid:f.mc,seasonId:'S01',metric:'pol-smuggler-introduction',quantity:1,occurredAt:2000,reference:randomUUID()});const runtime=createPOLProgressionRuntime(f.db,f.keys,{clock:()=>2000});await runtime.collect(f.member);const claim={definitionId:'POL-SMUGGLERS-01',revision:1,requestId:randomUUID()};await runtime.quests.claim(f.member,claim);await runtime.quests.claim(f.member,claim);
|
||||
const affiliations=await readSmugglerAffiliations(f.db,f.keys,f.member.id);assert.equal(affiliations.length,2);assert.ok(affiliations.every(a=>a.secondary&&a.hidden&&!a.pvp&&!a.bankManagement&&a.capabilities.join()==='quest.smuggling'));assert.equal((await f.db.first('SELECT clan_id FROM site_clan_members WHERE user_id=?',[f.member.id])).clan_id,f.normalClan);assert.equal((await f.db.first('SELECT COUNT(*) n FROM site_company_members WHERE user_id=?',[f.member.id])).n,1);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_secondary_affiliations')).n,2);const q=await f.db.first("SELECT key_id FROM jarvis_pol_quest_states WHERE definition_id='POL-SMUGGLERS-01'");await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[q.key_id]);assert.deepEqual(await readSmugglerAffiliations(f.db,f.keys,f.member.id),[]);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_secondary_affiliations')).n,2,'history retained');
|
||||
}finally{f.db.close();}
|
||||
});
|
||||
Loading…
Reference in a new issue

Staff