feat: 静态资源与前端 Markdown、浏览量、Gitea 同步内容

- 将 Markdown/KaTeX/高亮/Mermaid 移至 public 与 CDN,减小 Worker 体积
- 文章列表:标题、简介、时间与浏览量;访问文章时递增 view_count
- 新增 migrations/0003 与 blog 路由等配置
- 加入 public 资源与站点图标

Made-with: Cursor
This commit is contained in:
2026-04-14 14:07:46 +08:00
parent 276a7fbc83
commit 323869e6ca
9 changed files with 499 additions and 157 deletions

BIN
favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

BIN
logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 MiB

View File

@@ -0,0 +1 @@
ALTER TABLE posts ADD COLUMN view_count INTEGER NOT NULL DEFAULT 0;

127
public/css/markdown.css Normal file
View File

@@ -0,0 +1,127 @@
.markdown-body {
overflow-wrap: break-word;
}
.markdown-body > *:first-child {
margin-top: 0;
}
.markdown-body > *:last-child {
margin-bottom: 0;
}
.markdown-body h1 {
font-size: 1.75rem;
margin: 24px 0 12px;
}
.markdown-body h2 {
font-size: 1.45rem;
margin: 22px 0 10px;
}
.markdown-body h3 {
font-size: 1.2rem;
margin: 18px 0 8px;
}
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
font-size: 1.05rem;
margin: 16px 0 8px;
}
.markdown-body p {
margin: 0 0 12px;
}
.markdown-body ul,
.markdown-body ol {
margin: 0 0 12px;
padding-left: 1.6em;
}
.markdown-body li {
margin: 0 0 4px;
}
.markdown-body li > p {
margin: 0 0 6px;
}
.markdown-body blockquote {
border-left: 4px solid #ccc;
margin: 0 0 16px;
padding: 2px 0 2px 16px;
color: #444;
}
.markdown-body blockquote > :last-child {
margin-bottom: 0;
}
.markdown-body pre {
padding: 0;
margin: 0 0 16px;
border-radius: 6px;
overflow-x: auto;
font-size: 0.9em;
background: #f6f8fa;
}
.markdown-body pre code.hljs {
display: block;
padding: 12px 14px;
overflow-x: auto;
background: transparent;
}
.markdown-body code {
font-family: ui-monospace, "Cascadia Code", "Source Code Pro", Menlo, Consolas, monospace;
font-size: 0.9em;
}
.markdown-body pre code {
background: none;
padding: 0;
font-size: inherit;
}
.markdown-body :not(pre) > code {
background: #f0f0f0;
padding: 2px 6px;
border-radius: 4px;
}
.markdown-body table {
border-collapse: collapse;
width: 100%;
margin: 0 0 16px;
font-size: 0.95em;
}
.markdown-body th,
.markdown-body td {
border: 1px solid #ccc;
padding: 8px 10px;
vertical-align: top;
}
.markdown-body th {
background: #f5f5f5;
font-weight: 600;
}
.markdown-body hr {
margin: 20px 0;
}
.markdown-body a {
text-decoration: underline;
}
.markdown-body li:has(> input[type="checkbox"]) {
list-style: none;
margin-left: -1.5em;
padding-left: 0;
}
.markdown-body input[type="checkbox"] {
margin-right: 6px;
vertical-align: middle;
}
.markdown-body .katex-display {
overflow-x: auto;
overflow-y: hidden;
max-width: 100%;
padding: 8px 0;
}
.markdown-body .katex {
max-width: 100%;
}
.markdown-body .mermaid {
margin: 16px 0;
overflow-x: auto;
text-align: center;
}
.markdown-pending .markdown-loading {
color: #666;
margin: 0;
}

BIN
public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

View File

