oscar-admin/lib_gotify.php
Oscar Admin Contributors fb11868aa9 Support Gotify key migration when app_secret is added
Try legacy fallback key for decryption and re-encrypt with primary app_secret key on read.
2026-12-03 18:36:52 -05:00

320 lines
12 KiB
PHP

<?php
declare(strict_types=1);
/**
* Optional Gotify addon for Oscar Admin.
* 100% optional - the admin panel works without this file.
*
* Per-user settings are stored in gotify-users.php (gitignored).
* Tokens are encrypted at rest (sodium secretbox / openssl AES-256-GCM).
* Global gotify_url/gotify_token in config are optional fallbacks.
*/
function admin_gotify_feature_enabled(): bool
{
if (!function_exists('admin_cfg')) return false;
return (bool) admin_cfg('gotify_enabled', false);
}
function admin_gotify_users_path(): string
{
return __DIR__ . '/gotify-users.php';
}
function admin_gotify_users_legacy_json_path(): string
{
return __DIR__ . '/gotify-users.json';
}
/**
* Encryption keys for Gotify tokens at rest.
* Primary key is app_secret (if set) or a deterministic local fallback.
* If app_secret is set, we also try the legacy fallback key for migration.
*/
function admin_gotify_keys(): array
{
$fallbackSecret = (string) (function_exists('admin_cfg') ? admin_cfg('system_password', '') : '')
. '|' . (string) (function_exists('admin_cfg') ? admin_cfg('session_name', 'oscar_admin') : 'oscar_admin')
. '|oscar-admin-gotify';
$fallbackKey = hash('sha256', $fallbackSecret, true);
$secret = trim((string) (function_exists('admin_cfg') ? admin_cfg('app_secret', '') : ''));
if ($secret === '') {
return [$fallbackKey];
}
$primary = hash('sha256', $secret, true);
// Include fallback for smooth migration when app_secret is added later.
if (hash_equals($primary, $fallbackKey)) return [$primary];
return [$primary, $fallbackKey];
}
function admin_gotify_key(): string
{
$keys = admin_gotify_keys();
return $keys[0];
}
function admin_gotify_encrypt(string $plaintext): string
{
if ($plaintext === '') return '';
$key = admin_gotify_key();
if (function_exists('sodium_crypto_secretbox')) {
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$cipher = sodium_crypto_secretbox($plaintext, $nonce, $key);
return 's1:' . base64_encode($nonce . $cipher);
}
$iv = random_bytes(12);
$tag = '';
$cipher = openssl_encrypt($plaintext, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);
if ($cipher === false) return '';
return 'o1:' . base64_encode($iv . $tag . $cipher);
}
function admin_gotify_decrypt(string $value): string
{
$value = trim($value);
if ($value === '') return '';
$keys = admin_gotify_keys();
if (str_starts_with($value, 's1:')) {
if (!function_exists('sodium_crypto_secretbox_open')) return '';
$raw = base64_decode(substr($value, 3), true);
if ($raw === false || strlen($raw) < SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES) return '';
$nonce = substr($raw, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$cipher = substr($raw, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
foreach ($keys as $key) {
$plain = sodium_crypto_secretbox_open($cipher, $nonce, $key);
if (is_string($plain)) return $plain;
}
return '';
}
if (str_starts_with($value, 'o1:')) {
$raw = base64_decode(substr($value, 3), true);
if ($raw === false || strlen($raw) < 28) return '';
$iv = substr($raw, 0, 12);
$tag = substr($raw, 12, 16);
$cipher = substr($raw, 28);
foreach ($keys as $key) {
$plain = openssl_decrypt($cipher, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);
if (is_string($plain)) return $plain;
}
return '';
}
// Legacy plaintext token - returned as-is; will be migrated on next save.
return $value;
}
function admin_gotify_is_encrypted(string $value): bool
{
return str_starts_with($value, 's1:') || str_starts_with($value, 'o1:');
}
function admin_gotify_users_load(): array
{
$path = admin_gotify_users_path();
if (file_exists($path)) {
$data = @include $path;
return is_array($data) ? $data : [];
}
// One-time migration from legacy JSON if present.
$legacy = admin_gotify_users_legacy_json_path();
if (file_exists($legacy)) {
$raw = @file_get_contents($legacy);
$data = json_decode(is_string($raw) ? $raw : '', true);
if (is_array($data)) {
admin_gotify_users_save_all($data);
@unlink($legacy);
return $data;
}
}
return [];
}
function admin_gotify_users_save_all(array $data): bool
{
$path = admin_gotify_users_path();
$export = var_export($data, true);
$php = "<?php\ndeclare(strict_types=1);\n\n// Gotify per-user settings. Kept as PHP to avoid direct browser access.\n// Tokens are encrypted at rest; do not treat this file as public.\nreturn " . $export . ";\n";
$ok = @file_put_contents($path, $php, LOCK_EX) !== false;
if ($ok) {
@chmod($path, 0600);
}
return $ok;
}
function admin_gotify_user_get(string $screenName): ?array
{
if (!function_exists('admin_normalize_screen_name')) return null;
$key = admin_normalize_screen_name($screenName);
if ($key === '') return null;
$all = admin_gotify_users_load();
$row = $all[$key] ?? null;
if (!is_array($row)) return null;
$url = trim((string) ($row['url'] ?? ''));
$storedToken = trim((string) ($row['token'] ?? ''));
if ($url === '' || $storedToken === '') return null;
$token = admin_gotify_decrypt($storedToken);
if ($token === '') return null;
// Transparently migrate legacy plaintext or old-key encrypted tokens.
$needsMigration = !admin_gotify_is_encrypted($storedToken);
if (!$needsMigration && admin_gotify_is_encrypted($storedToken)) {
$primary = admin_gotify_key();
$probe = null;
if (str_starts_with($storedToken, 's1:') && function_exists('sodium_crypto_secretbox_open')) {
$raw = base64_decode(substr($storedToken, 3), true);
if ($raw !== false && strlen($raw) >= SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES) {
$nonce = substr($raw, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$cipher = substr($raw, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$probe = sodium_crypto_secretbox_open($cipher, $nonce, $primary);
}
} elseif (str_starts_with($storedToken, 'o1:')) {
$raw = base64_decode(substr($storedToken, 3), true);
if ($raw !== false && strlen($raw) >= 28) {
$iv = substr($raw, 0, 12);
$tag = substr($raw, 12, 16);
$cipher = substr($raw, 28);
$probe = openssl_decrypt($cipher, 'aes-256-gcm', $primary, OPENSSL_RAW_DATA, $iv, $tag);
}
}
$needsMigration = !is_string($probe);
}
if ($needsMigration) {
$row['token'] = admin_gotify_encrypt($token);
$row['updated_at'] = (string) ($row['updated_at'] ?? date('c'));
$all[$key] = $row;
admin_gotify_users_save_all($all);
}
return [
'url' => $url,
'token' => $token,
'priority' => max(0, min(10, (int) ($row['priority'] ?? admin_cfg('gotify_priority', 5)))),
'updated_at' => (string) ($row['updated_at'] ?? ''),
];
}
function admin_gotify_user_save(string $screenName, string $url, string $token, ?int $priority = null): array
{
if (!function_exists('admin_normalize_screen_name')) {
return ['ok' => false, 'error' => 'Missing admin helpers.'];
}
$key = admin_normalize_screen_name($screenName);
if ($key === '') return ['ok' => false, 'error' => 'Invalid screen name.'];
$url = rtrim(trim($url), '/');
$token = trim($token);
$priority = $priority ?? (int) admin_cfg('gotify_priority', 5);
$priority = max(0, min(10, $priority));
$all = admin_gotify_users_load();
if ($url === '' || $token === '') {
unset($all[$key]);
$saved = admin_gotify_users_save_all($all);
return $saved ? ['ok' => true, 'cleared' => true] : ['ok' => false, 'error' => 'Failed to save Gotify settings.'];
}
// Basic validation
if (!preg_match('#^https?://#i', $url)) {
return ['ok' => false, 'error' => 'Gotify URL must start with http:// or https://'];
}
$encToken = admin_gotify_encrypt($token);
if ($encToken === '') {
return ['ok' => false, 'error' => 'Failed to secure Gotify token.'];
}
$all[$key] = [
'screen_name' => $screenName,
'url' => $url,
'token' => $encToken,
'priority' => $priority,
'updated_at' => date('c'),
];
$saved = admin_gotify_users_save_all($all);
return $saved ? ['ok' => true, 'cleared' => false] : ['ok' => false, 'error' => 'Failed to save Gotify settings.'];
}
function admin_gotify_resolve(string $screenName): ?array
{
$user = admin_gotify_user_get($screenName);
if ($user) return $user;
// Optional global fallback
$url = rtrim(trim((string) admin_cfg('gotify_url', '')), '/');
$token = trim((string) admin_cfg('gotify_token', ''));
if ($url !== '' && $token !== '') {
return [
'url' => $url,
'token' => $token,
'priority' => max(0, min(10, (int) admin_cfg('gotify_priority', 5))),
'updated_at' => '',
'fallback' => true,
];
}
return null;
}
function admin_gotify_enabled(): bool
{
// Back-compat alias: feature toggle (not "is configured for a specific user").
return admin_gotify_feature_enabled();
}
function admin_gotify_send(string $title, string $message, ?int $priority = null, ?string $url = null, ?string $token = null): array
{
if (!admin_gotify_feature_enabled()) {
return ['ok' => false, 'status' => 0, 'error' => 'Gotify is not enabled', 'data' => null, 'raw' => ''];
}
$url = rtrim(trim((string) ($url ?? admin_cfg('gotify_url', ''))), '/');
$token = trim((string) ($token ?? admin_cfg('gotify_token', '')));
if ($url === '' || $token === '') {
return ['ok' => false, 'status' => 0, 'error' => 'Gotify is not configured', 'data' => null, 'raw' => ''];
}
$priority = $priority ?? (int) admin_cfg('gotify_priority', 5);
$priority = max(0, min(10, $priority));
$endpoint = $url . '/message?token=' . rawurlencode($token);
$payload = json_encode([
'title' => $title,
'message' => $message,
'priority' => $priority,
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$ch = curl_init($endpoint);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json; charset=utf-8', 'Accept: application/json'],
CURLOPT_POSTFIELDS => $payload,
CURLOPT_TIMEOUT => 10,
CURLOPT_CONNECTTIMEOUT => 5,
]);
$raw = curl_exec($ch);
$status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$err = curl_error($ch);
curl_close($ch);
if ($raw === false) {
return ['ok' => false, 'status' => 0, 'error' => $err ?: 'Gotify request failed', 'data' => null, 'raw' => ''];
}
$decoded = json_decode($raw, true);
$ok = $status >= 200 && $status < 300;
return [
'ok' => $ok,
'status' => $status,
'error' => $ok ? null : (is_array($decoded) && isset($decoded['errorDescription']) ? (string) $decoded['errorDescription'] : ($raw !== '' ? $raw : 'HTTP ' . $status)),
'data' => $decoded,
'raw' => $raw,
];
}
function admin_gotify_send_for_user(string $screenName, string $title, string $message, ?int $priority = null): array
{
$cfg = admin_gotify_resolve($screenName);
if (!$cfg) {
return ['ok' => false, 'status' => 0, 'error' => 'No Gotify configuration for this user', 'data' => null, 'raw' => ''];
}
return admin_gotify_send($title, $message, $priority ?? $cfg['priority'], $cfg['url'], $cfg['token']);
}