MC/website/node/company-deed-route.mjs
2026-11-27 23:43:05 +00:00

46 lines
6.2 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {isClandestineInstitution} from './clandestine-identity.mjs';
import {createCompanySubsidiary} from './company-subsidiaries.mjs';
import {randomUUID,createHash} from 'node:crypto';
import {identity} from './auth.mjs';
import {accessFor} from './permissions.mjs';
import {validateCompanyInput} from './company-registry.mjs';
import {OrganisationKeyError} from './organisation-keys.mjs';
import {companyId,recordInitialCompanyDeed,readCompanyDeed,companyDeedView,upgradeOriginalCompany} from './company-deeds.mjs';
const fault=(message,status=409)=>Object.assign(Error(message),{status});
export function createCompanyDeedRoute(db,{keys=null,origin='https://cp.dunerealms.com',authenticate=r=>identity(r,db),access=u=>accessFor(db,u),clock=Date.now,onCompanyCreated=async()=>{}}={}){return async request=>{
const reply=(value,status=200)=>Response.json(value,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}}),url=new URL(request.url),match=/^\/api\/companies\/deeds(?:\/([a-f0-9-]{36}))?$/i.exec(url.pathname);
if(!match||url.search)return reply({message:'Company deed not found.'},404);
if(!['GET','POST'].includes(request.method))return reply({message:'Method not allowed.'},405);
const user=await authenticate(request);if(!user)return reply({message:'Sign in to open Company CP.'},401);
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(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);
const fresh=await authenticate(request);if(fresh?.id!==user.id||!(await access(fresh)).nodes.includes('web.menu.game'))throw fault('Your session changed.',403);
if(id){
if(body.action==='create-subsidiary'){const result=await createCompanySubsidiary(db,keys,user,id,body,{clock});try{await onCompanyCreated({id:result.companyId,ownerId:user.id});}catch{console.error('Subsidiary mailbox provisioning pending');}return reply(result,result.replayed?200:201);}
if(body.action!=='upgrade'||Object.keys(body).some(k=>!['action','code','version','requestId','confirmed'].includes(k)))throw fault('Unknown company deed instruction.',400);
if(!keys)throw fault('Company founding codes are temporarily unavailable.',503);
const result=await upgradeOriginalCompany(db,keys,user,{...body,companyId:id});return reply({ok:true,companyId:id,charter:'original',replayed:result.replayed});
}
if(body.action!=='create'||!companyId(body.requestId)||Object.keys(body).some(k=>!['action','slug','name','description','requestId','confirmed'].includes(k)))throw fault('Choose a name and a public company address.',400);
let input;try{input=validateCompanyInput(body);}catch{throw fault('Use a public address of 3–64 lowercase letters, numbers or hyphens, a name up to 120 characters and a description up to 1,000.',400);}
if(/[\x00-\x1f\x7f]/.test(input.name)||/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(input.description))throw fault('Remove control characters from the company details.',400);
const fingerprint=createHash('sha256').update(JSON.stringify(input)).digest('hex');
const response=await db.transaction(async tx=>{
const actor=await tx.first("SELECT id FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%' FOR UPDATE",[user.id]);if(!actor)throw fault('Account access changed.',403);
const prior=await tx.first('SELECT company_id,actor_id,action,details_json FROM corrino_company_events WHERE id=? FOR UPDATE',[body.requestId]);
if(prior){let details;try{details=JSON.parse(prior.details_json);}catch{}if(prior.actor_id!==user.id||prior.action!=='basic-registration'||details?.fingerprint!==fingerprint)throw fault('This instruction reference was already used.');return reply({ok:true,companyId:prior.company_id,replayed:true});}
if(!await tx.first('SELECT user_id FROM site_game_links WHERE user_id=?',[user.id]))throw fault('Link your Minecraft account before registering a company.');
const existing=await tx.first("SELECT c.id FROM corrino_companies c LEFT JOIN site_company_deeds d ON d.company_id=c.id WHERE c.status IN ('active','pending') AND (d.owner_account_id=? OR (d.company_id IS NULL AND c.founded_by=?) OR c.ceo_account_id=? OR EXISTS(SELECT 1 FROM site_company_members m WHERE m.company_id=c.id AND m.user_id=?)) LIMIT 1",[user.id,user.id,user.id,user.id]);if(existing)throw fault('You already belong to or manage a company. Use its existing workspace.');
const now=clock(),company={id:randomUUID(),founded_by:user.id};
await tx.query("INSERT INTO corrino_companies(id,slug,name,description,founded_by,ceo_account_id,status,created_at,updated_at) VALUES(?,?,?,?,?,NULL,'active',?,?)",[company.id,input.slug,input.name,input.description,user.id,now,now]);
await recordInitialCompanyDeed(tx,company,now);
await tx.query('INSERT INTO corrino_company_events(id,company_id,action,actor_id,details_json,created_at) VALUES(?,?,?,?,?,?)',[body.requestId,company.id,'basic-registration',user.id,JSON.stringify({fingerprint}),now]);return reply({ok:true,companyId:company.id,replayed:false},201);
});
if(response.ok){const result=await response.clone().json();try{await onCompanyCreated({id:result.companyId,ownerId:user.id});}catch{console.error('Company mailbox provisioning pending');}}return response;
}catch(error){if(error instanceof TypeError)return reply({message:error.message},400);if(error instanceof OrganisationKeyError)return reply({message:error.message},409);if(error.code==='ER_DUP_ENTRY')return reply({message:'That public company address is already registered.'},409);return reply({message:error.status?error.message:'The company instruction could not be confirmed.'},error.status||503);}
};}