<?php
/**
 * SeekQuarry/Yioop --
 * Open Source Pure PHP Search Engine, Crawler, and Indexer
 *
 * Copyright (C) 2009 - 2026  Chris Pollett chris@pollett.org
 *
 * LICENSE:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * END LICENSE
 *
 * @author Chris Pollett chris@pollett.org
 * @license https://www.gnu.org/licenses/ GPL3
 * @link https://www.seekquarry.com/
 * @copyright 2009 - 2026
 * @filesource
 */
namespace seekquarry\yioop\library\certificates;

/**
 * Thin libsodium wrapper for encrypting per-user credentials
 * (currently external IMAP account passwords; extensible to any other
 * secret a future feature wants to persist). Uses
 * sodium_crypto_secretbox under the hood, which provides authenticated
 * encryption (XSalsa20 + Poly1305) and refuses to decrypt anything
 * that has been tampered with.
 *
 * This class is pure crypto and never touches the database: the caller
 * supplies the master key. In Yioop that key is loaded (and generated
 * on first use) by MailAccountModel from the MAIL_SECRET table in the
 * private database, keeping the only database access in the model
 * layer where it belongs.
 *
 * Threat model in scope: protect stored credentials against an
 * attacker who exfiltrates the public-database dump but not the
 * private-database key. The master key lives in the private DB; the
 * encrypted ciphertext lives in the public DB; without both an
 * attacker reads nothing useful. Out of scope: an attacker with full
 * filesystem access (they would have both DBs and can read the key),
 * memory-resident-process attacks (the plaintext is briefly resident
 * during decrypt), and side-channel attacks on libsodium itself
 * (assumed safe).
 *
 * @author Chris Pollett
 */
class CredentialCipher
{
    /**
     * Encrypts the given plaintext with the supplied master key and
     * returns the nonce / ciphertext pair as base64-encoded strings,
     * suitable for insertion into TEXT columns. A fresh random nonce is
     * minted on every call (sodium_crypto_secretbox requires this;
     * reusing a nonce with the same key is catastrophic).
     *
     * @param string $key the raw 32-byte master key, supplied by the
     *      caller (the model loads it from the private DB)
     * @param string $plaintext bytes to encrypt; any length, including
     *      empty
     * @return array{nonce: string, ciphertext: string} two base64
     *      strings the caller stores side by side
     */
    public static function encrypt(string $key, string $plaintext): array
    {
        self::assertValidKey($key);
        $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
        $ciphertext = sodium_crypto_secretbox($plaintext, $nonce, $key);
        return [
            'nonce' => base64_encode($nonce),
            'ciphertext' => base64_encode($ciphertext),
        ];
    }
    /**
     * Reverses encrypt(). Returns the original plaintext on success;
     * throws \Exception when decryption fails because the ciphertext
     * was tampered with, the key is wrong, or either of the encoded
     * values is malformed.
     *
     * @param string $key the raw 32-byte master key, the same one
     *      passed to encrypt()
     * @param string $nonce_b64 base64-encoded nonce previously
     *      returned by encrypt()
     * @param string $ciphertext_b64 base64-encoded ciphertext
     *      previously returned by encrypt()
     * @return string the original plaintext bytes
     */
    public static function decrypt(string $key, string $nonce_b64,
        string $ciphertext_b64): string
    {
        self::assertValidKey($key);
        $nonce = base64_decode($nonce_b64, true);
        $ciphertext = base64_decode($ciphertext_b64, true);
        if ($nonce === false || $ciphertext === false) {
            throw new \Exception(
                "CredentialCipher: malformed base64 input");
        }
        if (strlen($nonce) !== SODIUM_CRYPTO_SECRETBOX_NONCEBYTES) {
            throw new \Exception(
                "CredentialCipher: nonce has wrong length");
        }
        $plaintext = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
        if ($plaintext === false) {
            throw new \Exception(
                "CredentialCipher: ciphertext failed authentication");
        }
        return $plaintext;
    }
    /**
     * Guards that a supplied key is the right size for
     * sodium_crypto_secretbox before it is used, turning a misuse into
     * a clear error instead of a raw libsodium exception.
     *
     * @param string $key the raw master key to check
     * @throws \Exception when the key is not the required length
     */
    protected static function assertValidKey(string $key): void
    {
        if (strlen($key) !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
            throw new \Exception(
                "CredentialCipher: master key has wrong length");
        }
    }
}
