Files
Sakurasan fbda293072 余白 UI:按设计稿模块化还原 + 站主自定义 CSS + 详情 neighbors + 静态缓存头
前端(新增 ui/yohaku/,各视图按 ui_id=vivid 分支渲染;classic 与后台不受影响)
- 令牌层:设计稿数值原样落地,28 个 --v-* 为站主接口(自定义 CSS 可覆盖,
  放 @layer 让出优先级);另加防线,中和 styles.css 裸选择器
  (h1 衬线 / body 行高 / 后台 .stat/.toolbar/.chip 卡片)漏进余白元素
- 顶栏(滚动收缩态)/ 阅读进度(顶部 2px + READ n%)/ 页脚
- 首页:hero(统计条)/ 筛选(类型分段 + 标签 chips + 搜索)/
  长文卡片与短文纸条 / 分页 / 作品展示区(3 件 + 查看所有,参照 diygod.cc);
  面板栅格改 1.6fr 1fr 1fr 且高度自适应内容(标签云明显大一圈)
- 文章页:三栏「纸」—— 左时间线(前后各两篇)/ 中纸张 / 右目录与阅读进度;
  短文详情不显示标题(h1 视觉隐藏保留无障碍)
- 全部规则收敛在 html[data-ui='vivid'] 前缀下;无 !important

后端
- GET /api/posts/:slug 增 neighbors(前后各两篇,详情页侧栏时间线用)
- SPA 缓存头:index.html no-cache,assets/ 带 hash 长期 immutable
  (此前无缓存头,浏览器会一直拿旧构建)

其他
- 站主自定义 CSS 管线(customCss.js + ui/sections.js,按分区注入,仅 vivid)
- 删除旧 vivid 覆盖层实现(VividNav/Hero/Footer/Timeline/Toc、ui/vivid.css)
- 设计稿原型附于仓库根 index.html;作品表清掉外链 diygod.cc 的示例封面,
  改用本地占位图(public/covers/)
2026-09-23 15:37:42 +08:00

208 lines
6.6 KiB
Go

