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