diff --git a/.gitea/workflows/release-container.yml b/.gitea/workflows/release-container.yml index 78bf981..926acb4 100644 --- a/.gitea/workflows/release-container.yml +++ b/.gitea/workflows/release-container.yml @@ -4,9 +4,12 @@ on: release: types: [published] +permissions: + releases: read + jobs: container: - if: ${{ gitea.repository == 'laysense/laysite' && !gitea.event.release.prerelease }} + if: ${{ gitea.repository == 'laysense/laysite' }} runs-on: host timeout-minutes: 30 steps: @@ -14,10 +17,33 @@ jobs: shell: bash env: RELEASE_TAG: ${{ gitea.event.release.tag_name }} + RELEASE_API_TOKEN: ${{ secrets.GITEA_TOKEN }} PACKAGE_USERNAME: ${{ secrets.PACKAGE_USERNAME }} PACKAGE_TOKEN: ${{ secrets.PACKAGE_TOKEN }} run: | set -euo pipefail + : "${RELEASE_TAG:?The release event did not specify a tag.}" + : "${RELEASE_API_TOKEN:?The job did not receive GITEA_TOKEN.}" + registry=git.laysense.com + source_url="https://$registry/laysense/laysite" + encoded_tag="$(python3 -c 'import sys, urllib.parse; print(urllib.parse.quote(sys.argv[1], safe=""))' "$RELEASE_TAG")" + release_json="$(printf 'Authorization: token %s\n' "$RELEASE_API_TOKEN" \ + | curl --fail --silent --show-error --max-time 30 --header @- \ + "https://$registry/api/v1/repos/laysense/laysite/releases/tags/$encoded_tag")" + release_type="$(printf '%s' "$release_json" | python3 -c ' + import json, sys + release = json.load(sys.stdin) + if release.get("tag_name") != sys.argv[1] or release.get("draft") is not False: + sys.exit("The release tag does not match a published release.") + prerelease = release.get("prerelease") + if not isinstance(prerelease, bool): + sys.exit("The release API did not report its prerelease status.") + print("prerelease" if prerelease else "stable") + ' "$RELEASE_TAG")" + if [ "$release_type" = 'prerelease' ]; then + echo 'Skipping the container build for a prerelease.' + exit 0 + fi if ! printf '%s\n' "$RELEASE_TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$'; then echo 'The release tag must use vMAJOR.MINOR.PATCH.' >&2 exit 1 @@ -30,12 +56,16 @@ jobs: export DOCKER_CONFIG="$work/docker" mkdir -m 700 "$DOCKER_CONFIG" - registry=git.laysense.com - source_url="https://$registry/laysense/laysite" image="$registry/laysense/laysite:$RELEASE_TAG" git init --quiet "$work/source" - git -C "$work/source" fetch --quiet --depth 1 "$source_url.git" "refs/tags/$RELEASE_TAG" - git -C "$work/source" checkout --quiet --detach FETCH_HEAD + git -C "$work/source" fetch --quiet --no-tags "$source_url.git" \ + refs/heads/main:refs/remotes/origin/main "refs/tags/$RELEASE_TAG:refs/tags/$RELEASE_TAG" + release_commit="$(git -C "$work/source" rev-parse "refs/tags/$RELEASE_TAG^{commit}")" + if ! git -C "$work/source" merge-base --is-ancestor "$release_commit" refs/remotes/origin/main; then + echo 'The release tag must point to a commit on main.' >&2 + exit 1 + fi + git -C "$work/source" checkout --quiet --detach "$release_commit" if [ "$(cat "$work/source/VERSION")" != "${RELEASE_TAG#v}" ]; then echo 'VERSION in the release commit must match the tag.' >&2 exit 1 @@ -44,20 +74,31 @@ jobs: docker build --pull --tag "$image" \ --label "org.opencontainers.image.source=$source_url" \ --label "org.opencontainers.image.version=${RELEASE_TAG#v}" \ - --label "org.opencontainers.image.revision=$(git -C "$work/source" rev-parse HEAD)" \ + --label "org.opencontainers.image.revision=$release_commit" \ "$work/source" printf '%s' "$PACKAGE_TOKEN" | docker login "$registry" --username "$PACKAGE_USERNAME" --password-stdin docker push "$image" package_url="https://$registry/api/v1/packages/laysense/container/laysite" package_api() { printf 'Authorization: token %s\n' "$PACKAGE_TOKEN" \ - | curl --fail --silent --show-error --header @- "$@" + | curl --fail --silent --show-error --max-time 30 --header @- "$@" } linked_repository() { - package_api "$package_url/$RELEASE_TAG" | python3 -c \ + local response + response="$(package_api "$package_url/$RELEASE_TAG")" || return 1 + printf '%s' "$response" | python3 -c \ 'import json, sys; print((json.load(sys.stdin).get("repository") or {}).get("full_name", ""))' } - linked_repo="$(linked_repository)" + wait_for_package() { + local attempt + for attempt in 1 2 3 4; do + if linked_repository; then return 0; fi + if [ "$attempt" -lt 4 ]; then sleep 2; fi + done + echo 'The uploaded package is not visible in the API yet.' >&2 + return 1 + } + linked_repo="$(wait_for_package)" if [ -z "$linked_repo" ]; then if ! package_api --request POST "$package_url/-/link/laysite"; then [ "$(linked_repository)" = 'laysense/laysite' ] || exit 1 diff --git a/README.md b/README.md index e89ac2f..28396f5 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ php start.php start ``` -保存后,画布与独立预览都会加载样式。自定义脚本在独立预览和公开页面运行,独立预览中的脚本与后台会话隔离。以站点权限运行的脚本应来自可信来源。站点备份包含图标、Head 代码和上传的资源。 +保存后,画布与独立预览都会加载样式。自定义脚本在独立预览和公开页面运行。启用自定义脚本后,独立预览会隔离 Cookie,并禁用表单提交和会员登录。内联脚本早于 LaySite 的 jQuery 执行。如需使用 jQuery,请用带 `defer` 的外部脚本,或在内联脚本中等待 `DOMContentLoaded`。站点备份包含图标、Head 代码和上传的资源。 ### 维护页与 404 页 @@ -164,9 +164,9 @@ docker run -d --name laysite --restart unless-stopped \ docker exec -it laysite php bin/admin.php admin@example.com ``` -示例由宿主机上的反向代理终止 HTTPS。容器以 UID/GID 10001 运行。使用宿主机目录代替命名卷时,请让该用户可写入挂载目录。升级时以新标签重建容器,并挂载同一个数据卷。 +示例由宿主机上的反向代理终止 HTTPS。容器以 UID/GID 10001 运行。使用宿主机目录代替命名卷时,请让该用户可写入挂载目录。升级时以新标签重建容器,并挂载同一个数据卷。默认的 `runtime/` 存放会话、日志和缓存,重建后管理员需要重新登录。如需保留这些数据,也可挂载 `/opt/laysite/runtime`。 -Gitea Actions 使用 `host` 标签。runner 的运行账户需要访问 Docker,并可调用 Git、curl 和 Python 3。发布前在仓库「设置 → Actions → Secrets」配置 `PACKAGE_USERNAME` 和 `PACKAGE_TOKEN`。令牌需要 `write:package` 权限,账号也须能向 `laysense` 发布包并关联 LaySite 仓库。工作流以 Release 标签检出源码,确认 `VERSION` 一致后构建、上传镜像并关联仓库。镜像会显示在 LaySite 的 Packages 页。 +Gitea Actions 使用 `host` 标签。runner 的运行账户需要访问 Docker,并可调用 Git、curl 和 Python 3。内置 `GITEA_TOKEN` 使用 `releases: read` 读取 Release 元数据。OCI 推送使用仓库 Actions Secrets 中的 `PACKAGE_USERNAME` 和 `PACKAGE_TOKEN`。PAT 需要 `write:package`,所属账号须能向 `laysense` 发布包并关联 LaySite 仓库。工作流只发布正式 Release,核对标签指向 `main` 历史中的提交且与 `VERSION` 一致。镜像会显示在 LaySite 仓库的 Packages 页。[Gitea Actions 令牌权限](https://docs.gitea.com/usage/actions/token-permissions/) · [OCI 发布的权限限制](https://docs.gitea.com/usage/actions/comparison/#package-repository-authorization) ## 生产反代 diff --git a/app/Content/Database.php b/app/Content/Database.php index 75770fb..358b23f 100644 --- a/app/Content/Database.php +++ b/app/Content/Database.php @@ -11,6 +11,7 @@ use Throwable; final class Database { + public const MIGRATION_REQUIRED = '数据库尚未完成升级。请在站点目录运行 php bin/install.php。'; private const SCHEMA_VERSION = 8; // Avoid reusing a deleted ID that may still be open in an editing form. public const NEXT_ARTICLE_ID = 'MAX(COALESCE((SELECT MAX(id) FROM articles), 0), diff --git a/app/Content/McpSettings.php b/app/Content/McpSettings.php index 2d77d32..4156eac 100644 --- a/app/Content/McpSettings.php +++ b/app/Content/McpSettings.php @@ -6,6 +6,7 @@ namespace App\Content; use App\Config\Environment; use PDO; +use PDOException; use RuntimeException; final class McpSettings @@ -16,10 +17,13 @@ final class McpSettings public static function read(): array { $row = self::stored(Database::connect()); - if ($row === null) { - $token = self::legacyToken(); + $migrationRequired = $row === false; + $keyError = ''; + if (!is_array($row)) { + $token = $migrationRequired ? null : self::legacyToken(); - return ['enabled' => $token !== null, 'version' => 0, 'token' => $token, 'legacy' => $token !== null]; + return ['enabled' => $token !== null, 'version' => 0, 'legacy' => $token !== null] + + compact('token', 'migrationRequired', 'keyError'); } $enabled = (bool) $row['enabled']; @@ -27,12 +31,14 @@ final class McpSettings if ($enabled && $row['encrypted_secret'] !== null) { try { $token = SiteSecrets::decrypt($row['encrypted_secret'], self::CONTEXT); + } catch (SiteKeyFileError $error) { + $keyError = $error->getMessage(); } catch (RuntimeException) { // Keep the settings accessible so an administrator can replace an unreadable key. } } - return ['enabled' => $enabled, 'version' => (int) $row['version'], 'token' => $token, 'legacy' => false]; + return ['version' => (int) $row['version'], 'legacy' => false] + compact('enabled', 'token', 'migrationRequired', 'keyError'); } public static function save(bool $enabled, bool $rotate, int $version): void @@ -42,6 +48,9 @@ final class McpSettings } Database::write(static function (PDO $pdo) use ($enabled, $rotate, $version): void { $row = self::stored($pdo); + if ($row === false) { + throw new RuntimeException(Database::MIGRATION_REQUIRED); + } if ($version !== (int) ($row['version'] ?? 0)) { throw new RuntimeException('MCP 设置已更新,请刷新后再保存。'); } @@ -58,9 +67,16 @@ final class McpSettings }); } - private static function stored(PDO $pdo): ?array + private static function stored(PDO $pdo): array|false|null { - return $pdo->query('SELECT enabled, encrypted_secret, version FROM mcp_settings WHERE id = 1')->fetch() ?: null; + try { + return $pdo->query('SELECT enabled, encrypted_secret, version FROM mcp_settings WHERE id = 1')->fetch() ?: null; + } catch (PDOException $error) { + if (($error->errorInfo[2] ?? '') === 'no such table: mcp_settings') { + return false; + } + throw $error; + } } private static function legacyToken(): ?string diff --git a/app/Content/PageHead.php b/app/Content/PageHead.php index 5df5c3a..bf996ad 100644 --- a/app/Content/PageHead.php +++ b/app/Content/PageHead.php @@ -38,7 +38,9 @@ final class PageHead continue; } if ($tag === 'script') { - $result['hasScript'] = true; + if (strtolower($attributes['type'] ?? '') !== 'application/ld+json') { + $result['hasScript'] = true; + } if (!isset($attributes['src'])) { $result['inlineScript'] = true; $attributes['nonce'] = $nonce; @@ -83,8 +85,11 @@ final class PageHead || ($node->nodeType === XML_TEXT_NODE && trim($node->textContent) === '')) { continue; } - if (!$node instanceof DOMElement || !isset(self::ATTRIBUTES[$node->tagName]) || count($entries) >= 40) { - throw new RuntimeException('Head 最多支持 40 个 meta、样式表、style 或 script 标签。'); + if (!$node instanceof DOMElement || !isset(self::ATTRIBUTES[$node->tagName])) { + throw new RuntimeException('Head 仅支持 meta、样式表(link)、style 和 script 标签。'); + } + if (count($entries) >= 40) { + throw new RuntimeException('Head 最多允许 40 个标签。'); } $tag = $node->tagName; $attributes = []; diff --git a/app/Content/Repository.php b/app/Content/Repository.php index 87d0fa8..909e2f6 100644 --- a/app/Content/Repository.php +++ b/app/Content/Repository.php @@ -132,14 +132,17 @@ final class Repository public function savePage(string $slug, array $data, int $version, array $sections = [], bool $replaceDraftSections = false, ?array $sectionOrder = null): void { Database::write(function (PDO $pdo) use ($slug, $data, $version, $sections, $replaceDraftSections, $sectionOrder): void { + $head = $data['head_html'] ?? null; $query = $pdo->prepare('UPDATE pages SET name = ?, title = ?, description = ?, heading = ?, accent = ?, lead = ?, image = ?, alt = ?, image_scale = ?, alignments = ?, actions = ?, quicklinks = ?, visibility = ?, header_id = ?, footer_id = ?, palette_id = ?, status = ?, updated_at = ?, - presentation = COALESCE(?, presentation), head_html = COALESCE(?, head_html), version = version + 1 WHERE slug = ? AND version = ?'); + presentation = COALESCE(?, presentation), ' . ($head === null ? '' : 'head_html = ?, ') + . 'version = version + 1 WHERE slug = ? AND version = ?'); $query->execute([ $data['name'], $data['title'], $data['description'], $data['heading'], $data['accent'], $data['lead'], $data['image'], $data['alt'], $data['image_scale'], Database::json($data['alignments']), Database::json($data['actions']), Database::json($data['quicklinks']), Database::json($data['visibility']), $data['header_id'], $data['footer_id'], $data['palette_id'], $data['status'], self::now(), - isset($data['presentation']) ? CanvasStyle::encode($data['presentation']) : null, $data['head_html'] ?? null, $slug, $version, + isset($data['presentation']) ? CanvasStyle::encode($data['presentation']) : null, + ...($head === null ? [] : [$head]), $slug, $version, ]); self::checkVersion($query->rowCount()); if ($data['status'] === 'draft' && str_starts_with($slug, 'system--')) { diff --git a/app/Content/SiteKeyFileError.php b/app/Content/SiteKeyFileError.php new file mode 100644 index 0000000..0223323 --- /dev/null +++ b/app/Content/SiteKeyFileError.php @@ -0,0 +1,9 @@ +method() === 'POST') { $data = []; @@ -348,6 +349,9 @@ class AdminController } try { if ($head !== null) { + if (!$headEditor) { + throw new RuntimeException(Database::MIGRATION_REQUIRED); + } $data['head_html'] = PageHead::normalize($head); } $data['actions'] = $request->post('hero_actions') === null ? $page['actions'] @@ -426,7 +430,7 @@ class AdminController return $this->render($request, 'admin-page', [ 'title' => '编辑 ' . $page['name'], 'page' => $page, 'categories' => $repo->categories(), 'wideAdmin' => true, 'canvasSourceEditor' => true, 'error' => $error, 'saved' => $request->get('saved') === '1', - 'pageTemplateDrawer' => !$layout, 'headEditor' => !$layout, 'designs' => DesignLibrary::all(), 'layout' => $layout, 'layoutDefault' => $default, + 'pageTemplateDrawer' => !$layout, 'headEditor' => $headEditor, 'designs' => DesignLibrary::all(), 'layout' => $layout, 'layoutDefault' => $default, 'layoutBase' => $layout && ($site['layout_defaults'][$layoutKind] ?? null) === $layout['id'], 'siteName' => $site['name'], 'layoutHasMember' => $layoutKind === 'header' && LayoutPage::hasMember($page['sections']), 'layoutDefaults' => array_intersect_key($site, ['header_id' => true, 'footer_id' => true]), diff --git a/app/Controller/McpController.php b/app/Controller/McpController.php index 7dd4d25..26b7ce1 100644 --- a/app/Controller/McpController.php +++ b/app/Controller/McpController.php @@ -34,7 +34,7 @@ final class McpController return new Response(503, ['Cache-Control' => 'no-store']); } $secret = $settings['token']; - if ($settings['enabled'] && $secret === null) { + if ($settings['migrationRequired'] || ($settings['enabled'] && $secret === null)) { return new Response(503, ['Cache-Control' => 'no-store']); } $header = $request->header('authorization', ''); diff --git a/app/view/admin-page.php b/app/view/admin-page.php index 83ae7fd..a8ce216 100644 --- a/app/view/admin-page.php +++ b/app/view/admin-page.php @@ -70,8 +70,8 @@ $spacingPresets = [0, 4, 8, 12, 16, 24, 32, 48, 64, 96, 128];
@@ -134,8 +134,8 @@ $spacingPresets = [0, 4, 8, 12, 16, 24, 32, 48, 64, 96, 128];
(px)
- 默认 @@ -146,6 +146,7 @@ $spacingPresets = [0, 4, 8, 12, 16, 24, 32, 48, 64, 96, 128];
+
@@ -281,8 +282,10 @@ $spacingPresets = [0, 4, 8, 12, 16, 24, 32, 48, 64, 96, 128]; - + '本页 Head', 'head' => $page['head_html']]) ?> + +

