import {clanDeedAuthority} from './clan-deeds.mjs'; import {OrganisationKeyError} from './organisation-keys.mjs'; const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v); // Internal issuer; the later creation/transfer handler must revalidate this same mother deed. export async function issueClanSubhouseKey(db,keys,user,{parentClanId,requestId}){ if(!uuid(parentClanId)||!uuid(requestId)||!uuid(user?.id))throw TypeError('Choose a valid mother deed and request'); return keys.issue({accountId:user.id,keyType:'clan-subhouse',scopeId:'parent:'+parentClanId+':'+requestId,authorize:async tx=>{ if(!await tx.first('SELECT id FROM site_clans WHERE id=? AND active=1 FOR UPDATE',[parentClanId]))throw new OrganisationKeyError('Mother clan unavailable'); const reader={prepare(sql){let values=[];return {bind(...args){values=args;return this;},first:()=>tx.first(sql,values),all:async()=>({results:await tx.query(sql,values)})};}}; const authority=await clanDeedAuthority(reader,user.id,parentClanId); if(!authority.canManage||!authority.deed?.keyed||authority.deed.root!==parentClanId||authority.deed.clan.institution_key)throw new OrganisationKeyError('A current Keyed or Royal mother deed is required'); }}); }