From 584455c66d6f8728cc39b2e097e408985048d932 Mon Sep 17 00:00:00 2001 From: ChatGPT Date: Mon, 23 Nov 2026 18:52:26 +0800 Subject: [PATCH] Fix design validation, canonical routes, media headers and favicon --- app/Content/Assets.php | 2 + app/Content/DesignFieldError.php | 15 +++++++ app/Content/DesignLibrary.php | 40 ++++++++++--------- app/Content/OAuthCredentials.php | 2 +- app/Content/PageDraft.php | 2 +- app/Content/SiteBackup.php | 2 +- app/Controller/AdminController.php | 1 + app/Controller/DesignController.php | 30 ++++++++++---- app/Controller/MediaController.php | 13 +++--- app/Controller/SiteController.php | 16 ++++++-- app/Controller/StudioController.php | 3 +- app/view/admin-design-edit.php | 62 ++++++++++++++++++----------- app/view/admin-layout.php | 3 +- app/view/layout.php | 1 + app/view/studio-asset-field.php | 2 +- config/route.php | 1 + public/assets/admin.css | 2 + public/assets/admin.js | 21 +++++++++- 18 files changed, 153 insertions(+), 65 deletions(-) create mode 100644 app/Content/DesignFieldError.php diff --git a/app/Content/Assets.php b/app/Content/Assets.php index 6e49b49..73bfc7c 100644 --- a/app/Content/Assets.php +++ b/app/Content/Assets.php @@ -8,6 +8,8 @@ use RuntimeException; final class Assets { + public const DEFAULT_ICON = '/assets/system/laysite-mark.webp'; + public static function cdn(string $value): string { $value = rtrim(trim($value), '/'); diff --git a/app/Content/DesignFieldError.php b/app/Content/DesignFieldError.php new file mode 100644 index 0000000..c7536dc --- /dev/null +++ b/app/Content/DesignFieldError.php @@ -0,0 +1,15 @@ + [, $default]) { $color = $data[$key] ?? $default; if (!is_string($color) || !preg_match('/^#[\da-f]{6}$/iD', $color)) { - throw new RuntimeException('颜色必须使用六位十六进制表示。'); + throw new DesignFieldError($key, '颜色必须使用六位十六进制表示。'); } $colors[$key] = strtolower($color); } @@ -110,23 +110,27 @@ final class DesignLibrary $clean = self::defaults($kind); foreach (['brand' => 100, 'text' => 1200, 'legal' => 300, 'logo' => 1000] as $field => $limit) { - $clean[$field] = self::string($data[$field] ?? '', $limit); + $clean[$field] = self::string($data[$field] ?? '', $limit, $field); } if ($clean['logo'] !== '' && !Html::url($clean['logo'], true)) { - throw new RuntimeException('请检查站点标识地址。'); + throw new DesignFieldError('logo', '请检查站点标识地址。'); } $components = $data['components'] ?? $clean['components']; if (!is_array($components) || !array_is_list($components)) { - throw new RuntimeException('组件顺序无效。'); + throw new DesignFieldError('components', '组件顺序无效。'); } foreach ($components as $component) { if (!is_string($component) || !isset(self::COMPONENTS[$kind][$component])) { - throw new RuntimeException('布局包含未知组件。'); + throw new DesignFieldError('components', '布局包含未知组件。'); } } $clean['components'] = array_values(array_unique($components)); $clean['links'] = Buttons::validate($data['links'] ?? $clean['links'], 20); - $clean['action'] = Buttons::validate($data['action'] ?? []); + try { + $clean['action'] = Buttons::validate($data['action'] ?? []); + } catch (RuntimeException $error) { + throw new DesignFieldError('action', $error->getMessage()); + } $clean['provider'] = $kind === 'header' && $preset === 'member' ? self::provider($data['provider'] ?? []) : []; @@ -140,27 +144,27 @@ final class DesignLibrary return []; } if (!in_array($mode, ['oidc', 'oauth2'], true)) { - throw new RuntimeException('请选择 OIDC 或 OAuth 2.0。'); + throw new DesignFieldError('provider_mode', '请选择 OIDC 或 OAuth 2.0。'); } $result = ['mode' => $mode]; foreach (['client_id', 'scope', 'issuer', 'authorization', 'token', 'userinfo', 'subject_field', 'name_field', 'avatar_field', 'token_auth'] as $field) { - $result[$field] = self::string($data[$field] ?? '', 600); + $result[$field] = self::string($data[$field] ?? '', 600, 'provider_' . $field); } if (!in_array($result['token_auth'], ['', 'client_secret_basic', 'client_secret_post'], true)) { - throw new RuntimeException('令牌端点认证方式无效。'); + throw new DesignFieldError('provider_token_auth', '令牌端点认证方式无效。'); } if ($result['client_id'] === '') { - throw new RuntimeException('请填写客户端 ID。'); + throw new DesignFieldError('provider_client_id', '请填写客户端 ID。'); } foreach ($mode === 'oidc' ? ['issuer'] : ['authorization', 'token', 'userinfo'] as $field) { $url = parse_url($result[$field]); if (!$url || ($url['scheme'] ?? '') !== 'https' || empty($url['host']) || isset($url['user']) || isset($url['pass']) || isset($url['fragment']) || ($field === 'issuer' && isset($url['query'])) || !Html::url($result[$field], true)) { - throw new RuntimeException('认证端点必须使用完整的 HTTPS 地址。'); + throw new DesignFieldError('provider_' . $field, '认证端点必须使用完整的 HTTPS 地址。'); } } if ($mode === 'oauth2' && $result['subject_field'] === '') { - throw new RuntimeException('OAuth 2.0 用户资料需要指定稳定的用户 ID 字段。'); + throw new DesignFieldError('provider_subject_field', 'OAuth 2.0 用户资料需要指定稳定的用户 ID 字段。'); } return $result; @@ -183,9 +187,9 @@ final class DesignLibrary public static function save(string $kind, ?int $id, string $name, string $preset, array $data, int $version, bool $default, string $secret = ''): int { - $name = self::string($name, 100); + $name = self::string($name, 100, 'name'); if ($name === '') { - throw new RuntimeException('请填写配置名称。'); + throw new DesignFieldError('name', '请填写配置名称。'); } $clean = self::normalize($kind, $preset, $data); $payload = Database::json($clean); @@ -198,7 +202,7 @@ final class DesignLibrary $fields = array_flip(['mode', 'issuer', 'authorization', 'token', 'userinfo', 'client_id']); if (empty($saved['credential_revision']) || array_intersect_key($provider, $fields) !== array_intersect_key($saved['payload']['provider'], $fields)) { - throw new RuntimeException('启用登录或变更身份提供商时,请填写客户端密钥。'); + throw new DesignFieldError('provider_secret', '启用登录或变更身份提供商时,请填写客户端密钥。'); } } if ($id === null) { @@ -232,10 +236,10 @@ final class DesignLibrary }); } - private static function string(mixed $value, int $limit): string + private static function string(mixed $value, int $limit, string $field): string { if (!is_string($value) || !mb_check_encoding($value, 'UTF-8') || mb_strlen($value) > $limit) { - throw new RuntimeException('配置包含无效或过长的文字。'); + throw new DesignFieldError($field, '配置包含无效或过长的文字。'); } return trim($value); diff --git a/app/Content/OAuthCredentials.php b/app/Content/OAuthCredentials.php index ba3f43b..3bcde84 100644 --- a/app/Content/OAuthCredentials.php +++ b/app/Content/OAuthCredentials.php @@ -18,7 +18,7 @@ final class OAuthCredentials public static function store(PDO $pdo, int $layout, string $secret): void { if ($secret === '' || strlen($secret) > 4096 || str_contains($secret, "\0")) { - throw new RuntimeException('客户端密钥为空或格式无效。'); + throw new DesignFieldError('provider_secret', '客户端密钥为空或格式无效。'); } $revision = bin2hex(random_bytes(16)); $nonce = random_bytes(self::NONCE_BYTES); diff --git a/app/Content/PageDraft.php b/app/Content/PageDraft.php index f8f01da..347cb9c 100644 --- a/app/Content/PageDraft.php +++ b/app/Content/PageDraft.php @@ -8,7 +8,7 @@ use RuntimeException; final class PageDraft { - public const RESERVED = ['admin', 'assets', 'home', 'account', 'mcp', 'palette', 'favicon']; + public const RESERVED = ['admin', 'assets', 'home', 'account', 'mcp', 'palette']; public static function slug(mixed $value, array $reserved = self::RESERVED): string { diff --git a/app/Content/SiteBackup.php b/app/Content/SiteBackup.php index 823b9e7..dcf35e0 100644 --- a/app/Content/SiteBackup.php +++ b/app/Content/SiteBackup.php @@ -179,7 +179,7 @@ final class SiteBackup } $tables['site_settings'] = [['id' => 1, 'payload' => Database::json($site)]]; foreach ($tables['pages'] as &$row) { - PageDraft::slug($row['slug'] ?? null, ['admin', 'assets', 'account', 'mcp', 'palette', 'favicon']); + PageDraft::slug($row['slug'] ?? null, array_diff(PageDraft::RESERVED, ['home'])); self::validateAssetUrl($row['image'] ?? '', true); $row['actions'] = Database::json(Buttons::validate(self::decode($row['actions'] ?? '[]'))); $row['quicklinks'] = Database::json(Buttons::validate(self::decode($row['quicklinks'] ?? '[]'), 20)); diff --git a/app/Controller/AdminController.php b/app/Controller/AdminController.php index 3e1f7b7..ce7d97c 100644 --- a/app/Controller/AdminController.php +++ b/app/Controller/AdminController.php @@ -648,6 +648,7 @@ class AdminController if ($request->isAjax() && $status >= 400) { return $this->json([ 'message' => $data['error'] ?? $data['title'], + ...(!empty($data['field']) ? ['field' => $data['field']] : []), ...($status === 403 ? ['csrf' => $token] : []), ], $status); } diff --git a/app/Controller/DesignController.php b/app/Controller/DesignController.php index 1b5b38c..8570e3d 100644 --- a/app/Controller/DesignController.php +++ b/app/Controller/DesignController.php @@ -5,7 +5,7 @@ declare(strict_types=1); namespace App\Controller; use App\Content\Assets; -use App\Content\Buttons; +use App\Content\DesignFieldError; use App\Content\DesignLibrary; use App\Content\Repository; use App\Content\SiteDesign; @@ -40,13 +40,17 @@ final class DesignController extends AdminController return $this->error($request, '找不到这项设计配置。', 404); } $error = ''; + $field = ''; + $secret = ''; + $links = SiteDesign::linkText($item['payload']['links'] ?? []); $default = $id !== null && ((new Repository())->site()[$kind . '_id'] ?? null) === $id; if ($request->method() === 'POST') { try { $savedProvider = $item['payload']['provider'] ?? []; - $secret = ''; $item['name'] = $this->input($request, 'name'); $item['preset'] = $this->input($request, 'preset'); + $item['version'] = $this->version($request); + $default = $request->post('make_default') === '1'; if ($kind === 'palette') { foreach (DesignLibrary::COLORS as $color => $definition) { $item['payload'][$color] = $this->input($request, $color); @@ -54,11 +58,11 @@ final class DesignController extends AdminController } else { $url = $this->input($request, 'action_url'); $label = $this->input($request, 'action_label'); + $links = $this->input($request, 'links', trimValue: false); $item['payload'] = [ 'components' => $request->post('components', []), 'brand' => $this->input($request, 'brand'), 'logo' => $this->input($request, 'logo'), 'text' => $this->input($request, 'text'), 'legal' => $this->input($request, 'legal'), - 'links' => SiteDesign::parseLinks($this->input($request, 'links')), 'action' => $url === '' && $label === '' ? [] : [[$url, $label, $this->input($request, 'action_style'), $request->post('action_blank') === '1']], 'provider' => $savedProvider, ]; @@ -69,20 +73,32 @@ final class DesignController extends AdminController } $secret = $this->input($request, 'provider_secret', trimValue: false); } + try { + $item['payload']['links'] = SiteDesign::parseLinks($links); + } catch (RuntimeException $ex) { + throw new DesignFieldError('links', $ex->getMessage()); + } } - $default = $request->post('make_default') === '1'; - $id = DesignLibrary::save($kind, $id, $item['name'], $item['preset'], $item['payload'], $this->version($request), $default, $secret); + $id = DesignLibrary::save($kind, $id, $item['name'], $item['preset'], $item['payload'], $item['version'], $default, $secret); return $this->success($request, "/admin/design/$kind/$id?saved=1"); } catch (RuntimeException $ex) { $error = $this->validationMessage($ex); - $item['payload'] = DesignLibrary::defaults($kind); + $field = $ex instanceof DesignFieldError ? $ex->field : ''; } } + if ($kind !== 'palette') { + $components = $item['payload']['components']; + $item['payload']['components'] = is_array($components) ? array_values(array_intersect( + array_filter($components, 'is_string'), array_keys(DesignLibrary::COMPONENTS[$kind]) + )) : []; + } + return $this->render($request, 'admin-design-edit', [ 'title' => '设计配置', 'kind' => $kind, 'key' => $key, 'item' => $item, 'default' => $default, - 'error' => $error, 'saved' => $request->get('saved') === '1', + 'error' => $error, 'field' => $field, 'links' => $links, 'reenterSecret' => $error !== '' && $secret !== '', + 'saved' => $error === '' && $request->get('saved') === '1', ], $error === '' ? 200 : 422); } diff --git a/app/Controller/MediaController.php b/app/Controller/MediaController.php index 0ebb7c4..5a583b7 100644 --- a/app/Controller/MediaController.php +++ b/app/Controller/MediaController.php @@ -23,23 +23,22 @@ final class MediaController 'Content-Type' => $media['mime'], 'X-Content-Type-Options' => 'nosniff', 'Content-Security-Policy' => "default-src 'none'; sandbox", 'Cache-Control' => 'public, max-age=31536000, immutable', - 'Access-Control-Allow-Origin' => '*', 'Accept-Ranges' => 'bytes', + 'Access-Control-Allow-Origin' => '*', ]; $range = $request->header('range'); if ($range === null) { - return (new Response(200, $headers + ['Content-Length' => (string) $length]))->withFile($path); + return (new Response(200, $headers))->withFile($path); } + $unsatisfiable = $headers + ['Accept-Ranges' => 'bytes', 'Content-Range' => "bytes */$length"]; if (!preg_match('/^bytes=(\d*)-(\d*)$/D', $range, $parts) || $parts[1] === '' && $parts[2] === '') { - return new Response(416, $headers + ['Content-Range' => "bytes */$length"]); + return new Response(416, $unsatisfiable); } $start = $parts[1] === '' ? max(0, $length - (int) $parts[2]) : (int) $parts[1]; $end = $parts[1] === '' || $parts[2] === '' ? $length - 1 : min($length - 1, (int) $parts[2]); if ($end < $start) { - return new Response(416, $headers + ['Content-Range' => "bytes */$length"]); + return new Response(416, $unsatisfiable); } - $count = $end - $start + 1; - return (new Response(206, $headers + ['Content-Length' => (string) $count, 'Content-Range' => "bytes $start-$end/$length"])) - ->withFile($path, $start, $count); + return (new Response(206, $headers))->withFile($path, $start, $end - $start + 1); } } diff --git a/app/Controller/SiteController.php b/app/Controller/SiteController.php index 88f335e..abb1b30 100644 --- a/app/Controller/SiteController.php +++ b/app/Controller/SiteController.php @@ -4,11 +4,14 @@ declare(strict_types=1); namespace App\Controller; +use App\Content\Assets; use App\Content\Html; use App\Content\Repository; use App\Content\View; +use FastRoute\Dispatcher; use support\Request; use support\Response; +use Webman\Route; final class SiteController { @@ -215,14 +218,21 @@ final class SiteController "User-agent: *\nAllow: /\nDisallow: /admin\nSitemap: " . View::absolute('/sitemap.xml') . "\n"); } + public function favicon(Request $request): Response + { + return View::redirect(Assets::DEFAULT_ICON, 301); + } + public function missing(Request $request): Response { $path = $request->path(); - if ($request->method() === 'GET' && strlen($path) > 1 && str_ends_with($path, '/')) { + if (in_array($request->method(), ['GET', 'HEAD'], true) && strlen($path) > 1 && str_ends_with($path, '/')) { $normal = rtrim($path, '/'); + $entry = preg_match('~^/(?:admin|account)(?:/|$)~D', $normal) + && Route::dispatch($request->method(), $normal)[0] === Dispatcher::FOUND; $single = preg_match('~^/[a-z0-9-]+$~D', $normal); - $known = $single && ((new Repository())->page(substr($normal, 1))['status'] ?? null) === 'published' && $normal !== '/home'; - if ($known || preg_match('~^/articles(?:/[a-z0-9-]+){1,2}$~D', $normal)) { + if ($entry || ($single && $normal !== '/home' && ((new Repository())->page(substr($normal, 1))['status'] ?? null) === 'published') + || preg_match('~^/articles(?:/[a-z0-9-]+){1,2}$~D', $normal)) { $query = $request->queryString(); return View::redirect($normal . ($query !== '' ? '?' . $query : ''), 301); diff --git a/app/Controller/StudioController.php b/app/Controller/StudioController.php index 0eebfd5..9723fd9 100644 --- a/app/Controller/StudioController.php +++ b/app/Controller/StudioController.php @@ -7,6 +7,7 @@ namespace App\Controller; use App\Content\BlockTemplates; use App\Content\Html; use App\Content\Media; +use App\Content\PageDraft; use App\Content\PageTemplates; use App\Content\Repository; use App\Http\Request; @@ -29,7 +30,7 @@ final class StudioController extends AdminController $data['name'] = $this->input($request, 'name'); $data['slug'] = $this->input($request, 'slug'); try { - if (!$this->slug($data['slug']) || in_array($data['slug'], ['admin', 'assets', 'home', 'account', 'mcp', 'palette', 'favicon'], true) + if (!$this->slug($data['slug']) || in_array($data['slug'], PageDraft::RESERVED, true) || $data['name'] === '' || mb_strlen($data['name']) > 100) { throw new RuntimeException('请填写页面名称及可用的网址标识。'); } diff --git a/app/view/admin-design-edit.php b/app/view/admin-design-edit.php index 00a873d..6cbf1fb 100644 --- a/app/view/admin-design-edit.php +++ b/app/view/admin-design-edit.php @@ -1,84 +1,100 @@ 'design-error-' . View::escape($name); +$describe = static fn (string $name): string => ' aria-describedby="' . $errorId($name) . '"' + . ($field === $name ? ' aria-invalid="true"' : ''); +$fieldError = static function (string $name) use ($errorId, $field, $error, $e): void { + $invalid = $field === $name; + ?> + > + 返回站点设计

'页头组件', 'footer' => '页脚组件', 'palette' => '配色方案'][$kind]) ?>

预览已保存的配置
- + $field === '' ? $error : '', 'saved' => $saved]) ?>
- - + +
[$label, $fallback]): ?> - +
-
组件及顺序 +
>组件及顺序
+
- - 'logo', 'label' => '品牌图片', 'value' => $data['logo']]) ?> + +
+ 'logo', 'label' => '品牌图片', 'value' => $data['logo'], + 'describedBy' => $errorId('logo'), 'invalid' => $field === 'logo']) ?> + +
- + -
行动按钮 +
>行动按钮 +
>用户区认证 - - + + - - - - '授权端点', 'token' => '令牌端点', 'userinfo' => '用户资料端点', 'subject_field' => '用户 ID 字段', 'name_field' => '名称字段', 'avatar_field' => '头像字段'] as $field => $label): ?> - + + + + '授权端点', 'token' => '令牌端点', 'userinfo' => '用户资料端点', 'subject_field' => '用户 ID 字段', 'name_field' => '名称字段', 'avatar_field' => '头像字段'] as $providerField => $label): ?> +