@@ -0,0 +1,96 @@
import { marked } from "https://esm.sh/marked@15";
import markedKatex from "https://esm.sh/marked-katex-extension@5?deps=marked@15,katex@0.16";
import hljs from "https://esm.sh/highlight.js@11";
import mermaid from "https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs";
marked.use(
markedKatex({
throwOnError: false,
nonStandard: true
})
);
marked.setOptions({ gfm: true, breaks: false });
function decodeHtmlEntities(str) {
return String(str)
.replace(/ /g, "\u00a0")
.replace(/&/g, "&")
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&quot;/g, '"')
.replace(/&#39;/g, "'")
.replace(/&#(\d+);/g, (_, n) => {
const code = Number(n);
return code >= 0 && code <= 0x10ffff ? String.fromCharCode(code) : "";
})
.replace(/&#x([0-9a-fA-F]+);/g, (_, h) => {
const code = parseInt(h, 16);
return code >= 0 && code <= 0x10ffff ? String.fromCharCode(code) : "";
});
}
function escapeHtml(s) {
return String(s)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
}
function mermaidFencedToDiv(html) {
return html.replace(
/<pre><code class="language-mermaid">([\s\S]*?)<\/code><\/pre>/gi,
(_, inner) => {
const raw = decodeHtmlEntities(inner);
return `<div class="mermaid">${escapeHtml(raw)}</div>`;
}
);
}
function decodeMdFromB64(b64) {
return decodeURIComponent(escape(atob(b64)));
}
async function renderOne(el) {
const b64 = el.getAttribute("data-b64-md");
if (!b64) return;
let md;
try {
md = decodeMdFromB64(b64);
} catch {
el.innerHTML = "<p>正文解码失败。</p>";
el.classList.remove("markdown-pending");
return;
}
el.removeAttribute("data-b64-md");
let html = marked.parse(md, { async: false });
if (typeof html !== "string") html = "";
html = mermaidFencedToDiv(html);
el.innerHTML = html;
el.classList.remove("markdown-pending");
el.querySelectorAll("pre code").forEach((block) => {
try {
hljs.highlightElement(block);
} catch {
/* ignore unknown languages */
}
});
const mNodes = el.querySelectorAll(".mermaid");
if (mNodes.length) {
mermaid.initialize({ startOnLoad: false, theme: "neutral" });
await mermaid.run({ nodes: mNodes });
}
}
function run() {
document.querySelectorAll(".markdown-body[data-b64-md]").forEach((el) => {
renderOne(el).catch(() => {
el.innerHTML = "<p>渲染失败。</p>";
el.classList.remove("markdown-pending");
});
});
}
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", run);
else run();

BIN
public/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 MiB

425
worker.js
View File

