function hex(bytes:ArrayBuffer){return[...new Uint8Array(bytes)].map(b=>b.toString(16).padStart(2,"0")).join("")}
function equal(a:string,b:string){if(a.length!==b.length)return false;let x=0;for(let i=0;i<a.length;i++)x|=a.charCodeAt(i)^b.charCodeAt(i);return x===0}
async function valid(body:string,header:string,secret:string){const parts=header.split(","),t=parts.find(x=>x.startsWith("t="))?.slice(2),signatures=parts.filter(x=>x.startsWith("v1=")).map(x=>x.slice(3));if(!t||Math.abs(Date.now()/1000-Number(t))>300)return false;const key=await crypto.subtle.importKey("raw",new TextEncoder().encode(secret),{name:"HMAC",hash:"SHA-256"},false,["sign"]);const digest=hex(await crypto.subtle.sign("HMAC",key,new TextEncoder().encode(`${t}.${body}`)));return signatures.some(s=>equal(s,digest))}
export async function POST(request:Request){const secret=process.env.STRIPE_WEBHOOK_SECRET,signature=request.headers.get("stripe-signature"),body=await request.text();if(!secret||!signature||!await valid(body,signature,secret))return new Response("Invalid signature",{status:400});const event=JSON.parse(body)as{id:string;type:string};return Response.json({received:true,eventId:event.id,eventType:event.type})}
