<?php
/**
 * API-Osmium.php 1.0.1 — kit PHP pour créer un outil qui dialogue avec l'API d'Osmium.
 * Documentation : https://osmium.lilas3.com/api/#kits
 * 1.0.1 (2026-11-15) : plus d'appel à curl_close() (obsolète depuis PHP 8.5 : son avertissement pouvait se glisser dans les
 *                      réponses de votre outil). Aucun autre changement ; la 1.0.0 reste téléchargeable telle quelle.
 * © Osmium (osmium.lilas3.com). Licence d'utilisation Osmium, avec cette exception : vous pouvez copier ce fichier
 * dans le projet de votre outil, sans le modifier, uniquement pour dialoguer avec l'API d'Osmium. La vente, la
 * commercialisation et la redistribution de ce fichier pour lui-même restent interdites.
 * Texte complet : https://osmium.lilas3.com/publique-outils/#licence
 *
 * Prérequis : PHP 8.1 ou plus, extensions curl, sodium, json ; sessions PHP (ou votre propre stockage, voir « store »).
 *
 * SÉCURITÉ (ce que fait le kit pour vous) :
 *  - connexion de l'utilisateur sur Osmium (OAuth 2 + PKCE S256) : votre outil ne voit jamais son mot de passe ;
 *    « state » vérifié au retour (protection contre les connexions forcées) ;
 *  - échanges avec Osmium en HTTPS uniquement, certificat vérifié, TLS 1.2 minimum, sans suivre de redirection ;
 *  - jetons (accès, renouvellement) gardés CHIFFRÉS (XSalsa20-Poly1305, libsodium) avec votre clé « storage_key » ;
 *    renouvellement automatique avant expiration ;
 *  - relais pour le navigateur (proxy) : même site uniquement, jeton anti-CSRF, liste blanche de routes, jamais les jetons.
 * CE QUI RESTE À VOTRE CHARGE :
 *  - garder « client_secret » et « storage_key » hors du code public (variables d'environnement, fichier hors du web) ;
 *  - servir votre outil en HTTPS ; ne jamais écrire les jetons dans des journaux.
 *
 * ---------------------------------------------------------------------------------------------------------------------
 *   require __DIR__ . '/API-Osmium.php';
 *   session_start();
 *   $osmium = new OsmiumApiClient([
 *       'client_id'     => 'identifiant de 32 caractères de votre outil',
 *       'client_secret' => getenv('OSMIUM_CLIENT_SECRET'),   // jeton d'identification « osmt_… »
 *       'redirect_uri'  => 'https://mon-outil.fr/osmium/retour.php',
 *       'scopes'        => ['profil.identifiant', 'systeme.lire', 'systeme.ecrire'],
 *       'storage_key'   => getenv('OSMIUM_STORAGE_KEY'),     // 64 caractères hexadécimaux : bin2hex(random_bytes(32))
 *   ]);
 *
 *   // connexion.php : envoie l'utilisateur sur Osmium
 *   header('Location: ' . $osmium->authorizeUrl()); exit;
 *
 *   // retour.php : adresse de retour enregistrée sur https://osmium.lilas3.com/api/
 *   $osmium->handleCallback($_GET);                // lève OsmiumApiException si refus, « state » faux, code invalide…
 *
 *   // ensuite, n'importe où :
 *   $moi = $osmium->me();                          // ['identifiant' => '@…', 'autorisations' => […]]
 *   $osmium->systemWrite('notes.txt', 'Bonjour');  // dossier « Système › votre outil » de l'utilisateur
 *
 *   // relais.php : pour API-Osmium.js (navigateur)
 *   $osmium->proxy(['moi', 'systeme/liste', 'systeme/lire', 'systeme/ecrire']);
 * ---------------------------------------------------------------------------------------------------------------------
 */

