v1.0.1
AtheraStudio Database
- <?php
- declare(strict_types=1);
-
- namespace Athera;
-
- defined('ATHERA') || exit;
-
- final class Auth
- {
- private static ?array $session = null;
- private static string $sidHash = '';
- private static ?Db $db = null;
-
- private static function file(string $hash): string
- {
- return Config::storage('sessions/' . $hash . '.json');
- }
-
- private static function write(string $file, array $s): bool
- {
- $tmp = $file . '.' . bin2hex(random_bytes(4)) . '.tmp';
- if (@file_put_contents($tmp, json_encode($s), LOCK_EX) === false) return false;
- @chmod($tmp, 0600);
- if (@rename($tmp, $file)) return true;
- @unlink($tmp);
- return is_file($file);
- }
-
- private static function fingerprint(): string
- {
- return hash('sha256', (string)preg_replace('/[\d._]+/', '', (string)($_SERVER['HTTP_USER_AGENT'] ?? '')));
- }
-
- public static function load(): ?array
- {
- if (self::$session !== null) return self::$session;
- $sid = Http::cookie('sid');
- if (!preg_match('/^[A-Za-z0-9_-]{43}$/', $sid)) return null;
- $hash = hash('sha256', $sid);
- $file = self::file($hash);
- $s = null;
- for ($try = 0; $try < 6; $try++) {
- $raw = is_file($file) ? @file_get_contents($file) : false;
- $s = is_string($raw) ? json_decode($raw, true) : null;
- if (is_array($s) && isset($s['last'], $s['created'], $s['fp'], $s['box'])) break;
- $s = null;
- usleep(25000 * ($try + 1));
- }
- if ($s === null) return null;
- $now = time();
- $bindIp = Config::bool('SESSION_BIND_IP') && Security::untrustedProxy() === null && (string)($s['net'] ?? '') !== '';
- $ok = $now - (int)$s['last'] <= Config::int('SESSION_IDLE', 60)
- && $now - (int)$s['created'] <= Config::int('SESSION_MAX', 300)
- && hash_equals((string)$s['fp'], self::fingerprint())
- && (!$bindIp || hash_equals((string)$s['net'], Security::network(Security::ip())));
- if (!$ok) {
- @unlink($file);
- return null;
- }
- if ($now - (int)$s['last'] > 20) {
- $s['last'] = $now;
- self::write($file, $s);
- }
- self::$sidHash = $hash;
- return self::$session = $s;
- }
-
- public static function user(): string
- {
- $s = self::load();
- return $s ? $s['user'] . '@' . $s['host'] : '';
- }
-
- public static function isAdmin(): bool
- {
- $s = self::load();
- if (!$s) return false;
- $admin = Config::get('ADMIN_USER');
- return $admin !== '' && hash_equals($admin, self::user());
- }
-
- public static function csrf(): string
- {
- $s = self::load();
- return $s ? (string)$s['csrf'] : '';
- }
-
- public static function checkCsrf(string $token): bool
- {
- $s = self::load();
- return $s && $token !== '' && hash_equals((string)$s['csrf'], $token);
- }
-
- public static function hostAllowed(string $host, int $port): bool
- {
- if (Config::bool('DB_ALLOW_ANY_HOST')) return true;
- foreach (Config::list('DB_HOSTS') as $h) {
- $parts = explode(':', $h, 2);
- if (strcasecmp($parts[0], $host) === 0 && (!isset($parts[1]) || (int)$parts[1] === $port || $port === 0)) return true;
- }
- return false;
- }
-
- public static function login(array $in): array
- {
- $ip = Security::ip();
- $user = trim((string)($in['user'] ?? ''));
- $pass = (string)($in['pass'] ?? '');
- $host = trim((string)($in['host'] ?? '')) ?: (Config::list('DB_HOSTS')[0] ?? 'localhost');
- $port = (int)($in['port'] ?? 0);
- if (preg_match('/^(.+):(\d+)$/', $host, $m) && !str_contains($m[1], ':')) {
- $host = $m[1];
- $port = (int)$m[2];
- }
- $gate = Security::gate($ip);
- if ($gate) {
- Security::log(['ev' => 'login_denied', 'user' => $user, 'reason' => $gate['reason']]);
- throw new UserError('Sign-in is temporarily unavailable. Try again later.', 429, 'locked');
- }
- if ($user === '' || strlen($user) > 128 || strlen($pass) > 4096 || !preg_match('/^[A-Za-z0-9._\-\[\]:\/]+$/', $host) || $port < 0 || $port > 65535) {
- throw new UserError('Invalid sign-in data', 400, 'bad_login');
- }
- if (!self::hostAllowed($host, $port)) {
- Security::fail($ip, $user, 'host_not_allowed');
- self::slow();
- throw new UserError('Invalid user name, password or server', 401, 'bad_login');
- }
- $secret = Config::get('TOTP_SECRET');
- if ($secret !== '') {
- $step = Crypto::totpMatch($secret, (string)($in['totp'] ?? ''));
- if (!$step || !Security::totpStep($step)) {
- Security::fail($ip, $user, 'totp');
- self::slow();
- throw new UserError('Invalid user name, password or code', 401, 'bad_login');
- }
- }
- try {
- $db = Db::connect($host, $port, $user, $pass);
- } catch (\PDOException $e) {
- $code = preg_match('/\[(\d{4})\]/', $e->getMessage(), $cm) ? (int)$cm[1] : (int)($e->errorInfo[1] ?? 0);
- if (!in_array($code, [2002, 2003, 2005, 2006, 2013], true)) {
- Security::fail($ip, $user, 'password');
- self::slow();
- throw new UserError('Invalid user name, password or server', 401, 'bad_login');
- }
- Security::log(['ev' => 'login_error', 'user' => $user, 'host' => $host, 'error' => mb_substr($e->getMessage(), 0, 200)]);
- throw new UserError('Cannot connect to the database server', 502, 'no_server');
- }
- if (Config::get('ADMIN_USER') === '') {
- Config::save(['ADMIN_USER' => $user . '@' . $host, 'BASE_URL' => Http::origin() . Http::basePath()]);
- Security::log(['ev' => 'admin_claim', 'user' => $user . '@' . $host]);
- }
- $known = Security::success($ip, $user . '@' . $host);
- if (!$known && Config::bool('NOTIFY_NEW_IP') && Config::get('ADMIN_EMAIL') !== '') {
- Notify::newIp($ip, $user . '@' . $host);
- }
- self::start($user, $host, $port, $pass);
- self::$db = $db;
- self::gc();
- return ['ok' => true];
- }
-
- private static function slow(): void
- {
- usleep(random_int(250000, 600000));
- }
-
- private static function start(string $user, string $host, int $port, string $pass): void
- {
- $sid = Crypto::b64u(random_bytes(32));
- $key = random_bytes(32);
- $hash = hash('sha256', $sid);
- $now = time();
- $s = [
- 'user' => $user,
- 'host' => $host,
- 'port' => $port,
- 'box' => base64_encode(Crypto::seal($pass, $key, $hash)),
- 'csrf' => Crypto::b64u(random_bytes(32)),
- 'created' => $now,
- 'last' => $now,
- 'fp' => self::fingerprint(),
- 'net' => Security::untrustedProxy() === null ? Security::network(Security::ip()) : '',
- 'ip' => Security::ip(),
- ];
- if (!self::write(self::file($hash), $s)) throw new \RuntimeException('Cannot write session');
- Http::setCookie('sid', $sid);
- Http::setCookie('k', Crypto::b64u($key));
- self::$session = $s;
- self::$sidHash = $hash;
- }
-
- public static function logout(): void
- {
- if (self::load()) {
- @unlink(self::file(self::$sidHash));
- Security::log(['ev' => 'logout', 'user' => self::user()]);
- }
- Http::clearCookie('sid');
- Http::clearCookie('k');
- self::$session = null;
- }
-
- public static function db(): Db
- {
- if (self::$db) return self::$db;
- $s = self::load();
- if (!$s) throw new UserError('Session expired', 401, 'session');
- $key = Crypto::unb64u(Http::cookie('k'));
- $pass = Crypto::open((string)base64_decode((string)$s['box']), $key, self::$sidHash);
- if ($pass === null) {
- self::logout();
- throw new UserError('Session expired', 401, 'session');
- }
- try {
- return self::$db = Db::connect((string)$s['host'], (int)$s['port'], (string)$s['user'], $pass);
- } catch (\PDOException $e) {
- throw new UserError('Cannot connect to the database server: ' . Db::error($e), 502, 'no_server');
- }
- }
-
- private static function gc(): void
- {
- $max = Config::int('SESSION_MAX', 300);
- $idle = Config::int('SESSION_IDLE', 60);
- $now = time();
- foreach (glob(Config::storage('sessions/*.tmp')) ?: [] as $f) {
- if (@filemtime($f) < $now - 300) @unlink($f);
- }
- foreach (glob(Config::storage('sessions/*.json')) ?: [] as $f) {
- $m = @filemtime($f);
- if ($m !== false && $m < $now - min($max, $idle) - 60) {
- $s = json_decode((string)@file_get_contents($f), true);
- if (!is_array($s) || $now - (int)$s['last'] > $idle || $now - (int)$s['created'] > $max) @unlink($f);
- }
- }
- }
-
- public static function sessions(): array
- {
- $out = [];
- $now = time();
- foreach (glob(Config::storage('sessions/*.json')) ?: [] as $f) {
- $s = json_decode((string)@file_get_contents($f), true);
- if (!is_array($s) || $now - (int)$s['last'] > Config::int('SESSION_IDLE', 60)) continue;
- $id = substr(basename($f, '.json'), 0, 16);
- $out[] = ['id' => $id, 'user' => $s['user'] . '@' . $s['host'], 'ip' => $s['ip'] ?? '', 'created' => $s['created'], 'last' => $s['last'], 'current' => str_starts_with(self::$sidHash, $id)];
- }
- usort($out, function ($a, $b) { return $b['last'] <=> $a['last']; });
- return $out;
- }
-
- public static function kill(string $id): void
- {
- if (!preg_match('/^[a-f0-9]{16}$/', $id)) return;
- foreach (glob(Config::storage('sessions/' . $id . '*.json')) ?: [] as $f) @unlink($f);
- Security::log(['ev' => 'session_kill', 'user' => self::user(), 'session' => $id]);
- }
- }
-