@@ -9,7 +9,7 @@ export default {
return htmlResponse(renderLayout("配置缺失", `
<h1>DB 绑定未配置</h1>
<p>请先在 <code>wrangler.toml</code> 里配置 D1 数据库。</p>
`), 500);
`, env), 500);
}
if (request.method === "OPTIONS") {
@@ -17,6 +17,10 @@ export default {
}
try {
if (path === "/admin/session" && request.method === "POST") {
return await handleAdminSession(request, env);
}
if (request.method === "GET") {
if (path === "/") return await handleIndex(env, url);
if (path.startsWith("/post/")) return await handlePost(env, path.slice(6));
@@ -45,12 +49,12 @@ export default {
if (request.method === "DELETE") return await handleApiDelete(request, env, idOrSlug);
}
return notFoundPage();
return notFoundPage(env);
} catch (error) {
return htmlResponse(renderLayout("错误", `
<h1>发生错误</h1>
<pre>${escapeHtml(error?.stack || error?.message || String(error))}</pre>
`), 500);
`, env), 500);
}
}
};
@@ -59,13 +63,9 @@ async function handleIndex(env, url) {
const q = (url.searchParams.get("q") || "").trim();
const posts = await listPosts(env.DB, { publishedOnly: true, q });
return htmlResponse(renderLayout(pageTitle(env, "首页"), `
<header>
<h1>${escapeHtml(pageTitle(env))}</h1>
<p><a href="/admin">后台</a></p>
</header>
${q ? `<p>搜索:<strong>${escapeHtml(q)}</strong></p>` : ""}
${posts.length ? posts.map(renderPostCard).join("") : "<p>暂无文章。</p>"}
`));
`, env));
}
async function handlePost(env, slug) {
@@ -73,20 +73,25 @@ async function handlePost(env, slug) {
"SELECT * FROM posts WHERE slug = ? AND published = 1 LIMIT 1"
).bind(decodeURIComponent(slug)).first();
if (!post) return notFoundPage();
if (!post) return notFoundPage(env);
await env.DB.prepare(
"UPDATE posts SET view_count = COALESCE(view_count, 0) + 1 WHERE id = ?"
).bind(post.id).run();
const views = (Number(post.view_count) || 0) + 1;
return htmlResponse(renderLayout(`${post.title} - ${pageTitle(env)}`, `
<p><a href="/">返回首页</a></p>
<article>
<h1>${escapeHtml(post.title)}</h1>
<p>${formatDateTime(post.updated_at)}</p>
<div>${renderMarkdown(post.content)}</div>
<p class="post-detail-meta"><span class="post-detail-time">${formatDateTime(post.updated_at)}</span><span class="post-detail-views">浏览 ${views}</span></p>
${markdownPlaceholder(post.content)}
</article>
`));
`, env, { markdownPage: true }));
}
async function handleAdminPage(request, env, url, path) {
const auth = requireAdmin(request, env);
const auth = await requireAdmin(request, env);
if (auth) return auth;
let post = blankPost();
@@ -143,11 +148,11 @@ async function handleAdminPage(request, env, url, path) {
</form>
${posts.length ? posts.map(renderAdminCard).join("") : "<p>没有找到文章。</p>"}
</section>
`));
`, env));
}
async function handleAdminSave(request, env, url) {
const auth = requireAdmin(request, env);
const auth = await requireAdmin(request, env);
if (auth) return auth;
const data = await readBody(request);
@@ -163,7 +168,7 @@ async function handleAdminSave(request, env, url) {
return htmlResponse(renderLayout("表单错误", `
<h1>标题和内容不能为空</h1>
<p><a href="/admin">返回后台</a></p>
`), 400);
`, env), 400);
}
const slug = await uniqueSlug(env.DB, slugify(slugBase), id);
@@ -171,7 +176,7 @@ async function handleAdminSave(request, env, url) {
if (id) {
const exists = await getPostById(env.DB, id);
if (!exists) return notFoundPage();
if (!exists) return notFoundPage(env);
await env.DB.prepare(`
UPDATE posts
SET title = ?, slug = ?, excerpt = ?, content = ?, published = ?, updated_at = ?
@@ -189,7 +194,7 @@ async function handleAdminSave(request, env, url) {
}
async function handleAdminDelete(request, env, url) {
const auth = requireAdmin(request, env);
const auth = await requireAdmin(request, env);
if (auth) return auth;
const data = await readBody(request);
@@ -198,13 +203,36 @@ async function handleAdminDelete(request, env, url) {
return htmlResponse(renderLayout("表单错误", `
<h1>无效的文章 ID</h1>
<p><a href="/admin">返回后台</a></p>
`), 400);
`, env), 400);
}
await env.DB.prepare("DELETE FROM posts WHERE id = ?").bind(id).run();
return Response.redirect(new URL(`/admin?deleted=1`, url), 303);
}
async function handleAdminSession(request, env) {
const password = cleanText(env.ADMIN_PASSWORD);
if (!password) {
return jsonResponse({ ok: false, error: "not_configured" }, 503);
}
const data = await readBody(request);
const token = cleanText(data.token);
if (token !== password) {
return jsonResponse({ ok: false, error: "invalid" }, 401);
}
const value = await adminSessionCookieValue(env);
const maxAge = 60 * 60 * 24 * 7;
const secure = new URL(request.url).protocol === "https:";
const parts = [`sb_admin=${value}`, "Path=/", "HttpOnly", "SameSite=Lax", `Max-Age=${maxAge}`];
if (secure) parts.push("Secure");
return jsonResponse({ ok: true }, 200, {
"Set-Cookie": parts.join("; ")
});
}
async function handleApiList(env, url) {
const q = (url.searchParams.get("q") || "").trim();
const posts = await listPosts(env.DB, { publishedOnly: false, q });
@@ -218,7 +246,7 @@ async function handleApiRead(env, idOrSlug) {
}
async function handleApiCreate(request, env) {
const auth = requireAdmin(request, env);
const auth = await requireAdmin(request, env);
if (auth) return auth;
const data = await readBody(request);
@@ -227,7 +255,7 @@ async function handleApiCreate(request, env) {
}
async function handleApiUpdate(request, env, idOrSlug) {
const auth = requireAdmin(request, env);
const auth = await requireAdmin(request, env);
if (auth) return auth;
const data = await readBody(request);
@@ -238,7 +266,7 @@ async function handleApiUpdate(request, env, idOrSlug) {
}
async function handleApiDelete(request, env, idOrSlug) {
const auth = requireAdmin(request, env);
const auth = await requireAdmin(request, env);
if (auth) return auth;
const post = await readPost(env.DB, idOrSlug);
@@ -336,11 +364,12 @@ function slugify(value) {
function renderPostCard(post) {
const excerpt = post.excerpt || stripMarkdown(post.content).slice(0, 180);
const views = Number(post.view_count) || 0;
return `
<article>
<article class="post-card">
<h2><a href="/post/${encodeURIComponent(post.slug)}">${escapeHtml(post.title)}</a></h2>
<p>${formatDateTime(post.updated_at)}</p>
<p>${escapeHtml(excerpt)}${excerpt.length >= 180 ? "…" : ""}</p>
<p class="post-excerpt">${escapeHtml(excerpt)}${excerpt.length >= 180 ? "…" : ""}</p>
<p class="post-meta"><span class="post-card-time">${formatDateTime(post.updated_at)}</span><span class="post-card-views">浏览 ${views}</span></p>
</article>
`;
}
@@ -361,18 +390,75 @@ function renderAdminCard(post) {
`;
}
function renderLayout(title, body) {
function renderLayout(title, body, env, options = {}) {
const site = cleanText(env?.SITE_TITLE) || DEFAULT_SITE_TITLE;
const mdHead = options.markdownPage
? `
<link rel="stylesheet" href="/css/markdown.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.45/dist/katex.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11/build/styles/github.min.css" crossorigin="anonymous">
`
: "";
const mdScript = options.markdownPage
? `\n <script type="module" src="/js/markdown-client.js"></script>`
: "";
return `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${escapeHtml(title)}</title>
<link rel="icon" href="/favicon.ico" sizes="any">
${mdHead}
<style>
html, body { margin: 0; padding: 0; background: #fff; color: #111; }
body { font-family: Arial, sans-serif; line-height: 1.7; }
main { max-width: 820px; margin: 0 auto; padding: 16px; }
header { margin-bottom: 24px; }
header.site-header {
margin-bottom: 24px;
padding-bottom: 16px;
border-bottom: 1px solid #e8e8e8;
}
.site-brand {
display: flex;
align-items: center;
gap: 12px;
}
.site-title-link {
text-decoration: none;
color: inherit;
font-weight: 700;
font-size: 1.2rem;
}
.site-logo {
flex-shrink: 0;
width: 40px;
height: 40px;
object-fit: contain;
cursor: pointer;
}
.admin-gate {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.35);
display: flex;
align-items: center;
justify-content: center;
z-index: 9999;
}
.admin-gate[hidden] { display: none !important; }
.admin-gate-panel {
background: #fff;
padding: 16px;
border-radius: 8px;
border: 1px solid #ccc;
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
max-width: 92vw;
}
.admin-gate-panel input[type="password"] { width: min(220px, 70vw); box-sizing: border-box; }
h1, h2, h3 { line-height: 1.3; margin: 0 0 12px; }
article, section { margin: 0 0 24px; }
p { margin: 0 0 12px; }
@@ -383,6 +469,26 @@ function renderLayout(title, body) {
pre { white-space: pre-wrap; word-break: break-word; }
img { max-width: 100%; height: auto; }
hr { border: 0; border-top: 1px solid #ddd; margin: 24px 0; }
.post-card .post-excerpt { margin: 0 0 10px; }
.post-card .post-meta {
font-size: 0.9em;
color: #555;
margin: 0 0 16px;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px 16px;
}
.post-detail-meta {
font-size: 0.95em;
color: #555;
margin: 0 0 16px;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px 16px;
}
.post-detail-views { color: #666; }
form { margin: 0; }
@media (max-width: 640px) {
main { padding: 12px; }
@@ -392,132 +498,107 @@ function renderLayout(title, body) {
</head>
<body>
<main>
<header class="site-header">
<div class="site-brand">
<img class="site-logo" src="/logo.png" alt="" width="40" height="40" decoding="async">
<a href="/" class="site-title-link">${escapeHtml(site)}</a>
</div>
</header>
${body}
</main>
<div id="admin-gate" class="admin-gate" hidden>
<div class="admin-gate-panel">
<input id="admin-token" type="password" autocomplete="off" placeholder="Token" aria-label="Token">
<button type="button" id="admin-token-go">进入</button>
<button type="button" id="admin-token-cancel">取消</button>
</div>
</div>
<script>
(function () {
var logo = document.querySelector(".site-logo");
var gate = document.getElementById("admin-gate");
var inp = document.getElementById("admin-token");
var btnGo = document.getElementById("admin-token-go");
var btnCancel = document.getElementById("admin-token-cancel");
if (!logo || !gate || !inp || !btnGo || !btnCancel) return;
var n = 0;
var resetTimer = null;
function showGate() {
gate.hidden = false;
inp.value = "";
inp.focus();
}
function hideGate() {
gate.hidden = true;
}
logo.addEventListener("click", function (e) {
e.preventDefault();
if (resetTimer) clearTimeout(resetTimer);
n += 1;
if (n >= 5) {
n = 0;
showGate();
return;
}
resetTimer = setTimeout(function () { n = 0; }, 4000);
});
btnCancel.addEventListener("click", hideGate);
function submit() {
fetch("/admin/session", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "same-origin",
body: JSON.stringify({ token: inp.value })
})
.then(function (r) {
if (r.ok) {
hideGate();
location.href = "/admin";
return;
}
inp.select();
alert("Token 无效");
})
.catch(function () {
alert("网络错误");
});
}
btnGo.addEventListener("click", submit);
inp.addEventListener("keydown", function (e) {
if (e.key === "Enter") {
e.preventDefault();
submit();
}
});
})();
</script>${mdScript}
</body>
</html>`;
}
function renderMarkdown(source) {
const lines = String(source || "").replace(/\r\n?/g, "\n").split("\n");
let html = "";
let i = 0;
while (i < lines.length) {
const line = lines[i];
const trimmed = line.trim();
if (!trimmed) {
i += 1;
continue;
}
if (trimmed.startsWith("```")) {
const fence = trimmed.slice(3).trim();
i += 1;
const code = [];
while (i < lines.length && !lines[i].trim().startsWith("```")) {
code.push(lines[i]);
i += 1;
}
if (i < lines.length) i += 1;
html += `<pre><code${fence ? ` class="language-${escapeAttr(fence)}"` : ""}>${escapeHtml(code.join("\n"))}</code></pre>`;
continue;
}
const heading = trimmed.match(/^(#{1,6})\s+(.*)$/);
if (heading) {
const level = heading[1].length;
html += `<h${level}>${parseInline(heading[2])}</h${level}>`;
i += 1;
continue;
}
if (/^(\*{3,}|-{3,}|_{3,})$/.test(trimmed)) {
html += "<hr>";
i += 1;
continue;
}
if (/^>\s?/.test(trimmed)) {
const quote = [];
while (i < lines.length && /^>\s?/.test(lines[i].trim())) {
quote.push(lines[i].trim().replace(/^>\s?/, ""));
i += 1;
}
html += `<blockquote>${renderMarkdown(quote.join("\n"))}</blockquote>`;
continue;
}
if (/^(\s*[-*+]\s+|\s*\d+[.)]\s+)/.test(line)) {
const ordered = /^\s*\d+[.)]\s+/.test(line);
const tag = ordered ? "ol" : "ul";
const items = [];
while (i < lines.length && /^(\s*[-*+]\s+|\s*\d+[.)]\s+)/.test(lines[i])) {
items.push(lines[i].replace(/^(\s*[-*+]\s+|\s*\d+[.)]\s+)/, ""));
i += 1;
}
html += `<${tag}>${items.map((item) => `<li>${parseInline(item)}</li>`).join("")}</${tag}>`;
continue;
}
const paragraph = [];
while (i < lines.length) {
const current = lines[i];
const currentTrimmed = current.trim();
if (!currentTrimmed) break;
if (
currentTrimmed.startsWith("```") ||
/^(#{1,6})\s+/.test(currentTrimmed) ||
/^(\*{3,}|-{3,}|_{3,})$/.test(currentTrimmed) ||
/^>\s?/.test(currentTrimmed) ||
/^(\s*[-*+]\s+|\s*\d+[.)]\s+)/.test(current)
) {
break;
}
paragraph.push(currentTrimmed);
i += 1;
}
html += `<p>${parseInline(paragraph.join(" "))}</p>`;
}
return html;
function b64EncodeUtf8(str) {
return btoa(unescape(encodeURIComponent(str)));
}
function parseInline(text) {
const placeholders = [];
let output = escapeHtml(String(text || ""));
output = output.replace(/`([^`]+?)`/g, (_, code) => {
placeholders.push(`<code>${escapeHtml(code)}</code>`);
return `\u0000${placeholders.length - 1}\u0000`;
});
output = output.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, (_, alt, src, title) => {
const attrs = [`alt="${escapeAttr(alt)}"`, `src="${escapeAttr(src)}"`];
if (title) attrs.push(`title="${escapeAttr(title)}"`);
return `<img ${attrs.join(" ")}>`;
});
output = output.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, (_, label, href, title) => {
const attrs = [`href="${escapeAttr(href)}"`];
if (title) attrs.push(`title="${escapeAttr(title)}"`);
return `<a ${attrs.join(" ")}>${label}</a>`;
});
output = output.replace(/(\*\*|__)(.+?)\1/g, "<strong>$2</strong>");
output = output.replace(/(\*|_)([^*_].*?)\1/g, "<em>$2</em>");
output = output.replace(/\u0000(\d+)\u0000/g, (_, index) => placeholders[Number(index)] || "");
return output;
function markdownPlaceholder(raw) {
const src = String(raw ?? "");
if (!src.trim()) return "";
const b64 = b64EncodeUtf8(src);
return `<div class="markdown-body markdown-pending" data-b64-md="${escapeAttr(b64)}"><p class="markdown-loading">加载中…</p></div>`;
}
function stripMarkdown(text) {
return String(text || "")
return String(text ?? "")
.replace(/```[\s\S]*?```/g, " ")
.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, "$1")
.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, "$1")
.replace(/[`*_>#-]/g, " ")
.replace(/\$\$[\s\S]*?\$\$/g, " ")
.replace(/\$[^$\n]+\$/g, " ")
.replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1")
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
.replace(/^\s{0,3}#{1,6}\s+/gm, "")
.replace(/^\s{0,3}>\s?/gm, "")
.replace(/^\s{0,3}[-*+]\s+/gm, "")
.replace(/^\s{0,3}\d+[.)]\s+/gm, "")
.replace(/[*_`~#]/g, " ")
.replace(/\s+/g, " ")
.trim();
}
@@ -542,22 +623,23 @@ function htmlResponse(html, status = 200, headers = {}) {
});
}
function jsonResponse(data, status = 200) {
function jsonResponse(data, status = 200, extraHeaders = {}) {
return new Response(JSON.stringify(data, null, 2), {
status,
headers: {
"content-type": "application/json; charset=UTF-8",
...corsHeaders()
...corsHeaders(),
...extraHeaders
}
});
}
function notFoundPage() {
function notFoundPage(env) {
return htmlResponse(renderLayout("404", `
<h1>404</h1>
<p>页面不存在。</p>
<p><a href="/">返回首页</a></p>
`), 404);
`, env), 404);
}
function corsHeaders() {
@@ -568,32 +650,61 @@ function corsHeaders() {
};
}
function requireAdmin(request, env) {
async function requireAdmin(request, env) {
const password = cleanText(env.ADMIN_PASSWORD);
if (!password) return null;
const header = request.headers.get("Authorization") || "";
if (!header.startsWith("Basic ")) {
return unauthorized();
const cookies = parseCookie(request.headers.get("Cookie") || "");
const expected = await adminSessionCookieValue(env);
if (cookies.sb_admin && cookies.sb_admin === expected) {
return null;
}
try {
const decoded = atob(header.slice(6));
const split = decoded.indexOf(":");
const inputPassword = split >= 0 ? decoded.slice(split + 1) : "";
if (inputPassword === password) return null;
} catch {
// ignore
const header = request.headers.get("Authorization") || "";
if (header.startsWith("Basic ")) {
try {
const decoded = atob(header.slice(6));
const split = decoded.indexOf(":");
const inputPassword = split >= 0 ? decoded.slice(split + 1) : "";
if (inputPassword === password) return null;
} catch {
// ignore
}
}
return unauthorized();
}
function parseCookie(header) {
const out = {};
if (!header) return out;
for (const part of header.split(";")) {
const idx = part.indexOf("=");
if (idx === -1) continue;
const k = part.slice(0, idx).trim();
const v = part.slice(idx + 1).trim();
try {
out[k] = decodeURIComponent(v);
} catch {
out[k] = v;
}
}
return out;
}
async function adminSessionCookieValue(env) {
const password = cleanText(env.ADMIN_PASSWORD);
const enc = new TextEncoder();
const data = enc.encode(`${password}\0sproutblog_admin_v1`);
const hash = await crypto.subtle.digest("SHA-256", data);
return [...new Uint8Array(hash)].map((b) => b.toString(16).padStart(2, "0")).join("");
}
function unauthorized() {
return new Response("Authentication required", {
status: 401,
headers: {
"WWW-Authenticate": 'Basic realm="SproutBlog admin", charset="UTF-8"'
"content-type": "text/plain; charset=UTF-8"
}
});
}

View File

@@ -2,6 +2,13 @@ name = "sproutblog"
main = "worker.js"
compatibility_date = "2026-04-13"
routes = [
{ pattern = "blog.smyhub.com/*", zone_name = "smyhub.com" }
]
[assets]
directory = "./public/"
[vars]
ADMIN_PASSWORD = "shumengya520"