Fix CMS login and restore PAGEPAN feature icons

This commit is contained in:
2026-11-21 18:47:07 +08:00
parent d9bda755d1
commit 908f9385fb
32 changed files with 519 additions and 156 deletions
+17 -7
View File
@@ -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/` 有写权限。
## 迁移范围
+6
View File
@@ -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);
}
});
}
+1 -1
View File
@@ -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' => [],
+55
View File
@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace App\Content;
use DOMDocument;
use DOMElement;
use DOMXPath;
use PDO;
final class PagepanFeatureIcons
{
public static function migrate(PDO $pdo): void
{
$query = $pdo->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('<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>' . $body . '</body></html>', 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')]);
}
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Content;
final class Passwords
{
public const MIN_LENGTH = 8;
public static function isSupported(string $password): bool
{
return strlen($password) <= 72 && !str_contains($password, "\0") && mb_check_encoding($password, 'UTF-8');
}
public static function isValidNew(string $password): bool
{
return self::isSupported($password) && mb_strlen($password, 'UTF-8') >= self::MIN_LENGTH;
}
}
+18 -10
View File
@@ -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
{
$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
{
return Database::write(function (PDO $pdo) use ($address): bool {
$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);
+118 -45
View File
@@ -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');
return $this->success($request, '/admin');
}
$error = '';
$email = '';
$status = 200;
if ($request->method() === 'POST') {
$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)) {
return $this->error($request, '表单已过期,请刷新后重试。', 403);
$data['error'] = '登录表单已更新,请重新提交。若反复出现此提示,请确认浏览器允许本站 Cookie。';
return $this->render($request, 'admin-login', $data, 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;
$user = strlen($data['email']) <= 254 ? $repo->administrator($data['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);
if (Passwords::isSupported($password) && password_verify($password, $hash) && $user) {
$this->openSession($request, $user);
return View::redirect('/admin');
}
$error = '邮箱或密码有误。';
$status = 422;
}
return $this->success($request, '/admin');
}
return $this->render($request, 'admin-login', ['title' => '登录内容管理', 'error' => $error, 'email' => $email], $status);
$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
+43
View File
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace App\Http;
final class Request extends \support\Request
{
private const LOOPBACK = ['127.0.0.1', '::1'];
public function clientAddress(): string
{
$peer = $this->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);
}
}
+2
View File
@@ -13,6 +13,7 @@ $e = View::escape(...);
<link rel="icon" href="/assets/favicon.png" type="image/png">
<link rel="stylesheet" href="/assets/site.css">
<link rel="stylesheet" href="/assets/admin.css">
<script src="/assets/jquery-4.0.0.min.js" defer></script>
<script src="/assets/admin.js" defer></script>
</head>
<body class="admin-body">
@@ -24,6 +25,7 @@ $e = View::escape(...);
<nav aria-label="后台导航">
<a href="/admin">页面</a>
<a href="/admin/articles">文章</a>
<a href="/admin/password">修改密码</a>
<a href="/">访问网站</a>
<form method="post" action="/admin/logout">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
+1
View File
@@ -13,4 +13,5 @@ $e = View::escape(...);
<label>密码<input name="password" type="password" autocomplete="current-password" required></label>
<button class="button button-primary" type="submit">登录</button>
</form>
<p class="field-note">忘记密码时,可请服务器管理员通过命令行重设。</p>
</div>
+14
View File
@@ -0,0 +1,14 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<header class="admin-heading"><h1><?= $e($title) ?></h1></header>
<?= View::fragment('admin-feedback', compact('error', 'saved')) ?>
<form class="admin-form admin-panel password-form" method="post" action="/admin/password">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<label>当前密码<input name="current_password" type="password" autocomplete="current-password" required></label>
<label>新密码<input name="new_password" type="password" autocomplete="new-password" minlength="8" required><small>至少 8 个字符,最多 72 字节。</small></label>
<label>再次输入新密码<input name="confirm_password" type="password" autocomplete="new-password" minlength="8" required></label>
<div class="form-submit"><button class="button button-primary" type="submit">修改密码</button></div>
</form>
+1
View File
@@ -42,6 +42,7 @@ $nav = [
<meta name="twitter:card" content="summary_large_image">
<link rel="icon" href="/assets/favicon.png" type="image/png">
<link rel="stylesheet" href="/assets/site.css">
<script src="/assets/jquery-4.0.0.min.js" defer></script>
<script src="/assets/site.js" defer></script>
</head>
<body>
+19 -5
View File
@@ -5,14 +5,17 @@ declare(strict_types=1);
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Content\Database;
use App\Content\Passwords;
use App\Content\Repository;
$email = strtolower(trim($argv[1] ?? ''));
$reset = ($argv[1] ?? '') === 'reset';
$email = strtolower(trim($argv[$reset ? 2 : 1] ?? ''));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
fwrite(STDERR, "用法:php bin/admin.php admin@example.com\n");
fwrite(STDERR, "用法:php bin/admin.php [reset] admin@example.com\n");
exit(1);
}
fwrite(STDERR, "请输入至少 12 字符的管理员密码:");
fwrite(STDERR, "请输入至少 8 字符的管理员密码:");
$tty = function_exists('stream_isatty') && stream_isatty(STDIN);
if ($tty) {
exec('stty -echo');
@@ -25,13 +28,24 @@ try {
}
fwrite(STDERR, "\n");
}
if (mb_strlen($password) < 12 || strlen($password) > 72 || str_contains($password, "\0")) {
fwrite(STDERR, "密码需至少 12 字符,并且最多 72 字节。\n");
if (!Passwords::isValidNew($password)) {
fwrite(STDERR, "密码至少 8 个字符,最多 72 字节。\n");
exit(1);
}
Database::initialize();
$hash = password_hash($password, PASSWORD_DEFAULT);
if ($reset) {
$repo = new Repository();
$user = $repo->administrator($email);
if (!$user || !$repo->changePassword($user, $hash)) {
fwrite(STDERR, "未能重设密码。请确认邮箱对应的账户存在,且未被同时修改。\n");
exit(1);
}
fwrite(STDOUT, "密码已重设,旧会话将失效。\n");
exit(0);
}
$query = Database::connect()->prepare('INSERT INTO users (email, password_hash) VALUES (?, ?)
ON CONFLICT (email) DO UPDATE SET password_hash = excluded.password_hash');
$query->execute([$email, $hash]);
+1 -1
View File
@@ -4,7 +4,7 @@ return [
'debug' => false,
'error_reporting' => E_ALL,
'default_timezone' => 'Asia/Shanghai',
'request_class' => support\Request::class,
'request_class' => App\Http\Request::class,
'public_path' => base_path() . '/public',
'runtime_path' => base_path() . '/runtime',
'controller_suffix' => 'Controller',
+1 -1
View File
@@ -6,7 +6,7 @@ return [
'listen' => getenv('LAYSENSE_LISTEN') ?: 'http://127.0.0.1:8787',
'count' => max(1, (int) (getenv('LAYSENSE_WORKERS') ?: 2)),
'constructor' => [
'requestClass' => support\Request::class,
'requestClass' => App\Http\Request::class,
'logger' => support\Log::channel('default'),
'appPath' => app_path(),
'publicPath' => public_path(),
+1
View File
@@ -22,6 +22,7 @@ Route::get('/sitemap.xml', [SiteController::class, 'sitemap']);
Route::add(['GET', 'POST'], '/admin/login', [AdminController::class, 'login']);
Route::post('/admin/logout', [AdminController::class, 'logout']);
Route::add(['GET', 'POST'], '/admin/password', [AdminController::class, 'password']);
Route::get('/admin', [AdminController::class, 'dashboard']);
Route::get('/admin/articles', [AdminController::class, 'articles']);
Route::add(['GET', 'POST'], '/admin/articles/new', [AdminController::class, 'article']);
+4
View File
@@ -49,3 +49,7 @@
.form-grid { grid-template-columns: 1fr; }
.admin-bar nav { gap: .3rem .85rem; }
}
.password-form { max-width: 37rem; }
.admin-form button:disabled, .admin-bar button:disabled { cursor: progress; opacity: .65; }
.admin-form .ajax-feedback { margin: 0; }
+96 -25
View File
@@ -1,5 +1,6 @@
'use strict';
jQuery(function ($) {
const formats = {
markdown: {
heading: ['## ', '', '小标题'],
@@ -15,16 +16,80 @@ const formats = {
}
};
for (const editor of document.querySelectorAll('[data-editor]')) {
const area = editor.querySelector('textarea');
const format = editor.dataset.format;
const preview = editor.querySelector('.editor-preview');
const previewButton = editor.querySelector('[data-preview-button]');
const form = editor.closest('form');
function refreshToken(response) {
if (response?.csrf) {
$('input[name="csrf"]').val(response.csrf);
}
}
for (const button of editor.querySelectorAll('[data-insert]')) {
button.addEventListener('click', () => {
const [before, after, example] = formats[format][button.dataset.insert];
function formError($form, message, status) {
let $feedback = $form.children('.ajax-feedback');
if (!$feedback.length) {
$feedback = $('<p>', {class: 'ajax-feedback feedback error', role: 'alert', tabindex: -1})
.prependTo($form);
}
$feedback.text(message);
if (status === 401) {
$feedback.append(' ', $('<a>', {
href: '/admin/login', target: '_blank', rel: 'noopener', text: '打开登录页'
}));
}
$feedback.prop('hidden', false).trigger('focus');
}
$('form[method="post"]').on('submit', function (event) {
event.preventDefault();
const $form = $(this);
if ($form.attr('aria-busy') === 'true') return;
const action = $form.attr('action');
const isLogin = action === '/admin/login';
const $submit = $form.find(':submit');
$form.attr('aria-busy', 'true').children('.ajax-feedback').prop('hidden', true);
$submit.prop('disabled', true);
function finish() {
$form.removeAttr('aria-busy');
$submit.prop('disabled', false);
}
function submit(canRetryLogin) {
$.ajax({
url: action,
method: 'POST',
data: $form.serialize(),
dataType: 'json'
}).done(function (response) {
if (response.redirect) {
window.location.assign(response.redirect);
return;
}
formError($form, '未收到保存结果,请刷新页面确认。');
finish();
}).fail(function (request) {
const response = request.responseJSON;
refreshToken(response);
if (canRetryLogin && request.status === 403 && response?.csrf) {
submit(false);
return;
}
formError($form, response?.message || '请求未完成,请稍后重试。', request.status);
finish();
});
}
submit(isLogin);
});
$('[data-editor]').each(function () {
const $editor = $(this);
const area = $editor.find('textarea').get(0);
const format = $editor.data('format');
const $preview = $editor.find('.editor-preview');
const $form = $editor.closest('form');
let pendingPreview;
$editor.on('click', '[data-insert]', function () {
const [before, after, example] = formats[format][$(this).data('insert')];
const start = area.selectionStart;
const end = area.selectionEnd;
const selection = area.value.slice(start, end) || example;
@@ -32,24 +97,30 @@ for (const editor of document.querySelectorAll('[data-editor]')) {
area.focus();
area.setSelectionRange(start + before.length, start + before.length + selection.length);
});
}
previewButton.addEventListener('click', async () => {
const show = preview.hidden;
preview.hidden = !show;
previewButton.textContent = show ? '收起预览' : '预览正文';
previewButton.setAttribute('aria-expanded', String(show));
$editor.on('click', '[data-preview-button]', function () {
const $button = $(this);
const show = $preview.prop('hidden');
$preview.prop('hidden', !show);
$button.text(show ? '收起预览' : '预览正文').attr('aria-expanded', String(show));
pendingPreview?.abort();
if (!show) return;
preview.textContent = '正在加载预览…';
try {
const body = new URLSearchParams({body: area.value, format, csrf: form.elements.csrf.value});
const response = await fetch('/admin/preview', {method: 'POST', body, redirect: 'error'});
if (!response.ok) throw new Error('Preview could not be loaded');
const markup = await response.text();
preview.innerHTML = markup;
} catch {
preview.textContent = '预览无法加载,请刷新后重试。';
$preview.text('正在加载预览…');
pendingPreview = $.ajax({
url: '/admin/preview',
method: 'POST',
data: {body: area.value, format, csrf: $form.find('input[name="csrf"]').val()},
dataType: 'text'
}).done((markup) => $preview.html(markup)).fail((request, status) => {
if (status === 'abort') return;
let feedback = request.responseJSON;
if (!feedback && request.getResponseHeader('Content-Type')?.startsWith('application/json')) {
feedback = JSON.parse(request.responseText);
}
refreshToken(feedback);
$preview.text(feedback?.message || '预览无法加载,请重试。');
});
});
});
});
}
File diff suppressed because one or more lines are too long
+20
View File
@@ -0,0 +1,20 @@
Copyright OpenJS Foundation and other contributors, https://openjsf.org/
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+1
View File
@@ -0,0 +1 @@
<svg height="50" viewBox="0 0 1033 1024" width="50" xmlns="http://www.w3.org/2000/svg"><path d="M512 512m-499.2 0a499.2 499.2 0 1 0 998.4 0 499.2 499.2 0 1 0-998.4 0Z" fill="#1989FA" fill-opacity=".3"></path><path d="M13.4144 536.8832A507.4816 507.4816 0 0 1 12.8 512C12.8 236.288 236.288 12.8 512 12.8c134.464 0 256.512 53.1584 346.2656 139.6096-7.1936 13.1328-18.2528 22.8992-28.5696 31.7056-17.1392 14.656-21.12-14.6432-34.3808-62.9888s-113.792-20.736-113.792 0 90.2272 29.6064-2.5984 79.296c-27.84 14.8992-65.1136 16.2176-87.8464 27.648-12.1344 6.0928-6.528 44.1856-14.6176 59.3152-6.272 11.776-26.8288 2.4064-31.68 0-24.8192-12.288-7.8336-80.9472-27.1104-86.9632-26.3168-8.2304-50.2784 27.4304-50.2784 40.64 0 15.0656 22.464 94.72 0 151.0784-24.8832 62.4256-104.5504 120.7936-156.2624 110.2976-98.4064-19.968-122.4448-48.4608-143.7184-19.968-21.2864 28.4928 12.9664 94.976 37.5552 135.6544 24.576 40.6656 2.56 92.2624-24.5888 92.2624-36.544 0-79.7824-46.6816-102.8096-92.2624-11.4048-22.5664-32.7936-49.664-64.1536-81.2416z m466.3936 246.7456c55.8336-38.3232 121.7664-60.6976 185.28-38.3232 63.488 22.3616 85.376 158.2976 31.616 200.0256-53.76 41.728-106.112 14.1696-128.7296 0-22.6176-14.1824-155.9936 14.1696-177.984 0-21.9904-14.1824-45.824-44.0832-45.824-99.776 0-55.68 79.808-23.616 135.6416-61.9264z m-171.392-146.7136c12.288-25.4208 40.64 7.168 57.3056-39.68 16.6656-46.8736 31.616-56.6784 49.344-26.5984 17.7408 30.08 13.376 62.7968 0 82.5344-13.376 19.7248-12.7872 15.5008-48.768 15.5008-35.968 0-70.1952-6.336-57.8944-31.7568zM473.0112 435.2c13.0176 1.3824 19.52 5.824 19.52 13.3504 0 11.2768-9.7536 26.9056-9.7536 26.9056s-27.1616 15.2576-33.28 8.704c-6.0928-6.528 8.1664-22.272 8.1664-35.6096 0-8.896 5.12-13.3504 15.36-13.3504z m24.6016 206.3488c28.9536-16.0512 51.7632-18.6368 68.4032-7.744 24.96 16.3456 87.2448 28.9024 87.2448 36.4928v25.0368c-51.9296-2.9824-85.248-11.328-99.9424-25.0368-22.0416-20.5568-66.9312 9.0368-66.9312 0 0-6.016 3.7376-15.6032 11.2256-28.7488z" fill="#1989FA"></path></svg>

After

Width:  |  Height:  |  Size: 2.0 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 5.8 KiB

+1
View File
@@ -0,0 +1 @@
<svg height="50" viewBox="0 0 1024 1024" width="50" xmlns="http://www.w3.org/2000/svg"><path d="M109.312 228.736H765.44c30.208 0 54.72 24.512 54.72 54.656v468.16H54.656V283.392c0-30.144 24.512-54.656 54.656-54.656z" fill="#A4ADC5"></path><path d="M0 809.6m27.328 0l820.096 0q27.328 0 27.328 27.328l0 61.504q0 27.328-27.328 27.328l-820.096 0q-27.328 0-27.328-27.328l0-61.504q0-27.328 27.328-27.328Z" fill="#A4ADC5"></path><path d="M328 83.52m54.656 0l546.752 0q54.656 0 54.656 54.656l0 413.504q0 54.656-54.656 54.656l-546.752 0q-54.656 0-54.656-54.656l0-413.504q0-54.656 54.656-54.656Z" fill="#08153A"></path><path d="M536.96 244.16a25.6 25.6 0 0 1 4.224 32l-3.2 4.16-60.8 64.576 60.8 64.64a25.6 25.6 0 0 1 2.304 32.256l-3.392 3.904A25.6 25.6 0 0 1 504.64 448l-3.904-3.392-69.12-73.344a38.4 38.4 0 0 1-3.712-48l3.776-4.672 69.056-73.344a25.6 25.6 0 0 1 36.16-1.088zM775.168 244.16a25.6 25.6 0 0 0-4.224 32l3.2 4.16 60.8 64.576-60.8 64.64a25.6 25.6 0 0 0-2.368 32.256l3.392 3.904a25.6 25.6 0 0 0 32.256 2.304l3.968-3.392 69.056-73.344a38.4 38.4 0 0 0 3.712-48l-3.712-4.672-69.12-73.344a25.6 25.6 0 0 0-36.16-1.088zM677.952 243.712a25.6 25.6 0 0 1 47.04 19.648l-2.048 4.8-88.832 163.456a25.6 25.6 0 0 1-46.976-19.648l1.984-4.8 88.832-163.456z" fill="#FFFFFF"></path></svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

+1
View File
@@ -0,0 +1 @@
<svg height="50" viewBox="0 0 1048 1024" width="50" xmlns="http://www.w3.org/2000/svg"><path d="M387.121951 636.878049m-387.121951 0a387.121951 387.121951 0 1 0 774.243902 0 387.121951 387.121951 0 1 0-774.243902 0Z" fill="#FFEFDB"></path><path d="M899.121951 574.439024v224.780488H249.756098V274.731707h212.292682l87.414635 69.931708V0h499.512195v574.439024H899.121951zM437.073171 324.682927H299.707317v424.585366h549.463415V424.585366H561.95122zM999.02439 49.95122H599.414634v324.682926h299.707317v149.853659h99.902439V49.95122z" fill="#040405"></path><path d="M674.341463 299.707317v-49.951219h249.756098v49.951219H674.341463z m0-149.853658h249.756098v49.951219H674.341463v-49.951219z" fill="#FF9E1F"></path></svg>

After

Width:  |  Height:  |  Size: 718 B

+1
View File
@@ -0,0 +1 @@
<svg height="50" viewBox="0 0 1024 1024" width="50" xmlns="http://www.w3.org/2000/svg"><path d="M572.4 584.1m-159.4 0a159.4 159.4 0 1 0 318.8 0 159.4 159.4 0 1 0-318.8 0Z" fill="#FF4C4D"></path><path d="M223.3 743.5l54.5-145.4h199.7l51.9 145.4h61.9L408.6 231.8l-6.8-19.7-41.5-0.6-199.3 532h62.3zM380 325l76.6 214.8h-157L380 325zM869.1 474.2c17 19.2 25.4 45.2 25.4 78v183.6H853v-48.1c-11.4 15.9-26.2 28.8-44.2 38.7-21.8 11.4-45.4 17.1-70.8 17.1-28.8 0-51.6-7.4-68.6-22.1-17.7-15.1-26.6-35.2-26.6-60.3 0-36.5 14.6-63.1 43.7-79.6 23.6-14 55.3-21 95.1-21l68.6-0.6v-9.4c0-47.9-24.9-71.9-74.7-71.9-23.2 0-41.3 4.8-54.2 14.4-14.4 10-23.2 24.7-26.5 44.2h-43.7c4.4-32.8 18.4-57.1 42-73 20.6-14.7 49-22.1 85.2-22.1 40.7 0 70.9 10.7 90.8 32.1z m-18.8 120.5l-65.8 0.6c-64.1 0-96.2 21.8-96.2 65.3 0 14 5.2 25.4 15.5 34.3 10.7 8.5 25.2 12.7 43.7 12.7 28.8 0 53.3-8.9 73.6-26.6 19.5-17.7 29.3-38.2 29.3-61.4v-24.9z"></path></svg>

After

Width:  |  Height:  |  Size: 915 B

@@ -0,0 +1 @@
<svg height="50" viewBox="0 0 1024 1024" width="50" xmlns="http://www.w3.org/2000/svg"><path d="M311.224 428.616V40.96C186.696 93.99 87.406 195.29 36.936 321.096l274.286 274.286 0.002-166.766z" fill="#AFE164"></path><path d="M428.616 311.22L702.904 36.936C643.84 13.164 579.474 0 512 0c-71.314 0-139.154 14.628-200.776 40.96v387.656L428.616 311.22z" fill="#D7E664"></path><path d="M983.04 311.22H595.384l117.394 117.396 274.286 274.286C1010.836 643.84 1024 579.474 1024 512c0-71.314-14.628-139.154-40.96-200.78z" fill="#FFAA64"></path><path d="M712.776 595.384V983.04c124.526-53.03 223.816-154.33 274.286-280.136L712.776 428.616v166.768z" fill="#FF6469"></path><path d="M595.384 712.776L321.096 987.064C380.16 1010.834 444.526 1024 512 1024c71.316 0 139.154-14.628 200.776-40.96V595.384L595.384 712.776z" fill="#C3B4FA"></path><path d="M428.616 712.776H40.96c53.03 124.526 154.33 223.816 280.136 274.286l274.286-274.286H428.616z" fill="#7DD2F0"></path><path d="M311.224 595.384L36.936 321.096C13.164 380.16 0 444.526 0 512c0 71.314 14.628 139.154 40.96 200.776h387.656L311.224 595.384z" fill="#7DE6C3"></path><path d="M595.384 311.22H983.04C930.01 186.696 828.71 87.404 702.904 36.936L428.616 311.22h166.768z" fill="#FFE669"></path></svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

@@ -0,0 +1 @@
<svg height="50" viewBox="0 0 1024 1024" width="50" xmlns="http://www.w3.org/2000/svg"><path d="M891.2 948.8l-33.6-96H699.2l-33.6 96H564.8l153.6-403.2h115.2l153.6 403.2h-96zM780.8 632l-57.6 148.8h115.2L780.8 632zM526.4 780.8L569.6 680c-14.4-9.6-28.8-19.2-38.4-28.8 72-81.6 129.6-182.4 172.8-302.4h129.6v-96H468.8l72-24c-9.6-33.6-33.6-86.4-57.6-129.6l-105.6 33.6c19.2 38.4 38.4 86.4 48 120H70.4v96h134.4c43.2 120 105.6 220.8 177.6 302.4C296 718.4 185.6 766.4 56 800c19.2 24 48 72 62.4 96 134.4-38.4 249.6-96 340.8-172.8 19.2 19.2 43.2 38.4 67.2 57.6z m-220.8-432h288C560 440 512 516.8 454.4 584 392 516.8 339.2 440 305.6 348.8z"></path></svg>

After

Width:  |  Height:  |  Size: 642 B

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 6.0 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 5.0 KiB

+20 -25
View File
@@ -1,31 +1,23 @@
'use strict';
const toggle = document.querySelector('.menu-toggle');
const nav = document.querySelector('.primary-nav');
if (toggle && nav) {
toggle.hidden = false;
nav.classList.add('has-toggle');
jQuery(function ($) {
const $toggle = $('.menu-toggle');
const $nav = $('.primary-nav');
if ($toggle.length && $nav.length) {
$toggle.prop('hidden', false);
$nav.addClass('has-toggle');
const closeMenu = () => {
toggle.setAttribute('aria-expanded', 'false');
nav.classList.remove('is-open');
const setMenu = (open) => {
$toggle.attr('aria-expanded', String(open));
$nav.toggleClass('is-open', open);
};
toggle.addEventListener('click', () => {
const open = toggle.getAttribute('aria-expanded') === 'true';
if (open) {
closeMenu();
} else {
toggle.setAttribute('aria-expanded', 'true');
nav.classList.add('is-open');
}
});
nav.addEventListener('click', closeMenu);
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && toggle.getAttribute('aria-expanded') === 'true') {
closeMenu();
toggle.focus();
$toggle.on('click', () => setMenu($toggle.attr('aria-expanded') !== 'true'));
$nav.on('click', 'a', () => setMenu(false));
$(document).on('keydown', (event) => {
if (event.key === 'Escape' && $toggle.attr('aria-expanded') === 'true') {
setMenu(false);
$toggle.trigger('focus');
}
});
}
@@ -34,11 +26,14 @@ if ('IntersectionObserver' in window && !matchMedia('(prefers-reduced-motion: re
const observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
if (entry.isIntersecting) {
entry.target.classList.add('moment-active');
$(entry.target).addClass('moment-active');
observer.unobserve(entry.target);
}
}
}, {threshold: 0.35});
document.querySelectorAll('[data-moment]').forEach((section) => observer.observe(section));
$('[data-moment]').each(function () {
observer.observe(this);
});
}
});
+11
View File
@@ -0,0 +1,11 @@
{
"字体管理器": "/assets/original/pagepan/fonts.svg",
"文件管理器": "/assets/original/pagepan/files.svg",
"代码编辑器": "/assets/original/pagepan/code.svg",
"COS、CDN": "/assets/original/pagepan/cdn.svg",
"Sitemap一键生成": "/assets/original/pagepan/sitemap.svg",
"All for SEO": "/assets/original/pagepan/seo.svg",
"动态组件(CMS)": "/assets/original/pagepan/cms.svg",
"渐变色调色器": "/assets/original/pagepan/gradient.svg",
"多语言支持": "/assets/original/pagepan/languages.svg"
}
+3
View File
@@ -58,3 +58,6 @@ CREATE TABLE IF NOT EXISTS login_attempts (
attempts INTEGER NOT NULL,
expires_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS schema_migrations (
name TEXT PRIMARY KEY
);