/*
 * Decrypts the CMS's encrypted API responses. The Laravel backend sends every
 * public blog response (404s included) as RNCryptor v3 and marks it with
 * `X-Blog-Encryption: rncryptor-v3`. The body is base64 text; the password is
 * the Blog API key (LARAVEL_BLOG_API_KEY here; the websites call it CMS_ENCRYPTION_KEY).
 *
 * Uses Web Crypto only, so it runs in Node, on Vercel and on Cloudflare Workers.
 *
 * Message layout (RNCryptor v3, password-based):
 *   version (1 byte, 3) | options (1 byte, 1 = password) | encryption salt (8)
 *   | HMAC salt (8) | IV (16) | AES-256-CBC ciphertext, PKCS#7 padded | HMAC (32)
 * Both keys are PBKDF2-SHA1 of the password with their own salt, 10,000
 * rounds, 32 bytes. The HMAC is HMAC-SHA256 over everything before it, and is
 * checked before anything is decrypted.
 * Spec: https://github.com/RNCryptor/RNCryptor-Spec/blob/master/RNCryptor-Spec-v3.md
 */

const version = 3;
const passwordOption = 1;
const saltLength = 8;
const ivLength = 16;
const headerLength = 2 + saltLength * 2 + ivLength;
const hmacLength = 32;
const blockLength = 16;
const pbkdf2Rounds = 10_000;

function decodeBase64(text: string) {
  const binary = atob(text.replace(/\s+/g, ""));
  const bytes = new Uint8Array(binary.length);
  for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
  return bytes;
}

/**
 * Decrypts an RNCryptor v3 message (base64) to UTF-8 text. Throws when the
 * message is malformed, the password is wrong or the message was changed.
 */
export async function decryptRncryptor(
  base64: string,
  password: string,
): Promise<string> {
  let message: Uint8Array<ArrayBuffer>;
  try {
    message = decodeBase64(base64);
  } catch {
    throw new Error("the encrypted response is not base64");
  }

  const cipherLength = message.length - headerLength - hmacLength;
  if (cipherLength < blockLength || cipherLength % blockLength !== 0) {
    throw new Error("the encrypted response has the wrong length");
  }
  if (message[0] !== version || message[1] !== passwordOption) {
    throw new Error(
      `the encrypted response is not RNCryptor v3 with a password (version ${message[0]}, options ${message[1]})`,
    );
  }

  const encryptionSalt = message.subarray(2, 2 + saltLength);
  const hmacSalt = message.subarray(2 + saltLength, 2 + saltLength * 2);
  const iv = message.subarray(2 + saltLength * 2, headerLength);
  const signed = message.subarray(0, message.length - hmacLength);
  const ciphertext = message.subarray(
    headerLength,
    message.length - hmacLength,
  );
  const hmac = message.subarray(message.length - hmacLength);

  const { subtle } = globalThis.crypto;
  const passwordKey = await subtle.importKey(
    "raw",
    new TextEncoder().encode(password),
    "PBKDF2",
    false,
    ["deriveKey"],
  );
  const pbkdf2 = (salt: Uint8Array<ArrayBuffer>) => ({
    name: "PBKDF2",
    hash: "SHA-1",
    salt,
    iterations: pbkdf2Rounds,
  });

  const hmacKey = await subtle.deriveKey(
    pbkdf2(hmacSalt),
    passwordKey,
    { name: "HMAC", hash: "SHA-256", length: 256 },
    false,
    ["verify"],
  );
  // Constant-time comparison inside Web Crypto.
  if (!(await subtle.verify("HMAC", hmacKey, hmac, signed))) {
    throw new Error(
      "the encrypted response failed its integrity check (wrong Blog API key?)",
    );
  }

  const aesKey = await subtle.deriveKey(
    pbkdf2(encryptionSalt),
    passwordKey,
    { name: "AES-CBC", length: 256 },
    false,
    ["decrypt"],
  );
  // Web Crypto removes the PKCS#7 padding.
  const plaintext = await subtle.decrypt(
    { name: "AES-CBC", iv },
    aesKey,
    ciphertext,
  );
  return new TextDecoder("utf-8", { fatal: true }).decode(plaintext);
}
