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