package admin
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"oneblog/internal/config"
"oneblog/internal/db"
"oneblog/internal/model"
"oneblog/internal/store"
)
func newTestAPI(t *testing.T) (*API, http.Handler) {
t.Helper()
d, err := db.Open("sqlite", ":memory:")
if err != nil {
t.Fatalf("open sqlite: %v", err)
}
t.Cleanup(func() { d.Close() })
st, err := store.New(d)
if err != nil {
t.Fatalf("store: %v", err)
}
cfg := &config.Config{AdminUser: "admin", AdminPass: "s3cret"}
a := NewAPI(st, cfg, NewSessions("test-secret", time.Hour))
return a, a.Routes()
}
func login(t *testing.T, h http.Handler, user, pass string) *httptest.ResponseRecorder {
t.Helper()
body, _ := json.Marshal(loginRequest{Username: user, Password: pass})
req := httptest.NewRequest(http.MethodPost, "/api/admin/login", strings.NewReader(string(body)))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
func TestGuardRejectsAnonymous(t *testing.T) {
_, h := newTestAPI(t)
for _, path := range []string{"/api/admin/posts", "/api/admin/projects", "/api/admin/settings", "/api/admin/dashboard"} {
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))
if rec.Code != http.StatusUnauthorized {
t.Errorf("%s: got %d, want 401", path, rec.Code)
}
}
}
func TestLoginIssuesUsableSession(t *testing.T) {
_, h := newTestAPI(t)
rec := login(t, h, "admin", "wrong")
if rec.Code != http.StatusUnauthorized {
t.Fatalf("wrong password: got %d, want 401", rec.Code)
}
rec = login(t, h, "admin", "s3cret")
if rec.Code != http.StatusOK {
t.Fatalf("login: got %d, want 200", rec.Code)
}
var out struct {
Token string `json:"token"`
}
if err := json.NewDecoder(rec.Body).Decode(&out); err != nil || out.Token == "" {
t.Fatalf("no token in response: %v", err)
}
// Bearer 通道
req := httptest.NewRequest(http.MethodGet, "/api/admin/posts", nil)
req.Header.Set("Authorization", "Bearer "+out.Token)
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req)
if rec2.Code != http.StatusOK {
t.Fatalf("bearer posts: got %d, want 200", rec2.Code)
}
// cookie 通道
req = httptest.NewRequest(http.MethodGet, "/api/admin/posts", nil)
req.AddCookie(&http.Cookie{Name: "one_session", Value: out.Token})
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req)
if rec3.Code != http.StatusOK {
t.Fatalf("cookie posts: got %d, want 200", rec3.Code)
}
}
func TestLoginRateLimitedAfterRepeatedFailures(t *testing.T) {
_, h := newTestAPI(t)
var rec *httptest.ResponseRecorder
for i := 0; i < maxLoginFails+1; i++ {
rec = login(t, h, "admin", "bad")
}
if rec.Code != http.StatusTooManyRequests {
t.Fatalf("after %d failures: got %d, want 429", maxLoginFails+1, rec.Code)
}
// 限速期间即使口令正确也被拒
rec = login(t, h, "admin", "s3cret")
if rec.Code != http.StatusTooManyRequests {
t.Fatalf("locked out login: got %d, want 429", rec.Code)
}
}
func TestSecureCookieBehindTLSProxy(t *testing.T) {
_, h := newTestAPI(t)
body, _ := json.Marshal(loginRequest{Username: "admin", Password: "s3cret"})
req := httptest.NewRequest(http.MethodPost, "/api/admin/login", strings.NewReader(string(body)))
req.Header.Set("X-Forwarded-Proto", "https")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("login: %d", rec.Code)
}
cookie := rec.Header().Get("Set-Cookie")
if !strings.Contains(cookie, "Secure") {
t.Fatalf("expected Secure flag over https proxy, got: %s", cookie)
}
}
// ?order= 直接来自查询串并拼进 SQL,注入串必须被白名单挡掉且不影响数据。
func TestOrderParamInjectionIsNeutralized(t *testing.T) {
a, h := newTestAPI(t)
if _, err := a.Store.Create(model.PostInput{Title: "one", ContentMd: "a", Status: model.StatusPublished}); err != nil {
t.Fatal(err)
}
token := login(t, h, "admin", "s3cret")
var out struct {
Token string `json:"token"`
}
_ = json.NewDecoder(token.Body).Decode(&out)
req := httptest.NewRequest(http.MethodGet, "/api/admin/posts?order="+
strings.ReplaceAll("published_at DESC; DROP TABLE posts; --", " ", "%20"), nil)
req.Header.Set("Authorization", "Bearer "+out.Token)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("injected order: got %d body=%s", rec.Code, rec.Body.String())
}
// 表若被 DROP,这条查询会报错
if _, err := a.Store.List(store.ListOptions{Status: "any"}); err != nil {
t.Fatalf("posts table damaged: %v", err)
}
}
// 设置里的 ui_id / custom_css 必须能经 PUT→GET 往返,且非法分区被挡掉。
func TestSettingsUIRoundTrip(t *testing.T) {
_, h := newTestAPI(t)
token := login(t, h, "admin", "s3cret")
var sess struct {
Token string `json:"token"`
}
_ = json.NewDecoder(token.Body).Decode(&sess)
if sess.Token == "" {
t.Fatal("login failed")
}
put := func(body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPut, "/api/admin/settings", strings.NewReader(body))
req.Header.Set("Authorization", "Bearer "+sess.Token)
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
rec := put(`{"site_title":"ONE","posts_per_page":10,"light_skin_id":"paper",
"ui_id":"vivid","custom_css":{"home":"body{--v-accent:#f0f}","bogus":"x{}"}}`)
if rec.Code != http.StatusOK {
t.Fatalf("put settings: got %d body=%s", rec.Code, rec.Body.String())
}
get := httptest.NewRequest(http.MethodGet, "/api/admin/settings", nil)
get.Header.Set("Authorization", "Bearer "+sess.Token)
rec = httptest.NewRecorder()
h.ServeHTTP(rec, get)
if rec.Code != http.StatusOK {
t.Fatalf("get settings: got %d", rec.Code)
}
var got model.Settings
if err := json.NewDecoder(rec.Body).Decode(&got); err != nil {
t.Fatalf("decode: %v", err)
}
if got.UIID != "vivid" {
t.Errorf("ui_id = %q, want vivid", got.UIID)
}
if got.CustomCSS["home"] != "body{--v-accent:#f0f}" {
t.Errorf("home css lost: %+v", got.CustomCSS)
}
if _, ok := got.CustomCSS["bogus"]; ok {
t.Error("unknown section should not be persisted")
}
// An invalid ui_id falls back rather than being stored verbatim.
rec = put(`{"site_title":"ONE","posts_per_page":10,"light_skin_id":"paper","ui_id":"neon","custom_css":{}}`)
if rec.Code != http.StatusOK {
t.Fatalf("put invalid ui: got %d body=%s", rec.Code, rec.Body.String())
}
rec = httptest.NewRecorder()
h.ServeHTTP(rec, get)
_ = json.NewDecoder(rec.Body).Decode(&got)
if got.UIID != "classic" {
t.Errorf("invalid ui_id should fall back to classic, got %q", got.UIID)
}
if got.CustomCSS == nil {
t.Error("custom_css should be non-nil")
}
}