import{ok,err}from"./_deps/shared/index.js";import{InviteService}from"./invite.js";import{HttpTrustRegistry,MemoryTrustRegistry}from"./trust-registry.js";import{fromBase64}from"./crypto-utils.js";import{importPublicKey}from"./identity.js";export var AutoAcceptErrorCode;!function(e){e.NO_INVITE_CODE="AUTO_ACCEPT_NO_INVITE_CODE",e.DISABLED="AUTO_ACCEPT_DISABLED",e.INVITE_FAILED="AUTO_ACCEPT_INVITE_FAILED",e.REGISTRY_SETUP_FAILED="AUTO_ACCEPT_REGISTRY_SETUP_FAILED"}(AutoAcceptErrorCode||(AutoAcceptErrorCode={}));export async function autoAcceptInvite(e,r){if(!(e.enabled??getEnvFlag("XBIND_AUTO_ACCEPT",!0)))return err({code:AutoAcceptErrorCode.DISABLED,message:"Auto-accept is disabled",hint:"Set XBIND_AUTO_ACCEPT=true or pass { enabled: true } in config"});const t=e.inviteCode??getEnv("XBIND_INVITE_CODE");if(!t)return err({code:AutoAcceptErrorCode.NO_INVITE_CODE,message:"No invite code provided",hint:"Set XBIND_INVITE_CODE environment variable or pass inviteCode in config"});const i=new InviteService({inviteApiUrl:e.inviteApiUrl??getEnv("XBIND_INVITE_API_URL")??"https://xbind.to"}),o=normalizeInviteCode(t),n=await i.get(o);if(!n.ok)return err({code:AutoAcceptErrorCode.INVITE_FAILED,message:`Failed to fetch invite: ${n.error.message}`,hint:n.error.hint,cause:n.error});const s=n.value,c=e.registry??await autoConfigureRegistry(s);try{const e=fromBase64(s.from.publicKey),r=await importPublicKey(e);if(!r.ok)return err({code:AutoAcceptErrorCode.REGISTRY_SETUP_FAILED,message:"Invalid inviter public key",hint:"The invite may be corrupted",cause:r.error});const t=await c.register({did:s.from.did,publicKey:e,name:s.from.name,scopes:s.permissions,x25519PublicKey:s.from.x25519PublicKey?fromBase64(s.from.x25519PublicKey):void 0,mlKemPublicKey:s.from.mlKemPublicKey?fromBase64(s.from.mlKemPublicKey):void 0,mlDsaPublicKey:void 0,xchange:!1});if(!t.ok&&"ALREADY_REGISTERED"!==t.error)return err({code:AutoAcceptErrorCode.REGISTRY_SETUP_FAILED,message:`Failed to add inviter to registry: ${t.error}`,cause:t.error})}catch(e){return err({code:AutoAcceptErrorCode.REGISTRY_SETUP_FAILED,message:"Failed to configure trust registry",cause:e})}return(await i.accept({inviteUrl:o,acceptor:r})).ok,ok({invite:s,from:s.from,registryUrl:extractRegistryUrl(s),registryAutoconfigured:void 0===e.registry})}async function autoConfigureRegistry(e){const r=extractRegistryUrl(e);return r?new HttpTrustRegistry({baseUrl:r}):new MemoryTrustRegistry}function extractRegistryUrl(e){if(e.from.endpoint.includes("/registry")||e.from.endpoint.includes("/trust"))return e.from.endpoint}function normalizeInviteCode(e){if(e.startsWith("http://")||e.startsWith("https://"))return e;return`https://xbind.to/invite/${e.replace(/^XBD-/i,"")}`}function getEnv(e,r){return"undefined"!=typeof process&&void 0!==process.env?process.env[e]??r:r}function getEnvFlag(e,r){const t=getEnv(e);if(void 0===t)return r;const i=t.toLowerCase().trim();return"true"===i||"1"===i||"yes"===i}