diff --git a/README.md b/README.md index 79893ee..4eb0fb8 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # 来笙 Laysense 官网 -PHP Webman、原生 CSS 和 SQLite 实现的来笙官网。公开页面由服务端渲染,菜单和 CMS 编辑工具使用原生 JavaScript。运行时只依赖 PHP、Composer 依赖和本机 SQLite 文件。 +PHP Webman、原生 CSS 和 SQLite 实现的来笙官网。公开页面由服务端渲染,前后台共用本地 jQuery,菜单、编辑器及后台表单交互通过 jQuery 实现。运行时只依赖 PHP、Composer 依赖和本机 SQLite 文件。 ## 本地启动 @@ -10,10 +10,20 @@ PHP Webman、原生 CSS 和 SQLite 实现的来笙官网。公开页面由服务 composer install php bin/install.php php bin/admin.php admin@example.com -LAYSENSE_SECURE_COOKIES=0 php start.php start +php start.php start ``` -打开 `http://127.0.0.1:8787`。后台入口为 `/admin`。创建管理员命令会交互读取密码,对同一邮箱再次执行会轮换密码并使旧会话失效。本地 HTTP 测试时关闭 Secure Cookie,生产 HTTPS 环境使用默认设置。 +打开 `http://127.0.0.1:8787`。后台入口为 `/admin`。创建管理员命令会交互读取密码。本机 HTTP 与 HTTPS 反代均支持登录,HTTPS 请求使用 Secure Cookie。 + +## 管理员密码 + +新密码至少 8 个字符,最多 72 字节。已登录的管理员可在 `/admin/password` 输入当前密码并修改密码。忘记密码时,由服务器管理员在站点目录运行以下命令,使用生产服务相同的 `LAYSENSE_DB`。 + +```sh +php bin/admin.php reset admin@example.com +``` + +命令会交互读取密码。重设后,该账号原有的登录会话会失效。 ## 后台编辑 @@ -27,7 +37,7 @@ LAYSENSE_SECURE_COOKIES=0 php start.php start 2. 通过 systemd 或其他进程管理器以前台命令 `php start.php start` 运行。默认监听 `127.0.0.1:8787`。 3. 由 Nginx 等反向代理处理 `laysense.cn` 的 HTTPS,并将请求转发给 Webman。项目根目录保持在公共站点根目录之外。 -下面的 Nginx 片段可放入现有 HTTPS 虚拟主机。 +下面的 Nginx 片段可放入现有 HTTPS 虚拟主机。应用默认信任来自本机回环地址的反代头,Nginx 会覆盖请求携带的 `X-Real-IP` 和 `X-Forwarded-Proto`。密码验证失败的请求按来源计数,超过阈值后返回 429。正确密码仍可登录。 ```nginx location / { @@ -46,10 +56,10 @@ location / { | `LAYSENSE_LISTEN` | `http://127.0.0.1:8787` · Webman 监听地址 | | `LAYSENSE_WORKERS` | `2` · Webman worker 数量 | | `LAYSENSE_DB` | `storage/laysense.sqlite` · SQLite 文件路径。生产可指向独立的持久化目录 | -| `LAYSENSE_SECURE_COOKIES` | 默认启用 · 本地 HTTP 测试设为 `0` | -| `LAYSENSE_TRUSTED_PROXIES` | 默认空 · 逗号分隔的受信反代 IP。使用上述 Nginx 片段时可设为 `127.0.0.1` | +| `LAYSENSE_SECURE_COOKIES` | 默认在可信 HTTPS 反代与非本机地址启用。仅临时测试环境可设置 `0`。 | +| `LAYSENSE_TRUSTED_PROXIES` | 默认 `127.0.0.1,::1` · 逗号分隔的受信反代 IP,设为空字符串可关闭信任 | -SQLite 已启用 WAL。迁移服务器或做线上备份时,可用 `sqlite3 storage/laysense.sqlite ".backup 'laysense-backup.sqlite'"` 取得一致备份。更新代码时保留数据库文件及其存放目录。服务用户需要对 SQLite 目录和 `runtime/` 有写权限。 +SQLite 已启用 WAL。迁移服务器或做线上备份时,可用 `sqlite3 storage/laysense.sqlite ".backup 'laysense-backup.sqlite'"` 取得一致备份。更新代码时保留数据库文件及其存放目录,以同一 `LAYSENSE_DB` 执行 `php bin/install.php` 应用迁移,然后重启服务。已有数据库会补回 PAGEPAN 原始功能图标,保留已编辑的文案和已有图像。服务用户需要对 SQLite 目录和 `runtime/` 有写权限。 ## 迁移范围 diff --git a/app/Content/Database.php b/app/Content/Database.php index 159c7fe..ad9ddb3 100644 --- a/app/Content/Database.php +++ b/app/Content/Database.php @@ -79,6 +79,12 @@ final class Database self::json($item['tags']), $item['status'], $item['date'], $item['date'], $item['legacy'], ]); } + + $migration = $pdo->prepare('INSERT OR IGNORE INTO schema_migrations (name) VALUES (?)'); + $migration->execute(['restore_pagepan_feature_icons']); + if ($migration->rowCount() === 1) { + PagepanFeatureIcons::migrate($pdo); + } }); } diff --git a/app/Content/Html.php b/app/Content/Html.php index 3ba1497..b336afd 100644 --- a/app/Content/Html.php +++ b/app/Content/Html.php @@ -14,7 +14,7 @@ final class Html private const TAGS = [ 'a' => ['href'], 'article' => [], 'b' => [], 'blockquote' => [], 'br' => [], 'caption' => [], 'code' => [], 'dd' => [], 'details' => [], 'div' => ['role', 'aria-label', 'tabindex'], - 'dl' => [], 'dt' => [], 'em' => [], 'h3' => [], 'h4' => [], 'h5' => [], 'hr' => [], 'i' => [], + 'dl' => [], 'dt' => [], 'em' => [], 'h1' => [], 'h2' => [], 'h3' => [], 'h4' => [], 'h5' => [], 'h6' => [], 'hr' => [], 'i' => [], 'img' => ['src', 'alt', 'loading', 'width', 'height'], 'label' => ['for'], 'li' => [], 'ol' => [], 'p' => [], 'pre' => [], 'progress' => ['max', 'value'], 's' => [], 'small' => [], 'source' => ['src', 'type'], 'span' => [], 'strong' => [], 'summary' => [], diff --git a/app/Content/PagepanFeatureIcons.php b/app/Content/PagepanFeatureIcons.php new file mode 100644 index 0000000..e12c923 --- /dev/null +++ b/app/Content/PagepanFeatureIcons.php @@ -0,0 +1,55 @@ +query("SELECT body FROM sections WHERE page_slug = 'pagepan' AND key = 'features'"); + $body = $query->fetchColumn(); + if (!is_string($body) || $body === '') { + return; + } + $paths = json_decode(file_get_contents(dirname(__DIR__, 2) . '/resources/pagepan-feature-icons.json'), true, flags: JSON_THROW_ON_ERROR); + $document = new DOMDocument('1.0', 'UTF-8'); + $document->loadHTML('' . $body . '', LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET); + $xpath = new DOMXPath($document); + + $changed = false; + foreach ($xpath->query('//article[contains(concat(" ", normalize-space(@class), " "), " feature-card ")]') as $card) { + $heading = $xpath->query('(./h2 | ./h3 | ./h4)[1]', $card)->item(0); + if (!$heading instanceof DOMElement || $card->getElementsByTagName('img')->length > 0) { + continue; + } + $title = trim($heading->textContent); + if (!isset($paths[$title])) { + continue; + } + $icon = $document->createElement('img'); + foreach (['src' => $paths[$title], 'alt' => '', 'width' => '50', 'height' => '50', 'loading' => 'lazy'] as $key => $value) { + $icon->setAttribute($key, $value); + } + $card->insertBefore($icon, $card->firstChild); + $changed = true; + } + + if ($changed) { + $updated = ''; + foreach ($document->getElementsByTagName('body')->item(0)->childNodes as $child) { + $updated .= $document->saveHTML($child); + } + $pdo->prepare("UPDATE sections SET body = ?, version = version + 1 WHERE page_slug = 'pagepan' AND key = 'features'") + ->execute([trim($updated)]); + $pdo->prepare("UPDATE pages SET updated_at = ? WHERE slug = 'pagepan'") + ->execute([(new \DateTimeImmutable('now', new \DateTimeZone('Asia/Shanghai')))->format('Y-m-d H:i:s')]); + } + } +} diff --git a/app/Content/Passwords.php b/app/Content/Passwords.php new file mode 100644 index 0000000..9d7a076 --- /dev/null +++ b/app/Content/Passwords.php @@ -0,0 +1,20 @@ += self::MIN_LENGTH; + } +} diff --git a/app/Content/Repository.php b/app/Content/Repository.php index 2e77dfe..b659317 100644 --- a/app/Content/Repository.php +++ b/app/Content/Repository.php @@ -168,28 +168,36 @@ final class Repository return $this->one('SELECT id, email, password_hash FROM users WHERE id = ?', [$id]); } - public function recordLoginAttempt(string $address): bool + public function changePassword(array $user, string $newHash): bool { - return Database::write(function (PDO $pdo) use ($address): bool { - $now = time(); + $query = $this->pdo->prepare('UPDATE users SET password_hash = ? WHERE id = ? AND password_hash = ?'); + $query->execute([$newHash, $user['id'], $user['password_hash']]); + + return $query->rowCount() === 1; + } + + public function recordFailedLogin(string $address): int + { + $now = time(); + $current = $this->one('SELECT attempts, expires_at FROM login_attempts WHERE address = ?', [$address]); + if ($current && $current['attempts'] >= 12 && $current['expires_at'] > $now) { + return $current['expires_at'] - $now; + } + + return Database::write(function (PDO $pdo) use ($address, $now): int { $pdo->prepare('DELETE FROM login_attempts WHERE expires_at <= ?')->execute([$now]); - $current = $this->one('SELECT attempts FROM login_attempts WHERE address = ?', [$address]); + $current = $this->one('SELECT attempts, expires_at FROM login_attempts WHERE address = ?', [$address]); if ($current && $current['attempts'] >= 12) { - return false; + return $current['expires_at'] - $now; } $query = $pdo->prepare('INSERT INTO login_attempts (address, attempts, expires_at) VALUES (?, 1, ?) ON CONFLICT (address) DO UPDATE SET attempts = attempts + 1'); $query->execute([$address, $now + 900]); - return true; + return 0; }); } - public function clearLoginAttempts(string $address): void - { - $this->pdo->prepare('DELETE FROM login_attempts WHERE address = ?')->execute([$address]); - } - private function one(string $sql, array $args): ?array { $query = $this->pdo->prepare($sql); diff --git a/app/Controller/AdminController.php b/app/Controller/AdminController.php index 117ed2d..eb4fe1f 100644 --- a/app/Controller/AdminController.php +++ b/app/Controller/AdminController.php @@ -4,11 +4,13 @@ declare(strict_types=1); namespace App\Controller; +use App\Content\Database; use App\Content\Html; +use App\Content\Passwords; use App\Content\Repository; use App\Content\View; +use App\Http\Request; use RuntimeException; -use support\Request; use support\Response; final class AdminController @@ -18,41 +20,41 @@ final class AdminController public function login(Request $request): Response { if ($this->signedIn($request)) { - return View::redirect('/admin'); - } - $error = ''; - $email = ''; - $status = 200; - if ($request->method() === 'POST') { - if (!$this->validToken($request)) { - return $this->error($request, '表单已过期,请刷新后重试。', 403); - } - $email = strtolower($this->input($request, 'email')); - $password = $this->input($request, 'password', trimValue: false); - $repo = new Repository(); - $address = $this->address($request); - if (!$repo->recordLoginAttempt($address)) { - $error = '尝试次数过多,请在 15 分钟后重试。'; - $status = 429; - } else { - $user = strlen($email) <= 254 ? $repo->administrator($email) : null; - $hash = $user['password_hash'] ?? '$2y$12$XGNKW.dBbfpUrZT8MYvWquCW1dBN3fIlVb29tlaoFIge3YDWG0AzG'; - if (strlen($password) <= 72 && password_verify($password, $hash) && $user) { - $request->sessionRegenerateId(true); - $request->session()->flush(); - $request->session()->set('admin_id', $user['id']); - $request->session()->set('auth_version', hash('sha256', $user['password_hash'])); - $request->session()->set('admin_since', time()); - $repo->clearLoginAttempts($address); - - return View::redirect('/admin'); - } - $error = '邮箱或密码有误。'; - $status = 422; - } + return $this->success($request, '/admin'); } - return $this->render($request, 'admin-login', ['title' => '登录内容管理', 'error' => $error, 'email' => $email], $status); + $data = ['title' => '登录内容管理', 'error' => '', 'email' => '']; + if ($request->method() !== 'POST') { + return $this->render($request, 'admin-login', $data); + } + + $data['email'] = strtolower($this->input($request, 'email')); + if (!$this->validToken($request)) { + $data['error'] = '登录表单已更新,请重新提交。若反复出现此提示,请确认浏览器允许本站 Cookie。'; + + return $this->render($request, 'admin-login', $data, 403); + } + + $password = $this->input($request, 'password', trimValue: false); + $repo = new Repository(); + $user = strlen($data['email']) <= 254 ? $repo->administrator($data['email']) : null; + $hash = $user['password_hash'] ?? '$2y$12$XGNKW.dBbfpUrZT8MYvWquCW1dBN3fIlVb29tlaoFIge3YDWG0AzG'; + if (Passwords::isSupported($password) && password_verify($password, $hash) && $user) { + $this->openSession($request, $user); + + return $this->success($request, '/admin'); + } + + $retryAfter = $repo->recordFailedLogin($request->clientAddress()); + if ($retryAfter > 0) { + $data['error'] = '当前来源的密码验证失败次数过多,请核对密码或稍后再试。'; + + return $this->render($request, 'admin-login', $data, 429)->withHeader('Retry-After', (string) $retryAfter); + } + + $data['error'] = '邮箱或密码有误。'; + + return $this->render($request, 'admin-login', $data, 422); } public function logout(Request $request): Response @@ -61,9 +63,47 @@ final class AdminController return $failure; } $request->session()->flush(); + $request->session()->save(); $request->sessionRegenerateId(true); - return View::redirect('/admin/login'); + return $this->success($request, '/admin/login'); + } + + public function password(Request $request): Response + { + if ($failure = $this->guard($request)) { + return $failure; + } + + $error = ''; + if ($request->method() === 'POST') { + $current = $this->input($request, 'current_password', trimValue: false); + $password = $this->input($request, 'new_password', trimValue: false); + $confirmation = $this->input($request, 'confirm_password', trimValue: false); + if (!Passwords::isSupported($current) || !password_verify($current, $this->user['password_hash'])) { + $error = '当前密码有误。'; + } elseif (!Passwords::isValidNew($password)) { + $error = '新密码至少 8 个字符,最多 72 字节。'; + } elseif ($password !== $confirmation) { + $error = '两次输入的新密码不一致。'; + } else { + try { + $newHash = password_hash($password, PASSWORD_DEFAULT); + if (!(new Repository())->changePassword($this->user, $newHash)) { + throw new RuntimeException('密码已在其他会话中更新,请重新登录。'); + } + $this->openSession($request, array_replace($this->user, ['password_hash' => $newHash])); + + return $this->success($request, '/admin/password?saved=1'); + } catch (RuntimeException $exception) { + $error = $this->validationMessage($exception); + } + } + } + + return $this->render($request, 'admin-password', [ + 'title' => '修改密码', 'error' => $error, 'saved' => $request->get('saved') === '1', + ], $error !== '' ? 422 : 200); } public function dashboard(Request $request): Response @@ -121,7 +161,7 @@ final class AdminController } $saved = $repo->saveArticle($id === null ? null : (int) $id, $data, $this->version($request)); - return View::redirect('/admin/articles/' . $saved . '?saved=1'); + return $this->success($request, '/admin/articles/' . $saved . '?saved=1'); } catch (RuntimeException $exception) { $error = $this->validationMessage($exception); } @@ -171,7 +211,7 @@ final class AdminController } $repo->savePage($slug, $data, $this->version($request)); - return View::redirect('/admin/pages/' . $slug . '?saved=1'); + return $this->success($request, '/admin/pages/' . $slug . '?saved=1'); } catch (RuntimeException $exception) { $error = $this->validationMessage($exception); } @@ -206,7 +246,7 @@ final class AdminController $data['body'] = Html::sanitize($data['body']); $repo->saveSection($slug, $key, $data, $this->version($request)); - return View::redirect('/admin/pages/' . $slug . '/' . $key . '?saved=1'); + return $this->success($request, '/admin/pages/' . $slug . '/' . $key . '?saved=1'); } catch (RuntimeException $exception) { $error = $this->validationMessage($exception); } @@ -224,7 +264,7 @@ final class AdminController } $body = $this->input($request, 'body'); if (strlen($body) > 300000) { - return new Response(413, ['Cache-Control' => 'no-store'], '正文太长。'); + return $this->error($request, '正文太长。', 413); } $html = $this->input($request, 'format') === 'html' ? Html::sanitize($body) : Html::markdown($body); @@ -237,10 +277,12 @@ final class AdminController private function guard(Request $request): ?Response { if (!$this->signedIn($request)) { - return View::redirect('/admin/login'); + return $request->isAjax() + ? $this->json(['message' => '登录已过期。请在新标签页重新登录,再返回继续编辑。'], 401) + : View::redirect('/admin/login'); } if ($request->method() === 'POST' && !$this->validToken($request)) { - return $this->error($request, '表单已过期,请刷新后重试。', 403); + return $this->error($request, '表单凭证已更新,请重新提交。', 403); } return null; @@ -256,6 +298,7 @@ final class AdminController $user = (new Repository())->administratorById($id); if (!$user || !hash_equals(hash('sha256', $user['password_hash']), (string) $session->get('auth_version'))) { $session->flush(); + $session->save(); return false; } @@ -264,6 +307,19 @@ final class AdminController return true; } + private function openSession(Request $request, array $user): void + { + $request->sessionRegenerateId(true); + $session = $request->session(); + $session->flush(); + $session->put([ + 'admin_id' => $user['id'], + 'auth_version' => hash('sha256', $user['password_hash']), + 'admin_since' => time(), + ]); + $this->token($request); + } + private function token(Request $request): string { $session = $request->session(); @@ -271,6 +327,7 @@ final class AdminController if (!is_string($token)) { $token = bin2hex(random_bytes(32)); $session->set('csrf', $token); + $session->save(); } return $token; @@ -278,7 +335,9 @@ final class AdminController private function validToken(Request $request): bool { - return hash_equals($this->token($request), $this->input($request, 'csrf')); + $token = $request->session()->get('csrf'); + + return is_string($token) && hash_equals($token, $this->input($request, 'csrf')); } private function input(Request $request, string $key, bool $trimValue = true): string @@ -313,15 +372,6 @@ final class AdminController return $data; } - private function address(Request $request): string - { - $peer = $request->getRemoteIp(); - $trusted = explode(',', getenv('LAYSENSE_TRUSTED_PROXIES') ?: ''); - $candidate = $request->header('x-real-ip', ''); - - return in_array($peer, $trusted, true) && filter_var($candidate, FILTER_VALIDATE_IP) ? $candidate : $peer; - } - private function validationMessage(RuntimeException $exception): string { if ($exception instanceof \PDOException) { @@ -333,9 +383,32 @@ final class AdminController return $exception->getMessage(); } + private function success(Request $request, string $path): Response + { + return $request->isAjax() ? $this->json(['redirect' => $path]) : View::redirect($path); + } + + private function json(array $payload, int $status = 200): Response + { + return new Response($status, [ + 'Content-Type' => 'application/json; charset=utf-8', + 'Cache-Control' => 'no-store', + 'X-Content-Type-Options' => 'nosniff', + 'X-Robots-Tag' => 'noindex, nofollow', + ], Database::json($payload)); + } + private function render(Request $request, string $view, array $data, int $status = 200): Response { - return View::render($view, $data + ['token' => $this->token($request), 'user' => $this->user], $status, true); + $token = $this->token($request); + if ($request->isAjax() && $status >= 400) { + return $this->json([ + 'message' => $data['error'] ?? $data['title'], + ...($status === 403 ? ['csrf' => $token] : []), + ], $status); + } + + return View::render($view, $data + ['token' => $token, 'user' => $this->user], $status, true); } private function error(Request $request, string $message, int $status): Response diff --git a/app/Http/Request.php b/app/Http/Request.php new file mode 100644 index 0000000..50310dd --- /dev/null +++ b/app/Http/Request.php @@ -0,0 +1,43 @@ +getRemoteIp(); + $forwarded = $this->header('x-real-ip', ''); + if (!$this->fromTrustedProxy() || !filter_var($forwarded, FILTER_VALIDATE_IP)) { + return $peer; + } + + return inet_ntop(inet_pton($forwarded)); + } + + protected function setSidCookie(string $sessionName, string $sid, array $cookieParams): void + { + $proto = $this->fromTrustedProxy() ? $this->header('x-forwarded-proto', '') : ''; + if ($proto === 'https') { + $cookieParams['secure'] = true; + } elseif (getenv('LAYSENSE_SECURE_COOKIES') === false + && in_array($this->getRemoteIp(), self::LOOPBACK, true) + && in_array(strtolower((string) $this->host(true)), ['localhost', '127.0.0.1', '[::1]', '::1'], true) + && in_array($proto, ['', 'http'], true)) { + $cookieParams['secure'] = false; + } + parent::setSidCookie($sessionName, $sid, $cookieParams); + } + + private function fromTrustedProxy(): bool + { + $configured = getenv('LAYSENSE_TRUSTED_PROXIES'); + $trusted = $configured === false ? self::LOOPBACK : array_map('trim', explode(',', $configured)); + + return in_array($this->getRemoteIp(), $trusted, true); + } +} diff --git a/app/view/admin-layout.php b/app/view/admin-layout.php index 9726c81..d853837 100644 --- a/app/view/admin-layout.php +++ b/app/view/admin-layout.php @@ -13,6 +13,7 @@ $e = View::escape(...); + @@ -24,6 +25,7 @@ $e = View::escape(...);