73 lines
2.7 KiB
PHP
73 lines
2.7 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Content;
|
|
|
|
use App\Config\Environment;
|
|
use PDO;
|
|
use RuntimeException;
|
|
|
|
final class McpSettings
|
|
{
|
|
private const CONTEXT = 'laysite-mcp';
|
|
public const PATH = '/mcp';
|
|
|
|
public static function read(): array
|
|
{
|
|
$row = self::stored(Database::connect());
|
|
if ($row === null) {
|
|
$token = self::legacyToken();
|
|
|
|
return ['enabled' => $token !== null, 'version' => 0, 'token' => $token, 'legacy' => $token !== null];
|
|
}
|
|
|
|
$enabled = (bool) $row['enabled'];
|
|
$token = null;
|
|
if ($enabled && $row['encrypted_secret'] !== null) {
|
|
try {
|
|
$token = SiteSecrets::decrypt($row['encrypted_secret'], self::CONTEXT);
|
|
} catch (RuntimeException) {
|
|
// Keep the settings accessible so an administrator can replace an unreadable key.
|
|
}
|
|
}
|
|
|
|
return ['enabled' => $enabled, 'version' => (int) $row['version'], 'token' => $token, 'legacy' => false];
|
|
}
|
|
|
|
public static function save(bool $enabled, bool $rotate, int $version): void
|
|
{
|
|
if ($rotate && !$enabled) {
|
|
throw new RuntimeException('启用 MCP 后才能生成新密钥。');
|
|
}
|
|
Database::write(static function (PDO $pdo) use ($enabled, $rotate, $version): void {
|
|
$row = self::stored($pdo);
|
|
if ($version !== (int) ($row['version'] ?? 0)) {
|
|
throw new RuntimeException('MCP 设置已更新,请刷新后再保存。');
|
|
}
|
|
$encrypted = $row['encrypted_secret'] ?? null;
|
|
$legacy = $row === null ? self::legacyToken() : null;
|
|
if ($rotate || ($enabled && $encrypted === null && $legacy === null)) {
|
|
$encrypted = SiteSecrets::encrypt(bin2hex(random_bytes(32)), self::CONTEXT);
|
|
} elseif ($legacy !== null) {
|
|
$encrypted = SiteSecrets::encrypt($legacy, self::CONTEXT);
|
|
}
|
|
$pdo->prepare('INSERT INTO mcp_settings (id, enabled, encrypted_secret, version) VALUES (1, ?, ?, 1)
|
|
ON CONFLICT (id) DO UPDATE SET enabled = excluded.enabled, encrypted_secret = excluded.encrypted_secret,
|
|
version = mcp_settings.version + 1')->execute([(int) $enabled, $encrypted]);
|
|
});
|
|
}
|
|
|
|
private static function stored(PDO $pdo): ?array
|
|
{
|
|
return $pdo->query('SELECT enabled, encrypted_secret, version FROM mcp_settings WHERE id = 1')->fetch() ?: null;
|
|
}
|
|
|
|
private static function legacyToken(): ?string
|
|
{
|
|
$value = Environment::get('LAYSITE_MCP_TOKEN');
|
|
|
|
return is_string($value) && strlen($value) >= 32 ? $value : null;
|
|
}
|
|
}
|