"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.DEFAULT_SPLIT_CONFIG=void 0,exports.splitForChannel=splitForChannel,exports.splitForChannelWithGroupId=splitForChannelWithGroupId,exports.reconstructFromChannel=reconstructFromChannel;const shared_1=require("../_deps/shared/index.js"),crypto_utils_js_1=require("./crypto-utils.js");async function splitForChannel(r,t=exports.DEFAULT_SPLIT_CONFIG){const{totalShares:e,threshold:s}=t;if(e<2||s<2||s>e)return(0,shared_1.err)("SPLIT_FAILED:INVALID_PARAMS");return splitForChannelWithGroupId(r,t,(0,crypto_utils_js_1.generateUUID)())}async function splitForChannelWithGroupId(r,t,e){const{totalShares:s,threshold:_}=t;if(s<2||_<2||_>s)return(0,shared_1.err)("SPLIT_FAILED:INVALID_PARAMS");let o,a,n;try{const t=(0,crypto_utils_js_1.nextOddPrime)(s)-1,e=(0,crypto_utils_js_1.pkcs7Pad)(r,t),i=await(0,crypto_utils_js_1.generateHMAC)(e);a=i.key,n=i.signature,o=(0,crypto_utils_js_1.splitXorIDA)(e,s,_)}catch{return(0,shared_1.err)("SPLIT_FAILED:CRYPTO_NOT_LOADED")}const i=(0,crypto_utils_js_1.toBase64)(a),c=(0,crypto_utils_js_1.toBase64)(n),u=o.map((r,t)=>({data:(0,crypto_utils_js_1.formatShareHeader)((0,crypto_utils_js_1.toBase64)(r)),index:t,total:s,threshold:_,groupId:e,hmacKey:i,hmacSig:c}));return(0,shared_1.ok)(u)}async function reconstructFromChannel(r){const t=validateShares(r);if(!t.ok)return t;const{k:e,n:s}=t.value;return reconstructValidated(r.slice(0,e),s,e)}function validateShares(r){if(0===r.length)return(0,shared_1.err)("INSUFFICIENT_SHARES");const t=r[0],e=t.threshold,s=t.total;if(r.length<e)return(0,shared_1.err)("INSUFFICIENT_SHARES");const _=new Set;for(const o of r){if(o.groupId!==t.groupId)return(0,shared_1.err)("INCONSISTENT_SHARES");if(o.total!==s||o.threshold!==e)return(0,shared_1.err)("INCONSISTENT_SHARES");if(o.index<0||o.index>=s)return(0,shared_1.err)("INVALID_SHARE_DATA");if(_.has(o.index))return(0,shared_1.err)("INVALID_SHARE_DATA");_.add(o.index)}return(0,shared_1.ok)({k:e,n:s,groupId:t.groupId})}async function reconstructValidated(r,t,e){let s;try{s=r.map(r=>(0,crypto_utils_js_1.fromBase64)((0,crypto_utils_js_1.parseShareHeader)(r.data)))}catch{return(0,shared_1.err)("INVALID_SHARE_DATA:BASE64")}const _=r.map(r=>r.index),o=r[0];let a,n;try{a=(0,crypto_utils_js_1.fromBase64)(o.hmacKey),n=(0,crypto_utils_js_1.fromBase64)(o.hmacSig)}catch{return(0,shared_1.err)("INVALID_SHARE_DATA:HMAC_DECODE")}try{const r=(0,crypto_utils_js_1.reconstructXorIDA)(s,_,t,e);if(!await(0,crypto_utils_js_1.verifyHMAC)(a,r,n))return(0,shared_1.err)("HMAC_VERIFICATION_FAILED");const o=(0,crypto_utils_js_1.nextOddPrime)(t)-1,i=(0,crypto_utils_js_1.pkcs7Unpad)(r,o);return i.ok?(0,shared_1.ok)(i.value):(0,shared_1.err)("UNPAD_FAILED")}catch{return(0,shared_1.err)("SPLIT_FAILED:CRYPTO_NOT_LOADED")}}exports.DEFAULT_SPLIT_CONFIG={totalShares:3,threshold:2};