"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.DEFAULT_BACKUP_CONFIG=void 0,exports.validateBackupConfig=validateBackupConfig,exports.splitKeyWithBackup=splitKeyWithBackup,exports.reconstructKeyFromBackup=reconstructKeyFromBackup;const shared_1=require("../_deps/shared/index.js"),crypto_utils_js_1=require("./crypto-utils.js");function validateBackupConfig(t){return t.threshold<2||t.totalShares<t.threshold||t.totalShares>255?(0,shared_1.err)("INVALID_CONFIG"):(0,shared_1.ok)(void 0)}async function splitKeyWithBackup(t,r=exports.DEFAULT_BACKUP_CONFIG){const e=validateBackupConfig(r);if(!e.ok)return e;if(0===t.length)return(0,shared_1.err)("INVALID_KEY_LENGTH");const s=r.totalShares,_=r.threshold,a=(0,crypto_utils_js_1.nextOddPrime)(s)-1,o=(0,crypto_utils_js_1.pkcs7Pad)(t,a),{key:c,signature:i}=await(0,crypto_utils_js_1.generateHMAC)(o),u=(0,crypto_utils_js_1.toBase64)(c),n=(0,crypto_utils_js_1.toBase64)(i);let l;try{l=(0,crypto_utils_js_1.splitXorIDA)(o,s,_)}catch{return(0,shared_1.err)("SPLIT_FAILED")}const h=l.map((t,r)=>({index:r,data:(0,crypto_utils_js_1.toBase64)(t),total:s,threshold:_,hmacKey:u,hmacSig:n}));return(0,shared_1.ok)(h)}async function reconstructKeyFromBackup(t){if(0===t.length)return(0,shared_1.err)("INSUFFICIENT_SHARES");const r=t[0].threshold,e=t[0].total;if(t.length<r)return(0,shared_1.err)("INSUFFICIENT_SHARES");const s=t.slice(0,r);let _;try{_=s.map(t=>(0,crypto_utils_js_1.fromBase64)(t.data))}catch{return(0,shared_1.err)("INVALID_SHARE_DATA")}const a=s.map(t=>t.index);let o,c,i;try{o=(0,crypto_utils_js_1.reconstructXorIDA)(_,a,e,r)}catch{return(0,shared_1.err)("RECONSTRUCT_FAILED")}try{c=(0,crypto_utils_js_1.fromBase64)(s[0].hmacKey),i=(0,crypto_utils_js_1.fromBase64)(s[0].hmacSig)}catch{return(0,shared_1.err)("INVALID_SHARE_DATA")}if(!await(0,crypto_utils_js_1.verifyHMAC)(c,o,i))return(0,shared_1.err)("HMAC_VERIFICATION_FAILED");const u=(0,crypto_utils_js_1.nextOddPrime)(e)-1,n=(0,crypto_utils_js_1.pkcs7Unpad)(o,u);return n.ok?(0,shared_1.ok)(n.value):(0,shared_1.err)("RECONSTRUCT_FAILED")}exports.DEFAULT_BACKUP_CONFIG={threshold:2,totalShares:3};