UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

15 lines • 22.4 kB
import{r as truncateUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{n as notifyListeners,r as registerListener}from"./listeners-awzYn4LE.mjs";import{a as getRuntimeConfigSnapshot}from"./runtime-snapshot-Bg5K4JNu.mjs";import{C as randomBytes,h as isIrohEndpointKey,k as bytesToHex,n as parseStatement,u as fingerprint}from"./validate-Btv7lFe1.mjs";import{l as prepareCorePluginStateReplacement}from"./plugin-state-store-3WYiJ75o.mjs";import{A as isOwnerDeviceActive,E as activeOwnerDevices,Ht as verifyOwnerStatement,N as nextOwnerExpiry,_ as recordSeen,i as DEFAULT_INACTIVITY_WINDOWS,j as linkClaw,k as isAdmitted,n as submitRedemption,p as nextInactivityDrop,r as submitStatement,t as registerInvite,u as dropInactive}from"./src-BTTzpNjb.mjs";import{o as nextPeopleExpiry}from"./invites-view-Brq3D-4S.mjs";import{c as withSweptInvites,i as createNodeInviteOperations,n as readMemberView,o as resolveReport,r as readOwnerView,s as resolvedInvite}from"./membership-views-Ct2l73jR.mjs";import{isDeepStrictEqual}from"node:util"; //!src/gateway/openclaw-id/binding-check.ts async function verifyBinding(e,t,n,r,i){const a=parseStatement(t,`ServerBinding`);if(!a.ok)return{ok:false,code:`malformed`,detail:a.detail};const o=await verifyOwnerStatement(a.statement,e.anchor,{now:i});if(!o.ok)return{ok:false,code:o.code,detail:o.detail};const s=a.statement.body;if(s.claw_id!==n.claw_id||s.hostname!==n.hostname||s.k_srv!==r.kSrv||s.k_gw!==r.kGw||s.binding_seq!==r.bindingSeq)return{ok:false,code:`target_mismatch`,detail:`binding does not name this claw's keys`};return{ok:true,statement:a.statement}} //!src/gateway/openclaw-id/claw-migration.ts function needsAllowlistUpgrade(e){const t=e;return`revocations`in t||`published_revocations`in t.discovery||t.binding!==null&&`chain`in t.binding||t.authority!==null&&(`revoked`in t.authority||`root_history`in t.authority||`rotation_seen`in t.authority||`frozen`in t.authority||`root_epoch`in t.authority.anchor||Object.values(t.authority.owner_devices).some(e=>e.approved_by===void 0||e.caps===void 0||`chain`in e.cert)||Object.values(t.authority.members).some(e=>e.last_seen===void 0))}function upgradeNodeCollections(e){const t=e.authority;if(!t||t.nodes!==void 0&&t.node_invites!==void 0)return e;return{...e,authority:{...t,nodes:t.nodes??{},node_invites:t.node_invites??{}},discovery:{...e.discovery,publish_pending:true}}}function withoutChain(e){const{chain:t,...n}=e;return n}async function upgradeOwnerDevices(e,t){const n=new Set(e.revoked??[]);const r={};for(const[i,a]of Object.entries(e.owner_devices)){if((a.chain_fps??[]).some(e=>n.has(e)))continue;const o=withoutChain(a.cert);r[i]={cert:o,caps:a.caps??[...o.body.caps],approved_by:a.approved_by??(o.signer===e.anchor.root_pub?`root`:await fingerprint(o.signer)),last_seen:a.last_seen??t}}return r}function upgradeMembers(e,t){return Object.fromEntries(Object.entries(e.members).map(([e,n])=>{const r={};for(const e of n.peer_keys)r[e]=n.last_seen?.[e]??t;return[e,{role:n.role,peer_keys:n.peer_keys,last_seen:r}]}))}async function upgradeToAllowlist(e,t){const n=e;const{revocations:r,authority:i,binding:a,discovery:o,...s}=n;const{published_revocations:c,...l}=n.discovery;let u=null;if(n.authority){const{revoked:e,root_history:r,rotation_seen:i,frozen:a,...o}=n.authority;u={...o,anchor:{root_pub:n.authority.anchor.root_pub},owner_devices:await upgradeOwnerDevices(n.authority,t),members:upgradeMembers(n.authority,t)}}return{...s,authority:u,binding:n.binding?withoutChain(n.binding):null,discovery:n.authority?{...l,publish_pending:true}:l}} //!src/gateway/openclaw-id/claw-store.ts function assertSameClawIdentity(e,t){if(e?.binding!==t.binding||e?.authority?.anchor.root_pub!==t.authority?.anchor.root_pub)throw new Error(`claw identity changed during registration recovery`)}function assertStoredClawText(e,t){if(e!==null&&(typeof e!==`string`||e.length>256))throw new Error(`OpenClaw ID ${t} must be null or at most 256 characters`)}function storedOwnerProfile(e){assertStoredClawText(e.sub,`owner account ID`);return{sub:e.sub,...typeof e.email===`string`?{email:truncateUtf16Safe(e.email,256)}:{},...typeof e.name===`string`?{name:truncateUtf16Safe(e.name,256)}:{}}}function openStore(){return prepareCorePluginStateReplacement({ownerId:`core:openclaw-id`,namespace:`claw`,retention:`retained`})}function clawStoreRows(e){const{authority:t,invite_reports:n,member_approved_at:r,token_bindings:i,...a}=e;let o=null;if(t){const{owner_devices:e,members:n,invites:r,...i}=t;o=i}const s=Object.entries(t?.members??{});const c={};for(let e=32;e<s.length;e+=32)c[`members:${e/32}`]=Object.fromEntries(s.slice(e,e+32));return{current:{...a,v:2,authority:o},"owner-devices":t?.owner_devices??{},members:Object.fromEntries(s.slice(0,32)),...c,invites:t?.invites??{},"invite-reports":n??{},"member-approvals":r??{},"token-bindings":{v:1,bindings:i??[]}}}async function readStoredClaw(){const e=new Map((await openStore().entries()).map(({key:e,value:t})=>[e,t]));const t=e.get(`current`);if(!t)return;if(t.v===1){const n=e.get(`token-bindings`);return n?{...t,token_bindings:n.bindings}:t}const section=t=>{if(!e.has(t))throw new Error(`OpenClaw ID claw storage is incomplete: missing ${t}`);return e.get(t)};return{...t,v:1,authority:t.authority?{...t.authority,owner_devices:section(`owner-devices`),members:Object.assign({},section(`members`),...[...e].filter(([e])=>e.startsWith(`members:`)).map(([,e])=>e)),invites:section(`invites`)}:null,invite_reports:section(`invite-reports`),member_approved_at:section(`member-approvals`),token_bindings:section(`token-bindings`).bindings}}async function writeStoredClaw(e,t){await openStore().replace(new Map(Object.entries(clawStoreRows(e))),t)} //!src/gateway/openclaw-id/member-profiles.ts const canonicalMemberProfiles={async inviteProfiles(){const{readOpenClawIdInviteProfiles:e}=await import(`./user-profile-openclaw-id-DlOlimsL.mjs`);return e()},async link(e){const{linkCanonicalOpenClawIdUserProfile:t}=await import(`./user-profile-openclaw-id-DlOlimsL.mjs`);return t(e)},async save(e){const{ensureCanonicalUserProfileForOpenClawIdIdentity:t}=await import(`./user-profile-openclaw-id-DlOlimsL.mjs`);return t(e)},async read(e){const{readOpenClawIdUserProfiles:t}=await import(`./user-profile-openclaw-id-DlOlimsL.mjs`);return t(e)}};async function retainMemberProfiles(e,t,n){const r=t.authority?.members??{};const i=Object.keys(r);const approval=(e,t)=>e?.member_approved_at&&Object.hasOwn(e.member_approved_at,t)?e.member_approved_at[t]:void 0;const a=Object.entries(t.invite_reports??{});const hasInvite=e=>Object.hasOwn(t.authority?.invites??{},e)||Object.hasOwn(t.authority?.node_invites??{},e);if(!a.some(([t,n])=>!hasInvite(t)||n.resolution===`approved`&&(n.email!==null||n.display_name!==null||n.existingProfile&&e?.invite_reports?.[t]?.resolution!==`approved`))&&i.length===Object.keys(t.member_approved_at??{}).length&&i.every(e=>approval(t,e)!==void 0))return t;const o=/* @__PURE__ */ new Map;const s=Object.entries({...e?.invite_reports,...t.invite_reports});for(const r of i){const i=approval(t,r);const c=i===void 0?approval(e,r):i;const l=Object.hasOwn(e?.authority?.members??{},r);const u=s.filter(([t,n])=>n.account_id===r&&n.resolution===`approved`&&(l&&c===void 0||e?.invite_reports?.[t]?.resolution!==`approved`)).toSorted(([,e],[,t])=>(t.resolved_at??0)-(e.resolved_at??0))[0];const d=u?.[1];if(u&&d?.existingProfile){const e=await n.link({profileId:d.existingProfile.id,accountId:r,email:d.email});if(!e.ok){const t={owner_profile:`The selected profile is the shared owner. The member joined with their OpenClaw ID profile instead.`,profile_changed:`The selected profile was removed or merged. The member joined with their OpenClaw ID profile instead.`,linked_elsewhere:`This OpenClaw ID account already belongs to another profile. The member kept that profile instead.`,profile_linked:`The selected profile is now linked to another OpenClaw ID account. The member joined with their OpenClaw ID profile instead.`};const n=a.findIndex(([e])=>e===u[0]);if(n!==-1)a[n]=[u[0],{...d,existingProfile:{...d.existingProfile,fallbackReason:t[e.code]}}]}}if(c===void 0||d?.existingProfile||d?.email||d?.display_name)await n.save({accountId:r,...d?.display_name?{name:d.display_name}:{},...d?.email?{email:d.email}:{}});const f=Object.hasOwn(e?.authority?.members??{},r)?null:Math.floor(Date.now()/1e3);o.set(r,c===void 0?d?.resolved_at??f:c)}const c=Object.fromEntries(a.filter(([e])=>hasInvite(e)).map(([e,t])=>[e,t.resolution===`approved`?{...t,email:null,display_name:null}:t]));return{...t,member_approved_at:Object.fromEntries(o),...t.invite_reports?{invite_reports:c}:{}}} //!src/gateway/openclaw-id/member-role-change.ts var UndefinedMemberRoleError=class extends Error{constructor(e){super(`The role ${e} is not defined on this claw. Choose another role on the Access page.`)}};function refuseUndefinedMemberRole(e){if(e instanceof UndefinedMemberRoleError)return{ok:false,code:`role_undefined`,detail:e.message};throw e}function assertMemberRoleDefined(e){const t=parseStatement(e,`MembershipChange`);const n=t.ok&&t.statement.body.target.op===`set_role`?t.statement.body.target.role:void 0;if(n!==void 0&&!Object.hasOwn(getRuntimeConfigSnapshot()?.gateway?.roles?.definitions??{},n))throw new UndefinedMemberRoleError(n)}function roleChangeDisconnects(e,t){const n=Object.entries(t.members).flatMap(([t,n])=>{const r=e.members[t];return r&&r.role!==n.role?n.peer_keys:[]});return n.length>0?[{type:`disconnect`,peer_keys:n}]:[]} //!src/gateway/openclaw-id/rebind-operations.ts const nowSeconds$1=()=>Math.floor(Date.now()/1e3);function nextBindingSeq(e){return e.binding.body.binding_seq+1}function linkedRecord(e){if(!e?.authority||!e.binding||!e.hostname)return{ok:false,code:`not_linked`,detail:`this claw is not linked`};return{ok:true,record:{...e,binding:e.binding,authority:e.authority,hostname:e.hostname}}}function replacesBoth(e,t){return e.binding.body.k_srv!==t.kSrv&&e.binding.body.k_gw!==t.kGw}function createRebindOperations(e){const{serialize:t,load:n,commit:r}=e;return{prepareRebind(e){return t(async()=>{const t=linkedRecord(await n());if(!t.ok)return t;const{record:r}=t;if(!replacesBoth(r,e))return{ok:false,code:`target_mismatch`,detail:`a re-bind replaces both keys`};const i=r.binding.body;return{claw_id:r.claw_id,hostname:r.hostname,root_pub:r.authority.anchor.root_pub,k_srv:e.kSrv,k_gw:e.kGw,binding_seq:nextBindingSeq(r),root_epoch:1,current:{k_srv:i.k_srv,k_gw:i.k_gw,binding_seq:i.binding_seq}}})},commitRebind(e,i,a,o){return t(async()=>{if(i!==`local_operator`)return{ok:false,code:`not_local_operator`,detail:`a re-bind needs direct loopback`};const t=linkedRecord(await n());if(!t.ok)return t;const{record:s}=t;if(!replacesBoth(s,a))return{ok:false,code:`target_mismatch`,detail:`a re-bind replaces both keys`};const c=parseStatement(e,`ServerBinding`);if(!c.ok)return{ok:false,code:`malformed`,detail:c.detail};const l=c.statement.body.binding_seq;if(l<nextBindingSeq(s))return{ok:false,code:`rollback`,detail:`binding_seq is not above the stored one`};const u=await verifyBinding(s.authority,e,s,{...a,bindingSeq:l},nowSeconds$1());if(!u.ok)return u;const d=/* @__PURE__ */ new Error(`the re-bind lifetime ended`);const assertCurrent=()=>{if(o&&!o())throw d};try{assertCurrent();await r({...s,binding:u.statement},assertCurrent)}catch(e){if(e===d||e instanceof Error&&e.cause===d)return{ok:false,code:`rebind_cancelled`,detail:d.message};throw e}return{ok:true,status:`applied`,events:[{type:`publish_snapshot`}],bindingSeq:l}})}}} //!src/gateway/openclaw-id/authority.ts const nowSeconds=()=>Math.floor(Date.now()/1e3);function emptyRecord(e){return{v:1,claw_id:e,hostname:null,authority:null,binding:null,discovery:{owner_account_id:null,published_binding_seq:0,published_snapshot_seq:0,mailbox_cursor:null}}}function createOpenClawIdAuthority(e={read:readStoredClaw,write:writeStoredClaw}){const t=e.profiles??canonicalMemberProfiles;let n;let r;let i;const a=/* @__PURE__ */ new Set;let o=Promise.resolve();const readInitial=async()=>{const r=await e.read();if(!r)return;let i=needsAllowlistUpgrade(r)?await upgradeToAllowlist(r,nowSeconds()):r;i=upgradeNodeCollections(i);if(Object.keys(i.authority?.members??{}).some(e=>!Object.hasOwn(i.member_approved_at??{},e)))i=await retainMemberProfiles(r,i,t);if(i!==r)await e.write(i);n=i};const assertReadable=()=>{if(i)throw i};const load=async()=>{assertReadable();r??=readInitial().then(()=>n,e=>{r=void 0;throw e});await r;assertReadable();return n};const serialize=e=>{const t=o.then(e,e);o=t.catch(()=>{});return t};const commit=async(r,o)=>{const s=await retainMemberProfiles(n,r,t);const c=n;o?.();try{await e.write(s,o)}catch(t){i=new Error(`OpenClaw ID storage outcome is uncertain; restart to reload authority`,{cause:t});n=void 0;notifyListeners(a,void 0);let r;try{r=await e.read()}catch{throw i}if(!r||!isDeepStrictEqual(clawStoreRows(r),clawStoreRows(s))){if(isDeepStrictEqual(r&&clawStoreRows(r),c&&clawStoreRows(c))){n=c;i=void 0}throw t}i=void 0}n=s;if(c?.authority!==s.authority||c?.invite_reports!==s.invite_reports||c?.owner_profile!==s.owner_profile||c?.discovery.owner_account_id!==s.discovery.owner_account_id)notifyListeners(a,void 0)};const currentPeer=e=>{if(!isIrohEndpointKey(e))return;const t=n?.authority;const r=nowSeconds();if(!t||!isAdmitted(t,e,r))return;const i=Object.entries(t.owner_devices).find(([,t])=>isOwnerDeviceActive(t,r)&&t.cert.body.peer_keys.includes(e));const a={clawId:t.claw_id,rootPub:t.anchor.root_pub};const o=t.nodes[e];if(o)return{kind:`node`,peerKey:e,authority:{...a,listedSeq:o.listed_seq}};if(i)return{kind:`owner`,peerKey:e,authority:{...a,ownerDevice:i[0],listedSeq:i[1].peer_listed_seq?.[i[1].cert.body.peer_keys.indexOf(e)]??0}};const s=Object.entries(t.members).find(([,t])=>t.peer_keys.includes(e));return s?{kind:`member`,peerKey:e,accountId:s[0],role:s[1].role,authority:{...a,listedSeq:s[1].listed_seq?.[s[1].peer_keys.indexOf(e)]??0}}:void 0};return{load,onPeopleChanged:e=>registerListener(a,e),recordVerifiedAccount(e){return serialize(async()=>{const t=await load()??emptyRecord(bytesToHex(randomBytes(16)));const n=t.discovery.owner_account_id;if(n&&n!==e.sub)return;await commit({...t,owner_profile:storedOwnerProfile(e)})})},async prepareOwnerPeerCheck(e){if(!isIrohEndpointKey(e))return()=>false;await load();return()=>{const t=n?.authority;return Boolean(t&&activeOwnerDevices(t,nowSeconds()).some(t=>t.cert.body.peer_keys.includes(e)))}},memberProfiles:t.read,inviteProfiles:t.inviteProfiles,current(){return n},prepareLink(e){return serialize(async()=>{const t=await load();if(t?.authority)return{ok:false,code:`already_linked`,detail:`this claw is already linked`};const n=t??emptyRecord(bytesToHex(randomBytes(16)));const r=e.hostname;if(n!==t||n.hostname!==r)await commit({...n,hostname:r},e.guard);return{claw_id:n.claw_id,hostname:r,k_srv:e.kSrv,k_gw:e.kGw,binding_seq:1,root_epoch:1}})},commitLink(e,t,n){return serialize(async()=>{if(t!==`local_operator`)return{ok:false,code:`not_local_operator`,detail:`linking needs direct loopback`};const r=await load();if(!r?.hostname)return{ok:false,code:`not_prepared`,detail:`prepare the link first`};if(r.authority)return{ok:false,code:`already_linked`,detail:`this claw is already linked`};const i=linkClaw({claw_id:r.claw_id,root_pub:e.root_pub},t);if(!i.ok)return{ok:false,code:i.code,detail:`linking needs direct loopback`};const a=nowSeconds();const o=await submitStatement(i.state,e.owner_device,{channel:t,now:a});if(!o.ok)return{ok:false,code:o.code,detail:o.detail};const s=await verifyBinding(o.state,e.binding,r,{...n,bindingSeq:1},a);if(!s.ok)return s;await commit({...r,authority:o.state,binding:s.statement},n.guard);return{ok:true,status:`applied`,events:[...o.events,{type:`publish_snapshot`}]}})},submit(e,t){return serialize(async()=>{const n=await load();if(!n?.authority)return{ok:false,code:`not_linked`,detail:`this claw is not linked`};const r=nowSeconds();const{record:i,events:a}=withSweptInvites({...n,authority:n.authority},r);const o=await submitStatement(i.authority,e,{channel:t,now:r});if(!o.ok){if(a.length>0)await commit(i);return{ok:false,code:o.code,detail:o.detail}}assertMemberRoleDefined(e);const s=resolvedInvite(e);await commit({...i,authority:o.state,...s?{invite_reports:resolveReport(i.invite_reports,s.inviteId,s.resolution,r)}:{}});const c=roleChangeDisconnects(i.authority,o.state);return{ok:true,status:o.status,events:[...a,...o.events,...c]}}).catch(refuseUndefinedMemberRole)},registerInvite(e,n){return serialize(async()=>{const r=await load();if(!r?.authority)return{ok:false,code:`not_linked`,detail:`this claw is not linked`};const i=nowSeconds();const{record:a,events:o}=withSweptInvites({...r,authority:r.authority},i);const s=await registerInvite(a.authority,e.cap,e.proofKey,{channel:n,now:i});if(!s.ok){if(o.length>0)await commit(a);return{ok:false,code:s.code,detail:s.detail}}let c=a.invite_reports;if(e.existingProfileId!==void 0){const n=(await t.inviteProfiles()).find(({id:t})=>t===e.existingProfileId);if(!n)return{ok:false,code:`profile_unavailable`,detail:`Choose a personal profile that is not linked to OpenClaw ID, or invite without an existing profile.`};const r=Object.keys(s.state.invites).find(e=>!Object.hasOwn(a.authority.invites,e));c={...c,[r]:{email:null,display_name:null,location_hint:null,existingProfile:n}}}const l={...a,authority:s.state};Object.assign(l,c?{invite_reports:c}:{});await commit(l);return{ok:true,status:s.status,events:[...o,...s.events]}})},...createNodeInviteOperations({serialize,load,commit}),...createRebindOperations({serialize,load,commit}),redeem(e,t){return serialize(async()=>{const n=await load();if(!n?.authority)return{ok:false,code:`not_linked`,detail:`this claw is not linked`};const r=nowSeconds();const{record:i,events:a}=withSweptInvites({...n,authority:n.authority},r);const o=await submitRedemption(i.authority,e,t,r);if(!o.ok||o.state===i.authority){if(a.length>0)await commit(i);return o.ok?{ok:true,status:o.status,events:a}:{ok:false,code:o.code,detail:o.detail}}const s=parseStatement(e,`InviteRedemption`);const display=e=>e?truncateUtf16Safe(e.trim(),256):null;const c={...s.ok?i.invite_reports?.[s.statement.body.invite_id]:{},account_id:t.account_id,email:display(t.email),display_name:display(t.display_name),location_hint:display(t.location_hint)};await commit({...i,authority:o.state,invite_reports:s.ok?{...i.invite_reports,[s.statement.body.invite_id]:c}:i.invite_reports});return{ok:true,status:o.status,events:[...a,...o.events]}})},tokenBinding(e,t){assertReadable();return n?.token_bindings?.find(n=>n.device_id===e&&n.role===t)?.peer_key},bindToken(e,t,n){return serialize(async()=>{const r=await load();if(!r)return;const i=(r.token_bindings??[]).filter(n=>n.device_id!==e||n.role!==t);await commit({...r,token_bindings:[...i,{device_id:e,role:t,peer_key:n,bound_at:nowSeconds()}]})})},tokensBoundTo(e){return(n?.token_bindings??[]).filter(t=>e.includes(t.peer_key)).map(e=>({deviceId:e.device_id,role:e.role,peerKey:e.peer_key}))},async orphanedTokens(){const e=await load();const t=new Set(e?.authority?memberKeys(e.authority):[]);return(e?.token_bindings??[]).filter(e=>!t.has(e.peer_key)).map(e=>({deviceId:e.device_id,role:e.role,peerKey:e.peer_key}))},unbindTokens(e){return serialize(async()=>{const t=await load();const confirmed=t=>e.some(e=>e.deviceId===t.device_id&&e.role===t.role&&e.peerKey===t.peer_key);if(t&&(t.token_bindings??[]).some(confirmed))await commit({...t,token_bindings:(t.token_bindings??[]).filter(e=>!confirmed(e))})})},unbindPeers(e){return serialize(async()=>{const t=await load();const n=(t?.token_bindings??[]).filter(t=>e.includes(t.peer_key));if(t&&n.length>0)await commit({...t,token_bindings:(t.token_bindings??[]).filter(t=>!e.includes(t.peer_key))});return n.map(e=>({deviceId:e.device_id,role:e.role}))})},async memberView(e){const t=await load();const r=await readMemberView(t,currentPeer(e));return n===t?r:void 0},async ownerView(e){const t=await load();const r=await readOwnerView(t,e);return n===t?r:void 0},async resolvePeer(e){await load();return currentPeer(e)},currentPeer,recordSeen(e){return serialize(async()=>{const t=await load();if(!t?.authority||!isIrohEndpointKey(e))return;const n=recordSeen(t.authority,e,nowSeconds());if(n)await commit({...t,authority:n})})},dropInactive(e={}){return serialize(async()=>{const t=await load();const n=t?.authority?dropInactive(t.authority,nowSeconds(),withDefaults(e)):null;if(!t||!n)return[];await commit({...t,authority:n.state});return n.peers})},isCurrentNodeListing(e){const t=currentPeer(e.peerKey);return t?.kind===`node`&&t.authority?.clawId===e.authority.clawId&&t.authority.rootPub===e.authority.rootPub&&t.authority.listedSeq===e.authority.listedSeq},async admittedPeerKeys(){const e=(await load())?.authority;if(!e)return{seq:0,admitted:[]};return{seq:e.seq,admitted:listAdmitted(e,nowSeconds())}},nextPeopleExpiry(){return nextPeopleExpiry(n?.authority,nowSeconds())},async nextOwnerExpiry(e={}){const t=(await load())?.authority;if(!t)return;const n=[nextOwnerExpiry(t,nowSeconds()),nextInactivityDrop(t,withDefaults(e))].filter(e=>e!==null);return n.length>0?Math.min(...n):void 0},async expiredOwnerPeers(){const e=(await load())?.authority;if(!e)return[];const t=nowSeconds();const n=new Set(Object.keys(e.nodes));for(const r of Object.values(e.owner_devices))if(!isOwnerDeviceActive(r,t))r.cert.body.peer_keys.forEach(e=>n.add(e));return[...n].filter(n=>!isAdmitted(e,n,t)).toSorted()},recordDiscovery(e,t){return serialize(async()=>{for(const t of[`owner_account_id`,`mailbox_cursor`])if(Object.hasOwn(e,t))assertStoredClawText(e[t],t);const n=await load();if(t)assertSameClawIdentity(n,t);if(n){const t={...n,discovery:{...n.discovery,...e}};const r=t.discovery.owner_account_id;if(!t.owner_profile||r&&t.owner_profile.sub!==r)delete t.owner_profile;await commit(t)}})}}}function withDefaults(e){return{...DEFAULT_INACTIVITY_WINDOWS,...e}}function memberKeys(e){return/* @__PURE__ */ new Set([...Object.values(e.members).flatMap(e=>e.peer_keys),...Object.values(e.owner_devices).flatMap(e=>e.cert.body.peer_keys),...Object.keys(e.nodes).filter(isIrohEndpointKey)])}function listAdmitted(e,t){return[...memberKeys(e)].filter(n=>isAdmitted(e,n,t)).toSorted()}export{createOpenClawIdAuthority};