import { ZuploContext, ZuploRequest } from "@zuplo/runtime"; export default async function policy( request: ZuploRequest, context: ZuploContext ) { // Get the API Key const { apiKey } = request.user.data; // Get the body as a string const body = await request.clone().text(); // Sign the body with the key const signature = await signRequestBody(apiKey, body); // Add the header to the request request.headers.set("X-Signature", signature) return request; } async function signRequestBody(secret: string, body: string) { // Encode the secret as a key const key = await crypto.subtle.importKey( "raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"] ); // Encode the body and generate the HMAC signature const signature = await crypto.subtle.sign( "HMAC", key, new TextEncoder().encode(body) ); // Convert the signature to a hex string return Array.from(new Uint8Array(signature)) .map((b) => b.toString(16).padStart(2, "0")) .join(""); }