回调地址

- - + + diff --git a/app/view/admin-layout.php b/app/view/admin-layout.php index 4c1ab63..1a64dda 100644 --- a/app/view/admin-layout.php +++ b/app/view/admin-layout.php @@ -1,4 +1,5 @@ - + <?= $e($title) ?> CMS diff --git a/app/view/layout.php b/app/view/layout.php index 3875253..4662545 100644 --- a/app/view/layout.php +++ b/app/view/layout.php @@ -20,6 +20,7 @@ $showFooter = $page['visibility']['footer'] ?? true; <?= $e($title) ?> + diff --git a/app/view/studio-asset-field.php b/app/view/studio-asset-field.php index bd6f12e..e340d95 100644 --- a/app/view/studio-asset-field.php +++ b/app/view/studio-asset-field.php @@ -4,6 +4,6 @@ use App\Content\View; $e = View::escape(...); ?>
- +
diff --git a/config/route.php b/config/route.php index 420e454..b8cf1b6 100644 --- a/config/route.php +++ b/config/route.php @@ -25,6 +25,7 @@ Route::get('/articles/feed/{slug:[a-z0-9-]+}/{key:[a-z0-9-]+}', [SiteController: Route::get('/articles/{slug:[a-z0-9-]+}', [SiteController::class, 'article']); Route::get('/robots.txt', [SiteController::class, 'robots']); Route::get('/sitemap.xml', [SiteController::class, 'sitemap']); +Route::get('/favicon.ico', [SiteController::class, 'favicon']); Route::add(['GET', 'POST'], '/admin/login', [AdminController::class, 'login']); Route::post('/admin/logout', [AdminController::class, 'logout']); diff --git a/public/assets/admin.css b/public/assets/admin.css index 19f5d5f..9aeba19 100644 --- a/public/assets/admin.css +++ b/public/assets/admin.css @@ -28,6 +28,8 @@ } .admin-form textarea { resize: vertical; } .admin-form small, .field-note { color: var(--muted); font-size: .875rem; font-weight: 400; } +.admin-form .design-field-error { color: #9c252a; grid-column: 1 / -1; } +.admin-form [aria-invalid=true] { border-color: #9c252a; } .form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: .85rem; } .form-submit { display: flex; flex-wrap: wrap; gap: .75rem; align-items: end; } .form-submit label { min-width: 10rem; } diff --git a/public/assets/admin.js b/public/assets/admin.js index ea715ed..9db89e1 100644 --- a/public/assets/admin.js +++ b/public/assets/admin.js @@ -93,6 +93,21 @@ jQuery(function ($) { $feedback.prop('hidden', false).trigger('focus'); } + function designFieldError($form, response) { + if (!response?.field) return false; + const $feedback = $form.find('[data-field-error]').filter(function () { + return this.dataset.fieldError === response.field; + }); + $feedback.text(response.message).prop('hidden', false); + if (!$feedback.is(':visible')) return false; + + $form.find('[aria-describedby]').filter(function () { + return this.getAttribute('aria-describedby') === $feedback.attr('id'); + }).attr('aria-invalid', 'true'); + $feedback.trigger('focus'); + return true; + } + document.addEventListener('invalid', (event) => { if (event.target.form?.method.toLowerCase() === 'post') clearSavedStatus(); }, true); @@ -109,6 +124,8 @@ jQuery(function ($) { const $submit = $form.find(':submit:enabled'); const multipart = $form.attr('enctype') === 'multipart/form-data'; $form.attr('aria-busy', 'true').children('.ajax-feedback').prop('hidden', true); + $form.find('[data-field-error]').text('').prop('hidden', true); + $form.find('[aria-describedby^="design-error-"]').removeAttr('aria-invalid'); $submit.prop('disabled', true); $form.triggerHandler('studio:busy', [true]); @@ -148,7 +165,9 @@ jQuery(function ($) { return; } finish(); - formError($form, response?.message || '请求未完成,请稍后重试。', request.status); + if (!designFieldError($form, response)) { + formError($form, response?.message || '请求未完成,请稍后重试。', request.status); + } }); } -- 2.52.0