阶段十:完成 Go 基础包注释基线清零

This commit is contained in:
Christ committed 2026-08-15 05:42:49 +08:00
1 parent ea1f2ec430
commit d1a165f897
14 files changed
+135 -924

No files matched your search

-912
View File
@@ -1,388 +1,4 @@
[
{
"file": "internal/auth/auth.go",
"line": 29,
"kind": "const",
"name": "ctxKeyUser"
},
{
"file": "internal/auth/auth.go",
"line": 48,
"kind": "local-variable",
"name": "err"
},
{
"file": "internal/auth/auth.go",
"line": 48,
"kind": "local-variable",
"name": "ok"
},
{
"file": "internal/auth/auth.go",
"line": 48,
"kind": "local-variable",
"name": "user"
},
{
"file": "internal/auth/auth.go",
"line": 55,
"kind": "local-variable",
"name": "err"
},
{
"file": "internal/auth/auth.go",
"line": 55,
"kind": "local-variable",
"name": "sid"
},
{
"file": "internal/auth/auth.go",
"line": 99,
"kind": "local-variable",
"name": "c"
},
{
"file": "internal/auth/auth.go",
"line": 99,
"kind": "local-variable",
"name": "err"
},
{
"file": "internal/auth/auth.go",
"line": 103,
"kind": "local-variable",
"name": "err"
},
{
"file": "internal/auth/auth.go",
"line": 103,
"kind": "local-variable",
"name": "sess"
},
{
"file": "internal/auth/auth.go",
"line": 116,
"kind": "local-variable",
"name": "err"
},
{
"file": "internal/auth/auth.go",
"line": 116,
"kind": "local-variable",
"name": "sess"
},
{
"file": "internal/auth/auth.go",
"line": 120,
"kind": "local-variable",
"name": "ctx"
},
{
"file": "internal/auth/auth.go",
"line": 139,
"kind": "local-variable",
"name": "sess"
},
{
"file": "internal/auth/auth.go",
"line": 153,
"kind": "function",
"name": "SessionFromContext"
},
{
"file": "internal/auth/auth.go",
"line": 154,
"kind": "local-variable",
"name": "v"
},
{
"file": "internal/auth/auth.go",
"line": 162,
"kind": "local-variable",
"name": "err"
},
{
"file": "internal/auth/auth.go",
"line": 162,
"kind": "local-variable",
"name": "existing"
},
{
"file": "internal/auth/auth.go",
"line": 167,
"kind": "local-variable",
"name": "err"
},
{
"file": "internal/auth/auth.go",
"line": 167,
"kind": "local-variable",
"name": "ok"
},
{
"file": "internal/auth/auth.go",
"line": 176,
"kind": "local-variable",
"name": "err"
},
{
"file": "internal/auth/auth.go",
"line": 176,
"kind": "local-variable",
"name": "ok"
},
{
"file": "internal/auth/auth_test.go",
"line": 14,
"kind": "function",
"name": "newAuth"
},
{
"file": "internal/auth/auth_test.go",
"line": 16,
"kind": "local-variable",
"name": "dbPath"
},
{
"file": "internal/auth/auth_test.go",
"line": 17,
"kind": "local-variable",
"name": "d"
},
{
"file": "internal/auth/auth_test.go",
"line": 17,
"kind": "local-variable",
"name": "err"
},
{
"file": "internal/auth/auth_test.go",
"line": 21,
"kind": "local-variable",
"name": "store"
},
{
"file": "internal/auth/auth_test.go",
"line": 27,
"kind": "local-variable",
"name": "svc"
},
{
"file": "internal/auth/auth_test.go",
"line": 31,
"kind": "function",
"name": "testLogger"
},
{
"file": "internal/auth/auth_test.go",
"line": 33,
"kind": "function",
"name": "TestLoginAndMiddleware"
},
{
"file": "internal/auth/auth_test.go",
"line": 34,
"kind": "local-variable",
"name": "cleanup"
},
{
"file": "internal/auth/auth_test.go",
"line": 34,
"kind": "local-variable",
"name": "svc"
},
{
"file": "internal/auth/auth_test.go",
"line": 36,
"kind": "local-variable",
"name": "ctx"
},
{
"file": "internal/auth/auth_test.go",
"line": 51,
"kind": "local-variable",
"name": "sess"
},
{
"file": "internal/auth/auth_test.go",
"line": 58,
"kind": "local-variable",
"name": "req"
},
{
"file": "internal/auth/auth_test.go",
"line": 60,
"kind": "local-variable",
"name": "rec"
},
{
"file": "internal/auth/auth_test.go",
"line": 67,
"kind": "function",
"name": "TestRequireAuthAndAdmin"
},
{
"file": "internal/auth/auth_test.go",
"line": 68,
"kind": "local-variable",
"name": "cleanup"
},
{
"file": "internal/auth/auth_test.go",
"line": 68,
"kind": "local-variable",
"name": "svc"
},
{
"file": "internal/auth/auth_test.go",
"line": 70,
"kind": "local-variable",
"name": "ctx"
},
{
"file": "internal/auth/auth_test.go",
"line": 71,
"kind": "local-variable",
"name": "sid"
},
{
"file": "internal/auth/auth_test.go",
"line": 73,
"kind": "local-variable",
"name": "protected"
},
{
"file": "internal/auth/auth_test.go",
"line": 79,
"kind": "local-variable",
"name": "rec"
},
{
"file": "internal/auth/auth_test.go",
"line": 88,
"kind": "local-variable",
"name": "rec2"
},
{
"file": "internal/auth/auth_test.go",
"line": 95,
"kind": "function",
"name": "TestSetAndClearCookie"
},
{
"file": "internal/auth/auth_test.go",
"line": 96,
"kind": "local-variable",
"name": "cleanup"
},
{
"file": "internal/auth/auth_test.go",
"line": 96,
"kind": "local-variable",
"name": "svc"
},
{
"file": "internal/auth/auth_test.go",
"line": 99,
"kind": "local-variable",
"name": "rec"
},
{
"file": "internal/auth/auth_test.go",
"line": 101,
"kind": "local-variable",
"name": "c"
},
{
"file": "internal/auth/auth_test.go",
"line": 109,
"kind": "local-variable",
"name": "rec2"
},
{
"file": "internal/auth/auth_test.go",
"line": 111,
"kind": "local-variable",
"name": "cc"
},
{
"file": "internal/auth/auth_test.go",
"line": 120,
"kind": "local-variable",
"name": "dbPath"
},
{
"file": "internal/auth/auth_test.go",
"line": 121,
"kind": "local-variable",
"name": "d"
},
{
"file": "internal/auth/auth_test.go",
"line": 121,
"kind": "local-variable",
"name": "err"
},
{
"file": "internal/auth/auth_test.go",
"line": 130,
"kind": "local-variable",
"name": "cleanup"
},
{
"file": "internal/auth/auth_test.go",
"line": 130,
"kind": "local-variable",
"name": "store"
},
{
"file": "internal/auth/auth_test.go",
"line": 132,
"kind": "local-variable",
"name": "ctx"
},
{
"file": "internal/auth/auth_test.go",
"line": 139,
"kind": "local-variable",
"name": "admin"
},
{
"file": "internal/auth/auth_test.go",
"line": 153,
"kind": "local-variable",
"name": "ok"
},
{
"file": "internal/auth/auth_test.go",
"line": 156,
"kind": "local-variable",
"name": "ok"
},
{
"file": "internal/auth/auth_test.go",
"line": 164,
"kind": "local-variable",
"name": "cleanup"
},
{
"file": "internal/auth/auth_test.go",
"line": 164,
"kind": "local-variable",
"name": "store"
},
{
"file": "internal/auth/auth_test.go",
"line": 166,
"kind": "local-variable",
"name": "err"
},
{
"file": "internal/auth/auth_test.go",
"line": 169,
"kind": "local-variable",
"name": "admin"
},
{
"file": "internal/browser/slider.go",
"line": 18,
@@ -4366,533 +3982,5 @@
"line": 154,
"kind": "range-variable",
"name": "text"
},
{
"file": "internal/logging/logging.go",
"line": 11,
"kind": "var",
"name": "Level"
},
{
"file": "internal/logging/logging.go",
"line": 13,
"kind": "function",
"name": "init"
},
{
"file": "internal/logging/logging.go",
"line": 18,
"kind": "function",
"name": "NewLogger"
},
{
"file": "internal/logging/logging.go",
"line": 19,
"kind": "local-variable",
"name": "opts"
},
{
"file": "internal/logging/logging.go",
"line": 27,
"kind": "function",
"name": "SetLevel"
},
{
"file": "internal/logging/logging.go",
"line": 28,
"kind": "local-variable",
"name": "err"
},
{
"file": "internal/logging/logging.go",
"line": 28,
"kind": "local-variable",
"name": "lv"
},
{
"file": "internal/logging/logging.go",
"line": 37,
"kind": "function",
"name": "ParseLevel"
},
{
"file": "internal/logging/logging_test.go",
"line": 10,
"kind": "function",
"name": "TestParseLevelAndSetLevel"
},
{
"file": "internal/logging/logging_test.go",
"line": 13,
"kind": "local-variable",
"name": "cases"
},
{
"file": "internal/logging/logging_test.go",
"line": 20,
"kind": "range-variable",
"name": "in"
},
{
"file": "internal/logging/logging_test.go",
"line": 20,
"kind": "range-variable",
"name": "want"
},
{
"file": "internal/logging/logging_test.go",
"line": 21,
"kind": "local-variable",
"name": "err"
},
{
"file": "internal/logging/logging_test.go",
"line": 21,
"kind": "local-variable",
"name": "got"
},
{
"file": "internal/logging/logging_test.go",
"line": 29,
"kind": "local-variable",
"name": "err"
},
{
"file": "internal/logging/logging_test.go",
"line": 32,
"kind": "local-variable",
"name": "err"
},
{
"file": "internal/logging/logging_test.go",
"line": 35,
"kind": "local-variable",
"name": "got"
},
{
"file": "internal/logging/logging_test.go",
"line": 40,
"kind": "function",
"name": "TestNewLoggerHonorsDynamicLevel"
},
{
"file": "internal/logging/logging_test.go",
"line": 42,
"kind": "var",
"name": "buf"
},
{
"file": "internal/logging/logging_test.go",
"line": 43,
"kind": "local-variable",
"name": "logger"
},
{
"file": "internal/logging/logging_test.go",
"line": 48,
"kind": "local-variable",
"name": "out"
},
{
"file": "internal/logsafe/logsafe.go",
"line": 13,
"kind": "function",
"name": "ID"
},
{
"file": "internal/logsafe/logsafe.go",
"line": 18,
"kind": "local-variable",
"name": "sum"
},
{
"file": "internal/logsafe/logsafe.go",
"line": 23,
"kind": "function",
"name": "URL"
},
{
"file": "internal/logsafe/logsafe.go",
"line": 24,
"kind": "local-variable",
"name": "err"
},
{
"file": "internal/logsafe/logsafe.go",
"line": 24,
"kind": "local-variable",
"name": "u"
},
{
"file": "internal/logsafe/logsafe_test.go",
"line": 5,
"kind": "function",
"name": "TestRedactionHelpers"
},
{
"file": "internal/logsafe/logsafe_test.go",
"line": 12,
"kind": "local-variable",
"name": "got"
},
{
"file": "internal/logsafe/logsafe_test.go",
"line": 15,
"kind": "local-variable",
"name": "got"
},
{
"file": "internal/netguard/http.go",
"line": 16,
"kind": "var",
"name": "nonPublicPrefixes"
},
{
"file": "internal/netguard/http.go",
"line": 31,
"kind": "local-variable",
"name": "transport"
},
{
"file": "internal/netguard/http.go",
"line": 55,
"kind": "local-variable",
"name": "baseURL"
},
{
"file": "internal/netguard/http.go",
"line": 55,
"kind": "local-variable",
"name": "err"
},
{
"file": "internal/netguard/http.go",
"line": 62,
"kind": "local-variable",
"name": "transport"
},
{
"file": "internal/netguard/http.go",
"line": 69,
"kind": "function",
"name": "IsPublicIP"
},
{
"file": "internal/netguard/http.go",
"line": 70,
"kind": "local-variable",
"name": "addr"
},
{
"file": "internal/netguard/http.go",
"line": 70,
"kind": "local-variable",
"name": "ok"
},
{
"file": "internal/netguard/http.go",
"line": 78,
"kind": "range-variable",
"name": "prefix"
},
{
"file": "internal/netguard/http.go",
"line": 92,
"kind": "function",
"name": "dialContextWithPolicy"
},
{
"file": "internal/netguard/http.go",
"line": 95,
"kind": "local-variable",
"name": "err"
},
{
"file": "internal/netguard/http.go",
"line": 95,
"kind": "local-variable",
"name": "host"
},
{
"file": "internal/netguard/http.go",
"line": 95,
"kind": "local-variable",
"name": "port"
},
{
"file": "internal/netguard/http.go",
"line": 99,
"kind": "local-variable",
"name": "err"
},
{
"file": "internal/netguard/http.go",
"line": 99,
"kind": "local-variable",
"name": "ips"
},
{
"file": "internal/netguard/http.go",
"line": 103,
"kind": "local-variable",
"name": "dialer"
},
{
"file": "internal/netguard/http.go",
"line": 104,
"kind": "var",
"name": "lastErr"
},
{
"file": "internal/netguard/http.go",
"line": 105,
"kind": "local-variable",
"name": "foundAllowed"
},
{
"file": "internal/netguard/http.go",
"line": 106,
"kind": "range-variable",
"name": "resolved"
},
{
"file": "internal/netguard/http.go",
"line": 109,
"kind": "local-variable",
"name": "conn"
},
{
"file": "internal/netguard/http.go",
"line": 109,
"kind": "local-variable",
"name": "dialErr"
},
{
"file": "internal/netguard/http_test.go",
"line": 12,
"kind": "function",
"name": "TestIsPublicIP"
},
{
"file": "internal/netguard/http_test.go",
"line": 13,
"kind": "range-variable",
"name": "raw"
},
{
"file": "internal/netguard/http_test.go",
"line": 26,
"kind": "function",
"name": "TestPublicHTTPClientRejectsLoopback"
},
{
"file": "internal/netguard/http_test.go",
"line": 27,
"kind": "local-variable",
"name": "client"
},
{
"file": "internal/netguard/http_test.go",
"line": 28,
"kind": "local-variable",
"name": "req"
},
{
"file": "internal/netguard/http_test.go",
"line": 29,
"kind": "local-variable",
"name": "err"
},
{
"file": "internal/netguard/http_test.go",
"line": 34,
"kind": "function",
"name": "TestTrustedEndpointHTTPClientAllowsLoopbackAndUnspecifiedAddress"
},
{
"file": "internal/netguard/http_test.go",
"line": 35,
"kind": "local-variable",
"name": "server"
},
{
"file": "internal/netguard/http_test.go",
"line": 40,
"kind": "local-variable",
"name": "err"
},
{
"file": "internal/netguard/http_test.go",
"line": 40,
"kind": "local-variable",
"name": "port"
},
{
"file": "internal/netguard/http_test.go",
"line": 44,
"kind": "range-variable",
"name": "host"
},
{
"file": "internal/netguard/http_test.go",
"line": 45,
"kind": "local-variable",
"name": "baseURL"
},
{
"file": "internal/netguard/http_test.go",
"line": 46,
"kind": "local-variable",
"name": "client"
},
{
"file": "internal/netguard/http_test.go",
"line": 46,
"kind": "local-variable",
"name": "clientErr"
},
{
"file": "internal/netguard/http_test.go",
"line": 50,
"kind": "local-variable",
"name": "requestErr"
},
{
"file": "internal/netguard/http_test.go",
"line": 50,
"kind": "local-variable",
"name": "resp"
},
{
"file": "internal/netguard/http_test.go",
"line": 61,
"kind": "function",
"name": "TestTrustedEndpointHTTPClientDoesNotApplyAddressPolicy"
},
{
"file": "internal/netguard/http_test.go",
"line": 62,
"kind": "range-variable",
"name": "raw"
},
{
"file": "internal/netguard/http_test.go",
"line": 66,
"kind": "local-variable",
"name": "client"
},
{
"file": "internal/netguard/http_test.go",
"line": 66,
"kind": "local-variable",
"name": "err"
},
{
"file": "internal/netguard/http_test.go",
"line": 76,
"kind": "function",
"name": "TestTrustedEndpointHTTPClientValidatesBaseURL"
},
{
"file": "internal/netguard/http_test.go",
"line": 77,
"kind": "range-variable",
"name": "raw"
},
{
"file": "internal/netguard/http_test.go",
"line": 78,
"kind": "local-variable",
"name": "err"
},
{
"file": "internal/version/version.go",
"line": 7,
"kind": "var",
"name": "Version"
},
{
"file": "internal/version/version.go",
"line": 8,
"kind": "var",
"name": "Commit"
},
{
"file": "internal/version/version.go",
"line": 9,
"kind": "var",
"name": "BuildTime"
},
{
"file": "internal/version/version.go",
"line": 13,
"kind": "function",
"name": "ShortCommit"
},
{
"file": "internal/version/version.go",
"line": 14,
"kind": "local-variable",
"name": "commit"
},
{
"file": "internal/version/version_test.go",
"line": 5,
"kind": "function",
"name": "TestShortCommit"
},
{
"file": "internal/version/version_test.go",
"line": 6,
"kind": "local-variable",
"name": "original"
},
{
"file": "internal/version/version_test.go",
"line": 10,
"kind": "local-variable",
"name": "got"
},
{
"file": "internal/webui/webui.go",
"line": 10,
"kind": "var",
"name": "files"
},
{
"file": "internal/webui/webui.go",
"line": 13,
"kind": "function",
"name": "Static"
},
{
"file": "internal/webui/webui_test.go",
"line": 8,
"kind": "function",
"name": "TestStaticContainsIndex"
},
{
"file": "internal/webui/webui_test.go",
"line": 9,
"kind": "local-variable",
"name": "err"
},
{
"file": "internal/webui/webui_test.go",
"line": 9,
"kind": "local-variable",
"name": "static"
},
{
"file": "internal/webui/webui_test.go",
"line": 13,
"kind": "local-variable",
"name": "data"
},
{
"file": "internal/webui/webui_test.go",
"line": 13,
"kind": "local-variable",
"name": "err"
}
]
@@ -639,3 +639,4 @@ npm --prefix frontend run build
| 2026-08-15 | 完成阶段 10 第十三个 PR 切片“Go internal/chat 注释基线按领域清零” | 为聊天 repository、消息服务、账号订阅、已读状态、事件广播及其测试补齐函数、变量、字段和常量中文注释;`internal/chat` 注释基线清零;Chat 定向测试、`go test -race ./internal/chat`、全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:进入非冻结 browser、cmd 与 tools 注释基线清理 |
| 2026-08-15 | 完成阶段 10 第十四个 PR 切片“Go 非冻结 internal/browser 注释基线按领域清零” | 为 Cookie、订单、密码登录、二维码刷新、生命周期、用户数据目录和浏览器辅助测试补齐函数、变量、字段及常量中文注释;严格跳过冻结的 slider/CAPTCHA 实现与测试;非冻结 browser 注释基线清零,冻结文件保留 664 项原有基线;Browser 定向测试和全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 cmd 与 tools 注释基线,并保留冻结基线边界 |
| 2026-08-15 | 完成阶段 10 第十五个 PR 切片“Go cmd 与 tools 注释基线按领域清零” | 为 server、tray、dbseed、dbverify、init-admin、browser-install、spike 命令及 iconconv 工具补齐函数、变量、字段和常量中文注释;`cmd` 与 `tools` 注释基线清零;命令/工具定向测试和全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理剩余基础内部包并保留冻结 browser 基线 |
| 2026-08-15 | 完成阶段 10 第十六个 PR 切片“Go 基础内部包注释基线按领域清零” | 为 `internal/auth`、`internal/netguard`、`internal/logging`、`internal/version`、`internal/logsafe` 和 `internal/webui` 补齐函数、变量、字段及常量中文注释;这些基础包注释基线清零;定向测试和全量 Go/React 门禁通过,合并为一个可回滚提交;当前 Go 基线仅保留冻结 browser CAPTCHA 文件 | 阶段 10:冻结基线边界审计、删除可清理基线并完成最终验收 |
+14
View File
@@ -25,6 +25,7 @@ const CookieMaxAge = 24 * 60 * 60
// ctxKey 上下文键类型,避免冲突。
type ctxKey int
// ctxKeyUser 保存ctxKey用户,供当前处理流程使用
const (
ctxKeyUser ctxKey = iota
)
@@ -45,6 +46,7 @@ type LoginResult struct {
// Login 用户名密码登录。成功时返回会话 ID(由调用方写入 Cookie)。
func (s *Service) Login(ctx context.Context, username, password string) (string, *db.User, error) {
// user、ok、err 保存user、ok、err,供当前处理流程使用
user, ok, err := s.Store.Users.VerifyAndUpgrade(ctx, username, password)
if err != nil {
return "", nil, err
@@ -52,6 +54,7 @@ func (s *Service) Login(ctx context.Context, username, password string) (string,
if !ok {
return "", nil, nil // 密码错误或用户不存在/未激活
}
// sid、err 保存sid、err,供当前处理流程使用
sid, err := s.Store.Sessions.Create(ctx, user)
if err != nil {
return "", nil, err
@@ -96,10 +99,12 @@ func (s *Service) ClearSessionCookie(w http.ResponseWriter) {
// SessionFromRequest 从请求 Cookie 取会话。无效返回 nil。
func (s *Service) SessionFromRequest(ctx context.Context, r *http.Request) (*db.Session, error) {
// c、err 保存c、err,供当前处理流程使用
c, err := r.Cookie(CookieName)
if err != nil || c.Value == "" {
return nil, nil
}
// sess、err 保存sess、err,供当前处理流程使用
sess, err := s.Store.Sessions.Get(ctx, c.Value)
if err != nil {
if errors.Is(err, db.ErrNotFound) {
@@ -113,10 +118,12 @@ func (s *Service) SessionFromRequest(ctx context.Context, r *http.Request) (*db.
// Middleware 解析会话并把 *db.Session 放入请求上下文。不强制登录(公开路由也可用)。
func (s *Service) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// sess、err 保存sess、err,供当前处理流程使用
sess, err := s.SessionFromRequest(r.Context(), r)
if err != nil {
s.Logger.Warn("读取会话失败", "err", err)
}
// ctx 保存ctx,供当前处理流程使用
ctx := WithSession(r.Context(), sess)
next.ServeHTTP(w, r.WithContext(ctx))
})
@@ -136,6 +143,7 @@ func RequireAuth(next http.Handler) http.Handler {
// RequireAdmin 要求管理员,否则 403(须在 RequireAuth 之后)。
func RequireAdmin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := SessionFromContext(r.Context())
if sess == nil || !sess.IsAdmin {
writeAuthError(w, r, http.StatusForbidden, "forbidden", "需要管理员权限")
@@ -150,7 +158,9 @@ func WithSession(ctx context.Context, sess *db.Session) context.Context {
return context.WithValue(ctx, ctxKeyUser, sess)
}
// SessionFromContext 负责会话From上下文相关处理。
func SessionFromContext(ctx context.Context) *db.Session {
// v 保存v,供当前处理流程使用
v, _ := ctx.Value(ctxKeyUser).(*db.Session)
return v
}
@@ -158,12 +168,15 @@ func SessionFromContext(ctx context.Context) *db.Session {
// InitAdmin 创建或重置 admin 管理员账号,是 cmd/server -init-admin 与
// cmd/init-admin 共用的公共入口。返回 created=true 表示新建 admin,
// false 表示重置已存在 admin 的密码。邮箱仅在新建时使用。
// InitAdmin 负责InitAdmin相关处理。
func InitAdmin(ctx context.Context, store *db.Store, email, password string) (created bool, err error) {
// existing、err 保存existing、err,供当前处理流程使用
existing, err := store.Users.GetAdmin(ctx)
if err != nil && !errors.Is(err, db.ErrNotFound) {
return false, fmt.Errorf("查询 admin 失败: %w", err)
}
if existing != nil {
// ok、err 保存ok、err,供当前处理流程使用
ok, err := store.Users.UpdatePassword(ctx, existing.Username, password)
if err != nil {
return false, err
@@ -173,6 +186,7 @@ func InitAdmin(ctx context.Context, store *db.Store, email, password string) (cr
}
return false, store.Users.SetAdmin(ctx, existing.Username)
}
// ok、err 保存ok、err,供当前处理流程使用
ok, err := store.Users.Create(ctx, "admin", email, password)
if err != nil {
return false, err
+40 -4
View File
@@ -11,28 +11,37 @@ import (
"xianyu-go/internal/db"
)
// newAuth 负责newAuth相关处理。
func newAuth(t *testing.T) (*Service, func()) {
t.Helper()
// dbPath 保存db路径,供当前处理流程使用
dbPath := filepath.Join(t.TempDir(), "test.db")
// d、err 保存d、err,供当前处理流程使用
d, _, err := db.Open(context.Background(), dbPath)
if err != nil {
t.Fatalf("Open: %v", err)
}
// store 保存store,供当前处理流程使用
store := db.NewStore(d, db.DialectSQLite)
// 初始化 admin。
if ok, _ := store.Users.Create(context.Background(), "admin", "a@e.com", "pw"); !ok {
t.Fatal("create admin")
}
store.Users.SetAdmin(context.Background(), "admin")
// svc 保存svc,供当前处理流程使用
svc := &Service{Store: store, Logger: testLogger()}
return svc, func() { d.Close() }
}
// testLogger 负责testLogger相关处理。
func testLogger() *slog.Logger { return slog.Default() }
// TestLoginAndMiddleware 负责Test登录AndMiddleware相关处理。
func TestLoginAndMiddleware(t *testing.T) {
// svc、cleanup 保存svc、cleanup,供当前处理流程使用
svc, cleanup := newAuth(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// 登录。
@@ -48,6 +57,7 @@ func TestLoginAndMiddleware(t *testing.T) {
// 中间件解析会话。
chain := svc.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := SessionFromContext(r.Context())
if sess == nil || !sess.IsAdmin {
t.Errorf("中间件应解析出管理员会话,got=%v", sess)
@@ -55,8 +65,10 @@ func TestLoginAndMiddleware(t *testing.T) {
w.WriteHeader(200)
}))
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.AddCookie(&http.Cookie{Name: CookieName, Value: sid})
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
chain.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -64,18 +76,24 @@ func TestLoginAndMiddleware(t *testing.T) {
}
}
// TestRequireAuthAndAdmin 负责TestRequireAuthAndAdmin相关处理。
func TestRequireAuthAndAdmin(t *testing.T) {
// svc、cleanup 保存svc、cleanup,供当前处理流程使用
svc, cleanup := newAuth(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// sid 保存sid,供当前处理流程使用
sid, _, _ := svc.Login(ctx, "admin", "pw")
// protected 保存protected,供当前处理流程使用
protected := svc.Middleware(RequireAuth(RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
}))))
// 无 cookie → 401。
req := httptest.NewRequest(http.MethodGet, "/", nil)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
protected.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
@@ -85,6 +103,7 @@ func TestRequireAuthAndAdmin(t *testing.T) {
// 有 admin cookie → 200。
req2 := httptest.NewRequest(http.MethodGet, "/", nil)
req2.AddCookie(&http.Cookie{Name: CookieName, Value: sid})
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
protected.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
@@ -92,12 +111,16 @@ func TestRequireAuthAndAdmin(t *testing.T) {
}
}
// TestSetAndClearCookie 负责TestSetAndClear登录凭证相关处理。
func TestSetAndClearCookie(t *testing.T) {
// svc、cleanup 保存svc、cleanup,供当前处理流程使用
svc, cleanup := newAuth(t)
defer cleanup()
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
svc.SetSessionCookie(rec, "sid123")
// c 保存c,供当前处理流程使用
c := rec.Result().Cookies()
if len(c) != 1 || c[0].Name != CookieName || c[0].Value != "sid123" || !c[0].HttpOnly {
t.Fatalf("SetSessionCookie 异常: %+v", c)
@@ -106,8 +129,10 @@ func TestSetAndClearCookie(t *testing.T) {
t.Fatalf("SameSite 应为 Lax,got %v", c[0].SameSite)
}
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
svc.ClearSessionCookie(rec2)
// cc 保存cc,供当前处理流程使用
cc := rec2.Result().Cookies()
if len(cc) != 1 || cc[0].MaxAge != -1 {
t.Fatalf("ClearSessionCookie 应 MaxAge=-1: %+v", cc)
@@ -117,7 +142,9 @@ func TestSetAndClearCookie(t *testing.T) {
// newEmptyStore 构造未初始化 admin 的测试 store,供 InitAdmin 测试。
func newEmptyStore(t *testing.T) (*db.Store, func()) {
t.Helper()
// dbPath 保存db路径,供当前处理流程使用
dbPath := filepath.Join(t.TempDir(), "init.db")
// d、err 保存d、err,供当前处理流程使用
d, _, err := db.Open(context.Background(), dbPath)
if err != nil {
t.Fatalf("Open: %v", err)
@@ -127,8 +154,10 @@ func newEmptyStore(t *testing.T) (*db.Store, func()) {
// TestInitAdmin_CreateThenReset 全新库创建 admin,二次调用走重置路径。
func TestInitAdmin_CreateThenReset(t *testing.T) {
// store、cleanup 保存store、cleanup,供当前处理流程使用
store, cleanup := newEmptyStore(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// 全新库 → 创建。
@@ -136,6 +165,7 @@ func TestInitAdmin_CreateThenReset(t *testing.T) {
if err != nil || !created {
t.Fatalf("首次 InitAdmin 应创建:created=%v err=%v", created, err)
}
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(ctx, "admin")
if admin == nil || !admin.IsAdmin {
t.Fatalf("admin 未正确创建/标记: %+v", admin)
@@ -150,23 +180,29 @@ func TestInitAdmin_CreateThenReset(t *testing.T) {
if err != nil || created2 {
t.Fatalf("二次 InitAdmin 应重置:created=%v err=%v", created2, err)
}
if _, ok, _ := store.Users.VerifyAndUpgrade(ctx, "admin", "pw1"); ok {
if // ok 保存ok,供当前处理流程使用
_, ok, _ := store.Users.VerifyAndUpgrade(ctx, "admin", "pw1"); ok {
t.Fatal("旧密码 pw1 应已失效")
}
if _, ok, _ := store.Users.VerifyAndUpgrade(ctx, "admin", "pw2"); !ok {
if // ok 保存ok,供当前处理流程使用
_, ok, _ := store.Users.VerifyAndUpgrade(ctx, "admin", "pw2"); !ok {
t.Fatal("新密码 pw2 应可用")
}
}
// TestInitAdmin_DoesNotValidatePassword 密码强度校验由调用方负责(ensureAdmin),
// InitAdmin 本身不拒绝空密码,仅保证不 panic 且能完成创建。
// TestInitAdmin_DoesNotValidatePassword 负责TestInitAdminDoesNotValidate密码相关处理。
func TestInitAdmin_DoesNotValidatePassword(t *testing.T) {
// store、cleanup 保存store、cleanup,供当前处理流程使用
store, cleanup := newEmptyStore(t)
defer cleanup()
if _, err := InitAdmin(context.Background(), store, "a@e.com", ""); err != nil {
if // err 保存err,供当前处理流程使用
_, err := InitAdmin(context.Background(), store, "a@e.com", ""); err != nil {
t.Fatalf("InitAdmin 不应自行拒绝空密码: %v", err)
}
if admin, _ := store.Users.GetByUsername(context.Background(), "admin"); admin == nil {
if // admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(context.Background(), "admin"); admin == nil {
t.Fatal("空密码也应创建 admin")
}
}
+7
View File
@@ -8,14 +8,18 @@ import (
)
// Level is the process-wide dynamic slog level.
// Level 保存Level,供当前处理流程使用
var Level slog.LevelVar
// init 负责init相关处理。
func init() {
Level.Set(slog.LevelInfo)
}
// NewLogger creates a slog logger wired to the dynamic Level.
// NewLogger 负责NewLogger相关处理。
func NewLogger(w io.Writer, format string) *slog.Logger {
// opts 保存opts,供当前处理流程使用
opts := &slog.HandlerOptions{Level: &Level}
if strings.EqualFold(strings.TrimSpace(format), "json") {
return slog.New(slog.NewJSONHandler(w, opts))
@@ -24,7 +28,9 @@ func NewLogger(w io.Writer, format string) *slog.Logger {
}
// SetLevel updates the process-wide log level.
// SetLevel 设置Level。
func SetLevel(raw string) error {
// lv、err 保存lv、err,供当前处理流程使用
lv, err := ParseLevel(raw)
if err != nil {
return err
@@ -34,6 +40,7 @@ func SetLevel(raw string) error {
}
// ParseLevel parses debug/info/warn/error.
// ParseLevel 解析Level。
func ParseLevel(raw string) (slog.Level, error) {
switch strings.ToLower(strings.TrimSpace(raw)) {
case "", "info":
+14 -3
View File
@@ -7,9 +7,11 @@ import (
"testing"
)
// TestParseLevelAndSetLevel 负责TestParseLevelAndSetLevel相关处理。
func TestParseLevelAndSetLevel(t *testing.T) {
defer Level.Set(slog.LevelInfo)
// cases 保存cases,供当前处理流程使用
cases := map[string]slog.Level{
"": slog.LevelInfo,
"debug": slog.LevelDebug,
@@ -17,7 +19,9 @@ func TestParseLevelAndSetLevel(t *testing.T) {
"warning": slog.LevelWarn,
"error": slog.LevelError,
}
// in、want 表示当前遍历过程中的in、want
for in, want := range cases {
// got、err 保存got、err,供当前处理流程使用
got, err := ParseLevel(in)
if err != nil {
t.Fatalf("ParseLevel(%q): %v", in, err)
@@ -26,25 +30,32 @@ func TestParseLevelAndSetLevel(t *testing.T) {
t.Fatalf("ParseLevel(%q)=%v want %v", in, got, want)
}
}
if _, err := ParseLevel("verbose"); err == nil {
if // err 保存err,供当前处理流程使用
_, err := ParseLevel("verbose"); err == nil {
t.Fatal("invalid level should fail")
}
if err := SetLevel("debug"); err != nil {
if // err 保存err,供当前处理流程使用
err := SetLevel("debug"); err != nil {
t.Fatalf("SetLevel: %v", err)
}
if got := Level.Level(); got != slog.LevelDebug {
if // got 保存got,供当前处理流程使用
got := Level.Level(); got != slog.LevelDebug {
t.Fatalf("global level=%v want debug", got)
}
}
// TestNewLoggerHonorsDynamicLevel 负责TestNewLoggerHonorsDynamicLevel相关处理。
func TestNewLoggerHonorsDynamicLevel(t *testing.T) {
defer Level.Set(slog.LevelInfo)
// buf 保存buf,供当前处理流程使用
var buf bytes.Buffer
// logger 保存logger,供当前处理流程使用
logger := NewLogger(&buf, "text")
Level.Set(slog.LevelWarn)
logger.Info("hidden")
logger.Warn("visible")
// out 保存out,供当前处理流程使用
out := buf.String()
if strings.Contains(out, "hidden") {
t.Fatalf("info log should be filtered: %s", out)
+4
View File
@@ -10,17 +10,21 @@ import (
)
// ID returns a short stable fingerprint for a sensitive identifier.
// ID 负责标识相关处理。
func ID(s string) string {
s = strings.TrimSpace(s)
if s == "" {
return ""
}
// sum 保存sum,供当前处理流程使用
sum := sha256.Sum256([]byte(s))
return hex.EncodeToString(sum[:])[:12]
}
// URL returns origin + path for URLs that may contain session tokens.
// URL 负责URL相关处理。
func URL(raw string) string {
// u、err 保存u、err,供当前处理流程使用
u, err := url.Parse(strings.TrimSpace(raw))
if err != nil || u.Scheme == "" || u.Host == "" {
return "<redacted>"
+5 -2
View File
@@ -2,6 +2,7 @@ package logsafe
import "testing"
// TestRedactionHelpers 负责TestRedactionHelpers相关处理。
func TestRedactionHelpers(t *testing.T) {
if ID(" secret ") != ID("secret") || len(ID("secret")) != 12 {
t.Fatal("ID should be trimmed, stable, and short")
@@ -9,10 +10,12 @@ func TestRedactionHelpers(t *testing.T) {
if ID("") != "" {
t.Fatal("empty ID should remain empty")
}
if got := URL("https://example.com/path?q=token#secret"); got != "https://example.com/path" {
if // got 保存got,供当前处理流程使用
got := URL("https://example.com/path?q=token#secret"); got != "https://example.com/path" {
t.Fatalf("URL leaked query or fragment: %q", got)
}
if got := URL("not-a-url"); got != "<redacted>" {
if // got 保存got,供当前处理流程使用
got := URL("not-a-url"); got != "<redacted>" {
t.Fatalf("invalid URL = %q", got)
}
}
+16
View File
@@ -13,6 +13,7 @@ import (
"time"
)
// nonPublicPrefixes 保存nonPublicPrefixes,供当前处理流程使用
var nonPublicPrefixes = []netip.Prefix{
netip.MustParsePrefix("0.0.0.0/8"), netip.MustParsePrefix("10.0.0.0/8"),
netip.MustParsePrefix("100.64.0.0/10"), netip.MustParsePrefix("127.0.0.0/8"),
@@ -28,6 +29,7 @@ var nonPublicPrefixes = []netip.Prefix{
// PublicHTTPClient 返回只允许连接公网 IP 的客户端。DNS 与每次重定向都会重新校验。
func PublicHTTPClient(timeout time.Duration) *http.Client {
// transport 保存transport,供当前处理流程使用
transport := &http.Transport{
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
return DialPublicContext(ctx, network, address, 10*time.Second)
@@ -51,7 +53,9 @@ func PublicHTTPClient(timeout time.Duration) *http.Client {
// TrustedEndpointHTTPClient 用于管理员明确配置的集成端点。目标地址完全由管理员
// 信任并负责,因此不限制 IP 类型、DNS 结果或 HTTP 重定向;仅校验 HTTP(S) URL。
// TrustedEndpointHTTPClient 负责TrustedEndpointHTTPClient相关处理。
func TrustedEndpointHTTPClient(rawBaseURL string, timeout time.Duration) (*http.Client, error) {
// baseURL、err 保存baseURL、err,供当前处理流程使用
baseURL, err := url.Parse(strings.TrimSpace(rawBaseURL))
if err != nil || baseURL.Hostname() == "" {
return nil, fmt.Errorf("服务地址无效")
@@ -59,6 +63,7 @@ func TrustedEndpointHTTPClient(rawBaseURL string, timeout time.Duration) (*http.
if baseURL.Scheme != "http" && baseURL.Scheme != "https" {
return nil, fmt.Errorf("服务地址只支持 http 或 https")
}
// transport 保存transport,供当前处理流程使用
transport := http.DefaultTransport.(*http.Transport).Clone()
return &http.Client{
Transport: transport,
@@ -66,7 +71,9 @@ func TrustedEndpointHTTPClient(rawBaseURL string, timeout time.Duration) (*http.
}, nil
}
// IsPublicIP 负责IsPublicIP相关处理。
func IsPublicIP(ip net.IP) bool {
// addr、ok 保存addr、ok,供当前处理流程使用
addr, ok := netip.AddrFromSlice(ip)
if !ok {
return false
@@ -75,6 +82,7 @@ func IsPublicIP(ip net.IP) bool {
if !addr.IsGlobalUnicast() {
return false
}
// prefix 表示当前遍历过程中的prefix
for _, prefix := range nonPublicPrefixes {
if prefix.Contains(addr) {
return false
@@ -89,23 +97,31 @@ func DialPublicContext(ctx context.Context, network, address string, timeout tim
"拒绝访问非公网地址", "连接公网地址失败")
}
// dialContextWithPolicy 负责dial上下文WithPolicy相关处理。
func dialContextWithPolicy(ctx context.Context, network, address string, timeout time.Duration,
allow func(net.IP) bool, deniedMessage, connectErrorMessage string,
) (net.Conn, error) {
// host、port、err 保存host、port、err,供当前处理流程使用
host, port, err := net.SplitHostPort(address)
if err != nil {
return nil, err
}
// ips、err 保存ips、err,供当前处理流程使用
ips, err := net.DefaultResolver.LookupIPAddr(ctx, host)
if err != nil {
return nil, err
}
// dialer 保存dialer,供当前处理流程使用
dialer := &net.Dialer{Timeout: timeout, KeepAlive: 30 * time.Second}
// lastErr 保存lastErr,供当前处理流程使用
var lastErr error
// foundAllowed 保存foundAllowed,供当前处理流程使用
foundAllowed := false
// resolved 表示当前遍历过程中的resolved
for _, resolved := range ips {
if allow(resolved.IP) {
foundAllowed = true
// conn、dialErr 保存conn、dialErr,供当前处理流程使用
conn, dialErr := dialer.DialContext(ctx, network, net.JoinHostPort(resolved.IP.String(), port))
if dialErr == nil {
return conn, nil
+21 -2
View File
@@ -9,7 +9,9 @@ import (
"testing"
)
// TestIsPublicIP 负责TestIsPublicIP相关处理。
func TestIsPublicIP(t *testing.T) {
// raw 表示当前遍历过程中的原始
for _, raw := range []string{
"127.0.0.1", "10.0.0.1", "172.16.1.1", "192.168.1.1", "169.254.169.254", "::1",
"100.64.0.1", "198.18.0.1", "192.0.2.1", "198.51.100.1", "203.0.113.1", "2001:db8::1",
@@ -23,30 +25,41 @@ func TestIsPublicIP(t *testing.T) {
}
}
// TestPublicHTTPClientRejectsLoopback 负责TestPublicHTTPClientRejectsLoopback相关处理。
func TestPublicHTTPClientRejectsLoopback(t *testing.T) {
// client 保存client,供当前处理流程使用
client := PublicHTTPClient(0)
// req 保存req,供当前处理流程使用
req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://127.0.0.1:1", nil)
if _, err := client.Do(req); err == nil {
if // err 保存err,供当前处理流程使用
_, err := client.Do(req); err == nil {
t.Fatal("loopback request must be rejected")
}
}
// TestTrustedEndpointHTTPClientAllowsLoopbackAndUnspecifiedAddress 负责TestTrustedEndpointHTTPClientAllowsLoopbackAndUnspecifiedAddress相关处理。
func TestTrustedEndpointHTTPClientAllowsLoopbackAndUnspecifiedAddress(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNoContent)
}))
t.Cleanup(server.Close)
// port、err 保存port、err,供当前处理流程使用
_, port, err := net.SplitHostPort(strings.TrimPrefix(server.URL, "http://"))
if err != nil {
t.Fatal(err)
}
// host 表示当前遍历过程中的host
for _, host := range []string{"127.0.0.1", "0.0.0.0"} {
// baseURL 保存baseURL,供当前处理流程使用
baseURL := "http://" + net.JoinHostPort(host, port)
// client、clientErr 保存client、clientErr,供当前处理流程使用
client, clientErr := TrustedEndpointHTTPClient(baseURL+"/v1", 0)
if clientErr != nil {
t.Fatal(clientErr)
}
// resp、requestErr 保存resp、requestErr,供当前处理流程使用
resp, requestErr := client.Get(baseURL + "/v1/models")
if requestErr != nil {
t.Fatalf("trusted endpoint should reach %s: %v", host, requestErr)
@@ -58,11 +71,14 @@ func TestTrustedEndpointHTTPClientAllowsLoopbackAndUnspecifiedAddress(t *testing
}
}
// TestTrustedEndpointHTTPClientDoesNotApplyAddressPolicy 负责TestTrustedEndpointHTTPClientDoesNotApplyAddressPolicy相关处理。
func TestTrustedEndpointHTTPClientDoesNotApplyAddressPolicy(t *testing.T) {
// raw 表示当前遍历过程中的原始
for _, raw := range []string{
"http://0.0.0.0:8080/v1", "http://127.0.0.1:8080/v1", "http://169.254.169.254/v1",
"http://192.168.0.220/v1", "http://[::1]:8080/v1", "https://user:pass@ai.internal/v1",
} {
// client、err 保存client、err,供当前处理流程使用
client, err := TrustedEndpointHTTPClient(raw, 0)
if err != nil {
t.Fatalf("admin-configured address should be accepted (%s): %v", raw, err)
@@ -73,9 +89,12 @@ func TestTrustedEndpointHTTPClientDoesNotApplyAddressPolicy(t *testing.T) {
}
}
// TestTrustedEndpointHTTPClientValidatesBaseURL 负责TestTrustedEndpointHTTPClientValidatesBaseURL相关处理。
func TestTrustedEndpointHTTPClientValidatesBaseURL(t *testing.T) {
// raw 表示当前遍历过程中的原始
for _, raw := range []string{"", "file:///tmp/model", "://bad"} {
if _, err := TrustedEndpointHTTPClient(raw, 0); err == nil {
if // err 保存err,供当前处理流程使用
_, err := TrustedEndpointHTTPClient(raw, 0); err == nil {
t.Fatalf("invalid base URL should fail: %q", raw)
}
}
+3
View File
@@ -3,6 +3,7 @@ package version
import "strings"
// Version 保存Version,供当前处理流程使用
var (
Version = "dev"
Commit = "unknown"
@@ -10,7 +11,9 @@ var (
)
// ShortCommit returns a compact commit identifier suitable for UI display.
// ShortCommit 负责ShortCommit相关处理。
func ShortCommit() string {
// commit 保存commit,供当前处理流程使用
commit := strings.TrimSpace(Commit)
if len(commit) > 12 {
return commit[:12]
+4 -1
View File
@@ -2,12 +2,15 @@ package version
import "testing"
// TestShortCommit 负责TestShortCommit相关处理。
func TestShortCommit(t *testing.T) {
// original 保存original,供当前处理流程使用
original := Commit
t.Cleanup(func() { Commit = original })
Commit = "0123456789abcdef"
if got := ShortCommit(); got != "0123456789ab" {
if // got 保存got,供当前处理流程使用
got := ShortCommit(); got != "0123456789ab" {
t.Fatalf("ShortCommit() = %q", got)
}
}
+3
View File
@@ -6,10 +6,13 @@ import (
"io/fs"
)
// files 保存文件列表,供当前处理流程使用
//
//go:embed static/*
var files embed.FS
// Static returns the embedded built frontend rooted at static/.
// Static 负责Static相关处理。
func Static() (fs.FS, error) {
return fs.Sub(files, "static")
}
+3
View File
@@ -5,11 +5,14 @@ import (
"testing"
)
// TestStaticContainsIndex 负责TestStaticContainsIndex相关处理。
func TestStaticContainsIndex(t *testing.T) {
// static、err 保存static、err,供当前处理流程使用
static, err := Static()
if err != nil {
t.Fatal(err)
}
// data、err 保存data、err,供当前处理流程使用
data, err := fs.ReadFile(static, "index.html")
if err != nil || len(data) == 0 {
t.Fatalf("embedded index missing: %v", err)