import crypto from "crypto";

export function verifySignature(publicKeyBase64, signatureBase64, message) {
  try {
    const publicKeyBuf = Buffer.from(publicKeyBase64, "base64url");
    const signatureBuf = Buffer.from(signatureBase64, "base64url");
    const keyObject = crypto.createPublicKey({
      key: publicKeyBuf,
      format: "der",
      type: "spki",
    });
    return crypto.verify(null, Buffer.from(message, "utf8"), keyObject, signatureBuf);
  } catch (_e) {
    return false;
  }
}

/** Build message that client must sign: method + path + timestamp + bodyHash */
/**
 * @param {string} method
 * @param {string} path
 * @param {string} timestamp
 * @param {string} bodyHash
 * @returns {string}
 */
export function buildSignMessage(method, path, timestamp, bodyHash) {
  return `${method}\n${path}\n${timestamp}\n${bodyHash}`;
}

/**
 * @param {string} body
 * @returns {string} hex hash of body
 */
export function hashBody(body) {
  return crypto.createHash("sha256").update(body || "").digest("hex");
}
