"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createSubscriptionProof=createSubscriptionProof,exports.verifySubscriptionProof=verifySubscriptionProof,exports.resumeSubscription=resumeSubscription,exports.hashBloomFilter=hashBloomFilter;const shared_1=require("../_deps/shared/index.js"),identity_js_1=require("./identity.js");async function sha256Hash(e){try{const r=new Uint8Array(e),t=await crypto.subtle.digest("SHA-256",r),i=Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("");return(0,shared_1.ok)(i)}catch{return(0,shared_1.err)("HASH_FAILED")}}function serializeForSigning(e){const r=`${e.type}|${e.version}|${e.peer_did}|${e.bloom_filter_hash}|${e.asserted_at}|${e.expires_at}`;return(new TextEncoder).encode(r)}function toBase64(e){return"undefined"!=typeof Buffer?Buffer.from(e).toString("base64"):globalThis.btoa(String.fromCharCode(...e))}function fromBase64(e){if("undefined"!=typeof Buffer)return new Uint8Array(Buffer.from(e,"base64"));const r=globalThis.atob(e),t=new Uint8Array(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}async function createSubscriptionProof(e,r,t,i){const o=Date.now(),s={type:"SubscriptionProof",version:"1.0",peer_did:e,bloom_filter_hash:r,asserted_at:o,expires_at:i??o+2592e6},n=serializeForSigning(s),a=await(0,identity_js_1.signMlDsa65)(t,n);if(!a.ok)return(0,shared_1.err)("SIGNATURE_VERIFICATION_FAILED");const _=a.value;if(_.length!==identity_js_1.ML_DSA65_SIG_BYTES)return(0,shared_1.err)("SIGNATURE_VERIFICATION_FAILED");const u={...s,peer_signature_algorithm:"ML-DSA-65",peer_signature:toBase64(_)};return(0,shared_1.ok)(u)}async function verifySubscriptionProof(e,r){if("1.0"!==e.version||"SubscriptionProof"!==e.type)return(0,shared_1.ok)(!1);if(Date.now()>e.expires_at)return(0,shared_1.err)("EXPIRED");if("ML-DSA-65"!==e.peer_signature_algorithm)return(0,shared_1.ok)(!1);let t;try{t=fromBase64(e.peer_signature)}catch{return(0,shared_1.ok)(!1)}if(t.length!==identity_js_1.ML_DSA65_SIG_BYTES)return(0,shared_1.ok)(!1);const i=serializeForSigning({type:e.type,version:e.version,peer_did:e.peer_did,bloom_filter_hash:e.bloom_filter_hash,asserted_at:e.asserted_at,expires_at:e.expires_at}),o=await(0,identity_js_1.verifyMlDsa65)(r,t,i);return o.ok?(0,shared_1.ok)(o.value):(0,shared_1.err)("SIGNATURE_VERIFICATION_FAILED")}async function resumeSubscription(e,r){try{const t=r.replace(/\/$/,"");return(await fetch(`${t}/trust/resume`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).ok?(0,shared_1.ok)(void 0):(0,shared_1.err)("NETWORK_ERROR")}catch{return(0,shared_1.err)("NETWORK_ERROR")}}async function hashBloomFilter(e){return sha256Hash(e)}