"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.requestAuth=requestAuth,exports.respondToChallenge=respondToChallenge,exports.onChallenge=onChallenge,exports.generateRegistrationQR=generateRegistrationQR;const shared_1=require("../_deps/shared/index.js"),envelope_js_1=require("./envelope.js"),DEFAULT_POLL_INTERVAL_MS=2e3,DEFAULT_TTL_MS=3e5,MAX_POLL_ITERATIONS=200;async function requestAuth(e,t,r){const a=t.ttlMs??DEFAULT_TTL_MS,n=t.pollIntervalMs??DEFAULT_POLL_INTERVAL_MS,s={recipientDid:t.to,action:t.action,metadata:t.metadata??{},ttlMs:a},o=await(0,envelope_js_1.createSignedEnvelope)({senderDid:e.did,recipientDid:t.to,scope:"xlock:challenge",plaintext:(new TextEncoder).encode(JSON.stringify(s)),privateKey:e.identity.privateKey});if(!o.ok)return(0,shared_1.err)("INVALID_REQUEST");let i,d;try{const e=await fetch(`${r.gatewayUrl}/gateway/auth/challenge`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o.value)});if(429===e.status)return(0,shared_1.err)("RATE_LIMITED");if(!e.ok){const t=await e.json().catch(()=>null),r=t?.error?.code;return(0,shared_1.err)(r??"INVALID_REQUEST")}const t=await e.json();i=t.challengeId,d=t.expiresAt}catch{return(0,shared_1.err)("INVALID_REQUEST")}return pollChallengeStatus(i,d,n,r)}async function respondToChallenge(e,t,r,a){const n={challengeId:t,approved:r,timestamp:Date.now()},s=await(0,envelope_js_1.createSignedEnvelope)({senderDid:e.did,recipientDid:e.did,scope:"xlock:respond",plaintext:(new TextEncoder).encode(JSON.stringify(n)),privateKey:e.identity.privateKey});if(!s.ok)return(0,shared_1.err)("INVALID_REQUEST");try{const e=await fetch(`${a.gatewayUrl}/gateway/auth/respond`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...s.value,challengeId:t,approved:r,responseEnvelope:s.value})});if(!e.ok){const t=await e.json().catch(()=>null),r=t?.error?.code;return(0,shared_1.err)(r??"INVALID_REQUEST")}return(0,shared_1.ok)(void 0)}catch{return(0,shared_1.err)("INVALID_REQUEST")}}function onChallenge(e,t){const r=e=>{try{const r=JSON.parse(e.data);"auth:challenge"===r.type&&r.data&&t(r.data)}catch{}};return e.addEventListener("message",r),()=>e.removeEventListener("message",r)}function generateRegistrationQR(e){const t=new URLSearchParams({app:e.appName,did:e.appDid,registry:e.registryUrl,callback:e.callbackUrl});return e.appIcon&&t.set("icon",e.appIcon),`xlock://register?${t.toString()}`}async function pollChallengeStatus(e,t,r,a){for(let n=0;n<200;n++){if(Date.now()>t)return(0,shared_1.err)("CHALLENGE_EXPIRED");await sleep(r);try{const t=await fetch(`${a.gatewayUrl}/gateway/auth/status/${e}`,{headers:{Authorization:`Bearer ${a.accessToken}`}});if(!t.ok){if(404===t.status)return(0,shared_1.err)("CHALLENGE_NOT_FOUND");continue}const r=await t.json();if("approved"===r.status)return(0,shared_1.ok)({challengeId:r.challengeId,approved:!0,respondedAt:r.respondedAt,envelope:r.envelope});if("denied"===r.status)return(0,shared_1.ok)({challengeId:r.challengeId,approved:!1,respondedAt:r.respondedAt});if("expired"===r.status)return(0,shared_1.err)("CHALLENGE_EXPIRED")}catch{}}return(0,shared_1.err)("CHALLENGE_TIMEOUT")}function sleep(e){return new Promise(t=>setTimeout(t,e))}