Files
laysense.cn/app/Content/OAuthCredentials.php
T

117 lines
4.8 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Content;
use App\Config\Environment;
use PDO;
use RuntimeException;
final class OAuthCredentials
{
private const CIPHER = 'aes-256-gcm';
private const KEY_BYTES = 32;
private const NONCE_BYTES = 12;
private const TAG_BYTES = 16;
public static function store(PDO $pdo, int $layout, string $secret): void
{
if ($secret === '' || strlen($secret) > 4096 || str_contains($secret, "\0")) {
throw new RuntimeException('客户端密钥为空或格式无效。');
}
$revision = bin2hex(random_bytes(16));
$nonce = random_bytes(self::NONCE_BYTES);
$ciphertext = openssl_encrypt($secret, self::CIPHER, self::key(create: true), OPENSSL_RAW_DATA, $nonce,
$tag, self::context($layout, $revision), self::TAG_BYTES);
if ($ciphertext === false) {
throw new RuntimeException('无法加密客户端密钥。');
}
$pdo->prepare('INSERT INTO layout_oauth_credentials (layout_id, revision, encrypted_secret) VALUES (?, ?, ?)
ON CONFLICT (layout_id) DO UPDATE SET revision = excluded.revision, encrypted_secret = excluded.encrypted_secret')
->execute([$layout, $revision, base64_encode($nonce . $tag . $ciphertext)]);
}
public static function read(int $layout, string $revision): string
{
$query = Database::connect()->prepare('SELECT encrypted_secret FROM layout_oauth_credentials WHERE layout_id = ? AND revision = ?');
$query->execute([$layout, $revision]);
$value = $query->fetchColumn();
$encrypted = is_string($value) ? base64_decode($value, true) : false;
if ($encrypted === false || strlen($encrypted) <= self::NONCE_BYTES + self::TAG_BYTES) {
throw new RuntimeException('客户端密钥尚未配置或已更新。');
}
$secret = openssl_decrypt(substr($encrypted, self::NONCE_BYTES + self::TAG_BYTES), self::CIPHER, self::key(),
OPENSSL_RAW_DATA, substr($encrypted, 0, self::NONCE_BYTES), substr($encrypted, self::NONCE_BYTES, self::TAG_BYTES),
self::context($layout, $revision));
if ($secret === false) {
throw new RuntimeException('无法解密客户端密钥。');
}
return $secret;
}
public static function migrateLegacy(PDO $pdo): void
{
$layouts = $pdo->query("SELECT id, payload FROM design_presets WHERE kind = 'header' AND preset = 'member'")->fetchAll();
$update = $pdo->prepare('UPDATE design_presets SET payload = ?, version = version + 1 WHERE id = ?');
foreach ($layouts as $layout) {
$payload = json_decode($layout['payload'], true, flags: JSON_THROW_ON_ERROR);
$variable = $payload['provider']['secret_env'] ?? null;
if (!is_string($variable)) {
continue;
}
unset($payload['provider']['secret_env']);
if (preg_match('/^LAYSITE_OAUTH_[A-Z0-9_]{1,45}$/D', $variable)) {
$secret = Environment::get($variable);
if (is_string($secret) && $secret !== '') {
self::store($pdo, (int) $layout['id'], $secret);
}
}
$update->execute([Database::json($payload), $layout['id']]);
}
}
private static function context(int $layout, string $revision): string
{
return 'laysite-oauth:' . $layout . ':' . $revision;
}
private static function key(bool $create = false): string
{
$path = Database::path() . '.key';
if (is_link($path)) {
throw new RuntimeException('密钥文件不能使用符号链接。');
}
$mask = umask(0077);
try {
$file = is_file($path) || $create ? @fopen($path, $create ? 'c+b' : 'rb') : false;
} finally {
umask($mask);
}
if ($file === false) {
throw new RuntimeException('无法打开站点密钥文件。');
}
try {
if (!flock($file, $create ? LOCK_EX : LOCK_SH) || (fstat($file)['mode'] & 0077) !== 0) {
throw new RuntimeException('站点密钥文件需能上锁,并且只能由运行用户访问。');
}
$key = stream_get_contents($file, self::KEY_BYTES + 1);
if ($create && $key === '') {
$key = random_bytes(self::KEY_BYTES);
if (fwrite($file, $key) !== self::KEY_BYTES || !fflush($file)) {
ftruncate($file, 0);
throw new RuntimeException('无法写入站点密钥文件。');
}
}
if (!is_string($key) || strlen($key) !== self::KEY_BYTES) {
throw new RuntimeException('站点密钥文件格式无效。');
}
return $key;
} finally {
fclose($file);
}
}
}