if (!class_exists('OsmiumApiClient', false)) {

    /** Erreur de l'API ou du kit. $error : code court (« acces », « autorisation », « cle »…), $status : code HTTP. */
    class OsmiumApiException extends RuntimeException {
        public string $error;
        public int $status;
        public function __construct(string $message, string $error = 'erreur', int $status = 0) {
            parent::__construct($message, $status);
            $this->error = $error;
            $this->status = $status;
        }
    }

    final class OsmiumApiClient {
        public const VERSION = '1.0.1';
        public const ENDPOINT = 'https://osmium.lilas3.com/endpoint/';
        public const AUTHORIZE = 'https://account.osmium.lilas3.com/autoriser';
        private const SESSION_KEY = 'osmium_api_kit';
        private const BINARY_ROUTES = ['moi/avatar', 'systeme/lire', 'fichiers/lire', 'groupes/lire'];
        private const FILE_MAX = 16 * 1024 * 1024;

        private string $clientId;
        private string $clientSecret;
        private string $redirectUri;
        private array $scopes;
        private string $storageKey;
        /** @var callable|null */ private $load;
        /** @var callable|null */ private $save;
        private int $timeout;

        /**
         * Options : client_id, client_secret, redirect_uri, scopes (tableau), storage_key (64 hexadécimaux),
         * store (facultatif) : ['load' => fn(): ?string, 'save' => fn(?string $blob): void] pour garder les jetons ailleurs
         * qu'en session (base de données…) ; le blob reçu est DÉJÀ chiffré. timeout (secondes, 30 par défaut).
         */
        public function __construct(array $config) {
            foreach (['curl_init', 'sodium_crypto_secretbox', 'json_encode'] as $fn) {
                if (!function_exists($fn)) throw new OsmiumApiException("Extension PHP manquante pour $fn.", 'configuration');
            }
            $this->clientId = (string) ($config['client_id'] ?? '');
            $this->clientSecret = (string) ($config['client_secret'] ?? '');
            $this->redirectUri = (string) ($config['redirect_uri'] ?? '');
            $this->scopes = array_values(array_map('strval', (array) ($config['scopes'] ?? [])));
            $key = (string) ($config['storage_key'] ?? '');
            $this->timeout = max(5, (int) ($config['timeout'] ?? 30));
            if (!preg_match('/^[0-9a-f]{32}$/', $this->clientId)) throw new OsmiumApiException('client_id invalide (32 caractères hexadécimaux).', 'configuration');
            if (!str_starts_with($this->clientSecret, 'osmt_')) throw new OsmiumApiException('client_secret invalide (jeton d\'identification « osmt_… »).', 'configuration');
            if (!self::validRedirect($this->redirectUri)) throw new OsmiumApiException('redirect_uri doit être en https (ou http://localhost en développement).', 'configuration');
            if (!$this->scopes) throw new OsmiumApiException('Indiquez au moins une autorisation dans « scopes ».', 'configuration');
            if (!preg_match('/^[0-9a-fA-F]{64}$/', $key)) throw new OsmiumApiException('storage_key doit faire 64 caractères hexadécimaux (bin2hex(random_bytes(32))).', 'configuration');
            $this->storageKey = sodium_hex2bin($key);
            if (isset($config['store'])) {
                if (!is_callable($config['store']['load'] ?? null) || !is_callable($config['store']['save'] ?? null)) {
                    throw new OsmiumApiException('store doit contenir deux fonctions : load et save.', 'configuration');
                }
                $this->load = $config['store']['load'];
                $this->save = $config['store']['save'];
            }
        }

        public function __destruct() {
            if (isset($this->storageKey)) sodium_memzero($this->storageKey);
        }

        // ============================================================== Connexion de l'utilisateur (OAuth 2 + PKCE)

        /** Adresse de la page d'autorisation d'Osmium ; prépare et garde (chiffrés) « state » et « code_verifier ». */
        public function authorizeUrl(?array $scopes = null): string {
            $verifier = self::b64url(random_bytes(64));
            $state = self::b64url(random_bytes(24));
            $this->sessionPut('pending', $this->seal(json_encode(['v' => $verifier, 's' => $state, 't' => time()])));
            return self::AUTHORIZE . '?' . http_build_query([
                'response_type' => 'code',
                'client_id' => $this->clientId,
                'redirect_uri' => $this->redirectUri,
                'scope' => implode(' ', $scopes ?? $this->scopes),
                'state' => $state,
                'code_challenge' => self::b64url(hash('sha256', $verifier, true)),
                'code_challenge_method' => 'S256',
            ]);
        }

        /** À appeler sur la page de retour avec $_GET. Vérifie « state », échange le code, garde les jetons chiffrés. */
        public function handleCallback(array $query): void {
            $pending = $this->sessionGet('pending');
            $this->sessionPut('pending', null);                       // usage unique
            $p = $pending ? json_decode((string) $this->open($pending), true) : null;
            if (!is_array($p) || time() - (int) $p['t'] > 900) throw new OsmiumApiException('Connexion expirée : recommencez.', 'state', 400);
            if (!is_string($query['state'] ?? null) || !hash_equals($p['s'], $query['state'])) {
                throw new OsmiumApiException('Réponse d\'Osmium non reconnue (state) : connexion annulée.', 'state', 400);
            }
            if (isset($query['error'])) {
                throw new OsmiumApiException($query['error'] === 'access_denied' ? 'Vous avez refusé l\'accès.' : 'Connexion refusée par Osmium.', (string) $query['error'], 403);
            }
            if (!is_string($query['code'] ?? null) || $query['code'] === '') throw new OsmiumApiException('Code absent.', 'code', 400);
            $r = $this->request('token', ['grant_type' => 'authorization_code', 'code' => $query['code'],
                                          'redirect_uri' => $this->redirectUri, 'code_verifier' => $p['v']], null);
            $this->storeTokens($r);
        }

        /** L'utilisateur a-t-il connecté son compte Osmium (jetons présents) ? */
        public function isConnected(): bool { return $this->loadTokens() !== null; }

        /** Oublie les jetons de cet utilisateur (sans couper l'accès côté Osmium : voir revoke()). */
        public function disconnect(): void { $this->saveTokens(null); }

        /** Coupe l'accès de l'outil au compte de l'utilisateur, côté Osmium, puis oublie les jetons. */
        public function revoke(): void {
            try { $this->call('revoquer'); } finally { $this->disconnect(); }
        }

        // ============================================================== Appels

        /** Appel JSON. Renouvelle le jeton d'accès si besoin, et réessaie une fois s'il vient d'expirer. */
        public function call(string $route, array $data = []): array {
            $r = $this->authorized($route, $data);
            if (!is_array($r)) throw new OsmiumApiException('Réponse inattendue : utilisez download() pour un fichier.', 'format');
            return $r;
        }

        /** Appel qui renvoie un fichier : ['content' => octets, 'name' => nom, 'type' => type MIME]. */
        public function download(string $route, array $data = []): array {
            $r = $this->authorized($route, $data);
            if (!isset($r['__binary'])) throw new OsmiumApiException('Cette route ne renvoie pas de fichier.', 'format');
            return ['content' => $r['__binary'], 'name' => $r['__name'], 'type' => $r['__type']];
        }

        // --- Raccourcis (voir la documentation pour le détail de chaque route) ---
        public function me(): array { return $this->call('moi'); }
        public function avatar(): array { return $this->download('moi/avatar'); }
        public function systemList(): array { return $this->call('systeme/liste')['fichiers'] ?? []; }
        public function systemRead(string $id): array { return $this->download('systeme/lire', ['id' => $id]); }
        /** Crée un fichier (ou le remplace si $id est donné) dans « Système › votre outil ». Retourne son identifiant. */
        public function systemWrite(string $name, string $bytes, ?string $id = null): string {
            return $this->call('systeme/ecrire', ($id ? ['id' => $id] : ['nom' => $name]) + ['contenu' => self::encodeFile($bytes)])['id'];
        }
        public function systemDelete(string $id): void { $this->call('systeme/supprimer', ['id' => $id]); }
        public function filesList(?string $folder = null): array { return $this->call('fichiers/liste', $folder ? ['dossier' => $folder] : []); }
        public function filesRead(string $id): array { return $this->download('fichiers/lire', ['id' => $id]); }
        public function filesWrite(string $folder, string $name, string $bytes): string {
            return $this->call('fichiers/ecrire', ['dossier' => $folder, 'nom' => $name, 'contenu' => self::encodeFile($bytes)])['id'];
        }
        public function filesUpdate(string $id, ?string $bytes = null, ?string $name = null): void {
            $d = ['id' => $id];
            if ($bytes !== null) $d['contenu'] = self::encodeFile($bytes);
            if ($name !== null) $d['nom'] = $name;
            $this->call('fichiers/ecrire', $d);
        }
        public function filesDelete(string $id): void { $this->call('fichiers/supprimer', ['id' => $id]); }
        public function groupsList(?string $group = null, ?string $folder = null): array {
            return $this->call('groupes/liste', array_filter(['groupe' => $group, 'dossier' => $folder]));
        }
        public function groupsRead(string $group, string $id): array { return $this->download('groupes/lire', ['groupe' => $group, 'id' => $id]); }
        public function groupsWrite(string $group, string $name, string $bytes, ?string $folder = null): string {
            return $this->call('groupes/ecrire', array_filter(['groupe' => $group, 'dossier' => $folder, 'nom' => $name]) + ['contenu' => self::encodeFile($bytes)])['id'];
        }
        public function groupsDelete(string $group, string $id): void { $this->call('groupes/supprimer', ['groupe' => $group, 'id' => $id]); }
        public function messagesList(string $conversation, int $after = 0, int $limit = 50): array {
            return $this->call('messages/liste', ['conversation' => $conversation, 'apres' => $after, 'limite' => $limit])['messages'] ?? [];
        }
        public function messagesSend(string $conversation, string $text): int {
            return (int) $this->call('messages/envoyer', ['conversation' => $conversation, 'texte' => $text])['id'];
        }
        public function notify(string $title, string $text = '', ?string $link = null): void {
            $this->call('notifier', array_filter(['titre' => $title, 'texte' => $text, 'lien' => $link], fn($v) => $v !== null));
        }

        // ============================================================== Relais pour le navigateur (API-Osmium.js)

        /** Jeton anti-CSRF à placer dans la page : <meta name="osmium-csrf" content="…"> */
        public function csrfToken(): string {
            $t = $this->sessionGet('csrf');
            if (!is_string($t) || strlen($t) !== 64) { $t = bin2hex(random_bytes(32)); $this->sessionPut('csrf', $t); }
            return $t;
        }

        /**
         * Traite une requête d'API-Osmium.js et termine le script. $allowedRoutes : routes que le navigateur peut demander
         * (n'autorisez que le nécessaire). Jamais de jeton envoyé au navigateur. Requête refusée si elle vient d'un autre site.
         */
        public function proxy(array $allowedRoutes): void {
            header('Cache-Control: no-store');
            header('X-Content-Type-Options: nosniff');
            $reply = function (int $status, array $data) { http_response_code($status); header('Content-Type: application/json; charset=utf-8'); echo json_encode($data, JSON_UNESCAPED_UNICODE); exit; };
            if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') $reply(405, ['ok' => false, 'erreur' => 'methode', 'message' => 'POST uniquement.']);
            // Même site uniquement : en-tête Sec-Fetch-Site du navigateur, sinon comparaison de l'origine
            $site = $_SERVER['HTTP_SEC_FETCH_SITE'] ?? null;
            $origin = $_SERVER['HTTP_ORIGIN'] ?? null;
            $self = (($_SERVER['HTTPS'] ?? '') === 'on' ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? '');
            if (($site !== null && $site !== 'same-origin') || ($origin !== null && $origin !== $self)) $reply(403, ['ok' => false, 'erreur' => 'origine', 'message' => 'Requête refusée : autre site.']);
            $csrf = $_SERVER['HTTP_X_OSMIUM_CSRF'] ?? '';
            if (!is_string($csrf) || !hash_equals($this->csrfToken(), $csrf)) $reply(403, ['ok' => false, 'erreur' => 'csrf', 'message' => 'Jeton anti-CSRF invalide : rechargez la page.']);
            $in = json_decode((string) file_get_contents('php://input'), true);
            $route = is_array($in) && is_string($in['route'] ?? null) ? $in['route'] : '';
            $data = is_array($in['data'] ?? null) ? $in['data'] : [];
            if (in_array($route, ['token', 'revoquer'], true) || !in_array($route, $allowedRoutes, true)) $reply(403, ['ok' => false, 'erreur' => 'route', 'message' => 'Route non autorisée par cet outil.']);
            if (!$this->isConnected()) $reply(401, ['ok' => false, 'erreur' => 'connexion', 'message' => 'Connectez d\'abord votre compte Osmium.']);
            try {
                $r = $this->authorized($route, $data);
            } catch (OsmiumApiException $e) {
                $reply($e->status ?: 502, ['ok' => false, 'erreur' => $e->error, 'message' => $e->getMessage()]);
            }
            if (isset($r['__binary'])) {
                header('Content-Type: application/octet-stream');
                header('X-Osmium-Nom: ' . rawurlencode($r['__name']));
                header('X-Osmium-Type: ' . preg_replace('#[^a-z0-9.+/-]#i', '', $r['__type']));
                header('Content-Disposition: attachment');
                echo $r['__binary'];
                exit;
            }
            $reply(200, $r);
        }

        // ============================================================== Interne : jetons chiffrés

        private function authorized(string $route, array $data, bool $retry = true) {
            if (!preg_match('#^[a-z]+(/[a-z]+)?$#', $route) || $route === 'token') throw new OsmiumApiException('Route invalide.', 'route');
            $t = $this->loadTokens();
            if ($t === null) throw new OsmiumApiException('Compte Osmium non connecté.', 'connexion', 401);
            if ($t['access_expires'] - 60 < time()) $t = $this->refresh($t);
            try {
                return $this->request($route, $data, $t['access_token']);
            } catch (OsmiumApiException $e) {
                if ($retry && $e->status === 401 && $e->error === 'acces') {   // jeton expiré entre-temps : un seul nouvel essai
                    $this->refresh($t);
                    return $this->authorized($route, $data, false);
                }
                if ($e->status === 401 || ($e->status === 400 && $e->error === 'renouvellement')) $this->disconnect();
                throw $e;
            }
        }

        private function refresh(array $t): array {
            try {
                $r = $this->request('token', ['grant_type' => 'refresh_token', 'refresh_token' => $t['refresh_token']], null);
            } catch (OsmiumApiException $e) {
                $this->disconnect();
                throw new OsmiumApiException('Accès expiré ou retiré par l\'utilisateur : reconnectez le compte Osmium.', 'connexion', 401);
            }
            return $this->storeTokens($r);
        }

        private function storeTokens(array $r): array {
            if (empty($r['access_token']) || empty($r['refresh_token'])) throw new OsmiumApiException('Réponse de jetons incomplète.', 'token', 502);
            $t = ['access_token' => (string) $r['access_token'], 'refresh_token' => (string) $r['refresh_token'],
                  'access_expires' => time() + (int) ($r['expires_in'] ?? 3600), 'scopes' => $r['autorisations'] ?? []];
            $this->saveTokens($t);
            return $t;
        }

        private function loadTokens(): ?array {
            $blob = $this->load ? ($this->load)() : $this->sessionGet('tokens');
            if (!is_string($blob) || $blob === '') return null;
            $json = $this->open($blob);
            $t = $json === null ? null : json_decode($json, true);
            return is_array($t) && isset($t['access_token'], $t['refresh_token']) ? $t : null;
        }

        private function saveTokens(?array $t): void {
            $blob = $t === null ? null : $this->seal(json_encode($t));
            if ($this->save) ($this->save)($blob); else $this->sessionPut('tokens', $blob);
        }

        private function seal(string $plain): string {
            $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
            return self::b64url($nonce . sodium_crypto_secretbox($plain, $nonce, $this->storageKey));
        }

        private function open(string $blob): ?string {
            $raw = base64_decode(strtr($blob, '-_', '+/'), true);
            if ($raw === false || strlen($raw) <= SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES) return null;
            $plain = sodium_crypto_secretbox_open(substr($raw, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES), substr($raw, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES), $this->storageKey);
            return $plain === false ? null : $plain;
        }

        private function sessionGet(string $k) {
            if (session_status() !== PHP_SESSION_ACTIVE) throw new OsmiumApiException('Démarrez la session PHP (session_start()) avant d\'utiliser le kit.', 'configuration');
            return $_SESSION[self::SESSION_KEY][$k] ?? null;
        }
        private function sessionPut(string $k, $v): void {
            if (session_status() !== PHP_SESSION_ACTIVE) throw new OsmiumApiException('Démarrez la session PHP (session_start()) avant d\'utiliser le kit.', 'configuration');
            if ($v === null) unset($_SESSION[self::SESSION_KEY][$k]); else $_SESSION[self::SESSION_KEY][$k] = $v;
        }

        // ============================================================== Interne : HTTPS vers Osmium

        private function request(string $route, array $data, ?string $accessToken) {
            $headers = ['Content-Type: application/json', 'Accept: application/json',
                        'X-Osmium-Outil: ' . $this->clientId . ':' . $this->clientSecret,
                        'User-Agent: API-Osmium.php/' . self::VERSION];
            if ($accessToken !== null) $headers[] = 'Authorization: Bearer ' . $accessToken;
            $respHeaders = [];
            $ch = curl_init(self::ENDPOINT . $route);
            curl_setopt_array($ch, [
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
                CURLOPT_HTTPHEADER => $headers,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_FOLLOWLOCATION => false,                       // jamais de redirection : les jetons ne partent nulle part ailleurs
                CURLOPT_SSL_VERIFYPEER => true,
                CURLOPT_SSL_VERIFYHOST => 2,
                CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
                CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1_2,
                CURLOPT_CONNECTTIMEOUT => 10,
                CURLOPT_TIMEOUT => $this->timeout,
                CURLOPT_HEADERFUNCTION => function ($c, $line) use (&$respHeaders) {
                    $p = explode(':', $line, 2);
                    if (count($p) === 2) $respHeaders[strtolower(trim($p[0]))] = trim($p[1]);
                    return strlen($line);
                },
            ]);
            $body = curl_exec($ch);
            $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
            $err = curl_error($ch);
            unset($ch);   // libère la connexion (curl_close() : obsolète depuis PHP 8.5, sans effet depuis PHP 8.0)
            if ($body === false) throw new OsmiumApiException('Connexion à Osmium impossible : ' . $err, 'reseau');
            if (in_array($route, self::BINARY_ROUTES, true) && $status === 200 && !str_contains($respHeaders['content-type'] ?? '', 'json')) {
                if (strlen($body) > self::FILE_MAX) throw new OsmiumApiException('Fichier trop gros.', 'taille');
                return ['__binary' => $body, '__name' => rawurldecode($respHeaders['x-osmium-nom'] ?? 'fichier'), '__type' => $respHeaders['x-osmium-type'] ?? 'application/octet-stream'];
            }
            $json = json_decode($body, true);
            if (!is_array($json)) throw new OsmiumApiException('Réponse illisible d\'Osmium (HTTP ' . $status . ').', 'format', $status);
            if ($status >= 400 || empty($json['ok'])) {
                throw new OsmiumApiException((string) ($json['message'] ?? 'Erreur de l\'API.'), (string) ($json['erreur'] ?? 'erreur'), $status);
            }
            return $json;
        }

        private static function encodeFile(string $bytes): string {
            if (strlen($bytes) > self::FILE_MAX) throw new OsmiumApiException('Fichier trop gros : 16 Mo au plus par l\'API.', 'taille');
            return base64_encode($bytes);
        }
        private static function b64url(string $bin): string { return rtrim(strtr(base64_encode($bin), '+/', '-_'), '='); }
        private static function validRedirect(string $uri): bool {
            $p = parse_url($uri);
            if (!$p || empty($p['host']) || str_contains($uri, '#')) return false;
            return ($p['scheme'] ?? '') === 'https' || (($p['scheme'] ?? '') === 'http' && in_array($p['host'], ['localhost', '127.0.0.1'], true));
        }
    }
}