本页 Head 尚不可用。

diff --git a/app/view/head-settings.php b/app/view/head-settings.php index ad9288c..6100936 100644 --- a/app/view/head-settings.php +++ b/app/view/head-settings.php @@ -12,6 +12,8 @@ $e = View::escape(...);

可添加 meta、样式表、style 和 script。全站代码先加载,本页代码随后加载。保存后,画布载入样式,脚本在独立预览和公开页面运行。

+

需要使用 jQuery 时,请插入带 defer 的外部脚本,或让内联脚本等待 DOMContentLoaded。

+
diff --git a/app/view/studio-settings.php b/app/view/studio-settings.php index 80d0eac..ee01e13 100644 --- a/app/view/studio-settings.php +++ b/app/view/studio-settings.php @@ -1,4 +1,5 @@ "> - +

允许持有密钥的 AI 客户端通过 Streamable HTTP 新建和编辑草稿。

+ + + - - + + + +
查看连接密钥 - +

在客户端设置 Authorization 请求头,格式为 Bearer 后加一个空格和密钥。

@@ -55,8 +61,8 @@ $e = View::escape(...);

当前密钥来自环境变量 LAYSITE_MCP_TOKEN。保存后由后台管理。

- - + +
diff --git a/public/assets/admin.css b/public/assets/admin.css index 70eea71..e101edb 100644 --- a/public/assets/admin.css +++ b/public/assets/admin.css @@ -113,7 +113,7 @@ .canvas-font-combo { gap: 0; } .canvas-font-combo input { border-start-end-radius: 0; border-end-end-radius: 0; } .canvas-font-combo select { - appearance: none; text-align: center; width: 2.15rem; min-height: 2.45rem; padding: 0; + width: 3.1rem; min-height: 2.45rem; padding: 0 .15rem; color: var(--ink); background: var(--white); border: 1px solid var(--line); border-inline-start: 0; border-start-end-radius: .35rem; border-end-end-radius: .35rem; cursor: pointer; } @@ -446,6 +446,7 @@ :is(.canvas-source, .head-settings) .CodeMirror-focused { outline: 2px solid var(--accent); outline-offset: 1px; } .head-settings-fields { display: grid; gap: .65rem; margin-block-start: .6rem; } .head-settings .CodeMirror { height: clamp(13rem, 38vh, 22rem); margin: 0; } +.mcp-token { font-family: var(--mono); } .favicon-editor-row { display: flex; flex-wrap: wrap; gap: 1rem; align-items: center; } .favicon-preview { display: grid; place-items: center; inline-size: 6rem; block-size: 6rem; diff --git a/public/assets/head-editor.js b/public/assets/head-editor.js index 4183ec1..3aeacdd 100644 --- a/public/assets/head-editor.js +++ b/public/assets/head-editor.js @@ -4,6 +4,15 @@ jQuery(function ($) { $('[data-head-settings]').each(function () { const $details = $(this); const source = $details.find('[data-head-source]').get(0); + const $limit = $details.find('[data-head-limit]'); + const encoder = new TextEncoder(); + const size = (value) => encoder.encode(value).length; + function fits(current, removed, added) { + const original = size(current); + const next = original - size(removed) + size(added); + $limit.prop('hidden', next <= source.maxLength); + return next <= source.maxLength || next < original; + } let editor; $details.on('toggle', () => { if (!this.open || !window.CodeMirror) return; @@ -12,6 +21,9 @@ jQuery(function ($) { mode: 'htmlmixed', lineNumbers: true, lineWrapping: true, indentUnit: 2, tabSize: 2, }); editor.getInputField().setAttribute('aria-labelledby', 'head-source-label'); + editor.on('beforeChange', (cm, change) => { + if (!fits(cm.getValue(), cm.getRange(change.from, change.to), change.text.join('\n'))) change.cancel(); + }); editor.on('change', () => editor.save()); } editor.refresh(); @@ -26,7 +38,7 @@ jQuery(function ($) { if (editor) { editor.replaceSelection(value); editor.focus(); - } else { + } else if (fits(source.value, source.value.slice(source.selectionStart, source.selectionEnd), value)) { source.setRangeText(value, source.selectionStart, source.selectionEnd, 'end'); source.focus(); } diff --git a/public/assets/studio.js b/public/assets/studio.js index 0c02a32..0dc9ea6 100644 --- a/public/assets/studio.js +++ b/public/assets/studio.js @@ -753,8 +753,13 @@ jQuery(function ($) { const target = doc && formatTarget(); $format.add($fontSize).add($fontPreset).prop('disabled', !target); const sample = target && (selectedText()[0]?.node || target); - const computed = sample ? doc.defaultView.getComputedStyle(sample.nodeType === 1 ? sample : sample.parentElement) : null; - if (!$fontSize.is(':focus')) $fontSize.val(computed ? Math.round(parseFloat(computed.fontSize)) : ''); + const element = sample?.nodeType === 1 ? sample : sample?.parentElement; + const computed = element ? doc.defaultView.getComputedStyle(element) : null; + const sizeClass = element && classesOf(element).size; + const size = sizeClass ? sizeClass.slice('studio-style-size-'.length) + : (computed ? String(Math.round(parseFloat(computed.fontSize))) : ''); + if (!$fontSize.is(':focus')) $fontSize.val(size); + $fontPreset.val($fontPreset.find('option').toArray().some((option) => option.value === size) ? size : ''); $color.add($clearColor).prop('disabled', !target); const rgb = computed?.color.match(/^rgba?\((\d+), (\d+), (\d+)(?:, [\d.]+)?\)$/); if (rgb && !$color.is(':focus')) $color.val('#' + rgb.slice(1).map((channel) => Number(channel).toString(16).padStart(2, '0')).join('')); @@ -815,7 +820,6 @@ jQuery(function ($) { $format.on('click', function () { applyTextStyle(this.dataset.canvasFormat); }); $fontPreset.on('change', function () { applyTextStyle('size', this.value); - this.value = ''; }); $fontSize.on('change', function () { if (this.validity.valid) applyTextStyle('size', this.value === '' ? '' : String(this.valueAsNumber)); @@ -833,7 +837,7 @@ jQuery(function ($) { const presets = $preset.data('spacingPreset'); const index = same && values[0] !== '' ? presets.indexOf(Number(values[0])) : -1; const label = !same ? '自定义' : (values[0] === '' ? '默认' : values[0] + ' px'); - $preset.val(index === -1 ? $preset.prop('defaultValue') : index).attr('aria-valuetext', label); + $preset.val(index).attr('aria-valuetext', label); $fields.find('[data-spacing-readout]').text(label); } @@ -850,7 +854,7 @@ jQuery(function ($) { $spacingForm.on('input', '[data-spacing-preset]', function () { const $preset = $(this); const $fields = $preset.closest('fieldset'); - $fields.find('[data-spacing-side]').val($preset.data('spacingPreset')[this.valueAsNumber]); + $fields.find('[data-spacing-side]').val($preset.data('spacingPreset')[this.valueAsNumber] ?? ''); syncSpacingPreset($fields); }).on('input', '[data-spacing-side]', function () { syncSpacingPreset($(this).closest('fieldset'));