import{ok,err}from"./_deps/shared/index.js";import{toBase64}from"./crypto-utils.js";export async function signVaultRequest(t,e,n){const r=Date.now(),a=generateNonce(),o=JSON.stringify(n),c=`POST\n${e}\n${r}\n${a}\n${await hashString(o)}`;let i;try{const e=(new TextEncoder).encode(c);i=await crypto.subtle.sign({name:"Ed25519"},t.privateKey,e)}catch{return err("SIGN_FAILED")}return ok({signature:toBase64(new Uint8Array(i)),timestamp:r,nonce:a})}function generateNonce(){if("undefined"!=typeof crypto&&crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(16);crypto.getRandomValues(t),t[6]=15&t[6]|64,t[8]=63&t[8]|128;const e=Array.from(t).map(t=>t.toString(16).padStart(2,"0")).join("");return[e.slice(0,8),e.slice(8,12),e.slice(12,16),e.slice(16,20),e.slice(20,32)].join("-")}async function hashString(t){const e=(new TextEncoder).encode(t),n=await crypto.subtle.digest("SHA-256",e);return toBase64(new Uint8Array(n))}export async function verifyVaultRequest(t,e,n,r,a,o,c){const i=Date.now();if(Math.abs(i-o)>3e5)return!1;const s=`POST\n${n}\n${o}\n${c}\n${await hashString(r)}`;let y;try{const t=new ArrayBuffer(e.byteLength);new Uint8Array(t).set(e),y=await crypto.subtle.importKey("raw",t,{name:"Ed25519"},!1,["verify"])}catch{return!1}try{const t=(new TextEncoder).encode(s),e=Uint8Array.from(atob(a),t=>t.charCodeAt(0));return await crypto.subtle.verify({name:"Ed25519"},y,e,t)}catch{return!1}}