An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:rewind: Restore encrypted notebook password trimming https://github.com/siyuan-note/siyuan/issues/19477
Daniel012ae7a161b0
diff --git a/app/src/config/tabs/accessTab.test.ts b/app/src/config/tabs/accessTab.test.tsindex dfb5f04aa0..52f78873d0 100644--- a/app/src/config/tabs/accessTab.test.ts+++ b/app/src/config/tabs/accessTab.test.ts@@ -51,7 +51,7 @@ test("encrypted notebook system lock is offered only for supported local desktop}});-test("crypto backup import preserves password bytes and rejects only an empty input", async () => {+test("crypto backup import trims passwords and rejects whitespace-only input", async () => {const compiled = transpileModule(readFileSync("src/config/tabs/accessTab.ts", "utf8") +"\nexport {mountEncryptedNotebook};", {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},@@ -91,12 +91,14 @@ test("crypto backup import preserves password bytes and rejects only an empty inlisteners.get("#importCryptoBackupBtn")();const dialog = {destroy: () => { destroyed++; }};confirm("", dialog);+ confirm(" ", dialog);+ confirm("\t\u00a0\u3000\n", dialog);assert.equal(requests.length, 0);- for (const password of [" password ", " ", "\tpassword\n", "\u00a0password\u3000"]) {+ for (const password of [" password ", "\tpassword\n", "\u00a0password\u3000"]) {confirm(password, dialog);await Promise.resolve();- assert.equal(requests[requests.length - 1].get("password"), password);+ assert.equal(requests[requests.length - 1].get("password"), password.trim());assert.ok(requests[requests.length - 1].get("file") instanceof Blob);}- assert.equal(destroyed, 4);+ assert.equal(destroyed, 3);});diff --git a/app/src/config/tabs/accessTab.ts b/app/src/config/tabs/accessTab.tsindex 703cbb03bd..da5352b503 100644--- a/app/src/config/tabs/accessTab.ts+++ b/app/src/config/tabs/accessTab.ts@@ -812,7 +812,7 @@ const mountEncryptedNotebook = (root: HTMLElement) => {placeholder: window.siyuan.languages.masterPassword,width: "520px",onConfirm: (value, passwordDialog) => {- const password = value;+ const password = value.trim();if (!password) {showMessage(window.siyuan.languages.enterMasterPassword);return;diff --git a/docs/API-CONTRACTS.md b/docs/API-CONTRACTS.mdindex 10ac2c4fd9..9397301e62 100644--- a/docs/API-CONTRACTS.md+++ b/docs/API-CONTRACTS.md@@ -30,11 +30,11 @@ Arrays, maps, and nested structs recursively validate request constraints. A `nuNotebook creation, renaming, removal, closing, icon updates, and sorting use typed contracts. Renaming, removal, and icon updates trim notebook IDs; closing preserves whitespace for ID validation. Empty names and icons remain available to business validation, and rename failures retain their message display duration.-Encrypted notebook lifecycle endpoints preserve passwords exactly, including leading, trailing, and all-whitespace strings. The `nonempty` string option rejects only an empty string without normalization; required password fields also reject omission, null, and non-string values. Backup import preserves multipart password text and retains its optional-field behavior, with authentication performed by the model. Fractional-minute truncation, negative-minute clamping, administrative authorization, lease acquisition, and mount rollback remain unchanged. Key derivation, ciphertext formats, and recovery material remain model-layer responsibilities.+Encrypted notebook lifecycle endpoints use typed requests and responses while retaining password trimming, fractional-minute truncation, negative-minute clamping, administrative authorization, lease acquisition, and mount rollback. Key derivation, ciphertext formats, and recovery material remain model-layer responsibilities.## Compatibility requirements-Encrypted notebook system-lock endpoints preserve administrator authorization and read-only checks. The boolean preference lives in system configuration, outside authenticated key backups. `TestAPIContractNotebookSystemLock` covers persistence, disabled behavior, independence from the idle timeout, multiple notebooks (including an unlocked but unmounted notebook), repeated locking, denied reads after locking, and authenticated reads of unchanged ciphertext after re-unlocking. It is included in the full kernel command below; run it separately with `go test -tags "fts5 sqlcipher" ./api -run 'TestAPIContractNotebook(SystemLock|CryptoAuthorization|PasswordRecovery)$' -count=1`. `TestNotebookSystemLockContract` covers strict boolean input and `TestRouteCoverage` checks registration and handler bindings.+Encrypted notebook system-lock endpoints preserve administrator authorization and read-only checks. The boolean preference lives in system configuration, outside authenticated key backups. `TestAPIContractNotebookSystemLock` covers persistence, disabled behavior, independence from the idle timeout, multiple notebooks (including an unlocked but unmounted notebook), repeated locking, denied reads after locking, and authenticated reads of unchanged ciphertext after re-unlocking. It is included in the full kernel command below; run it separately with `go test -tags "fts5 sqlcipher" ./api -run 'TestAPIContractNotebook(SystemLock|CryptoAuthorization)$' -count=1`. `TestNotebookSystemLockContract` covers strict boolean input and `TestRouteCoverage` checks registration and handler bindings.At migration completion on September 14, 2026, all 629 method/path registrations in `kernel/api/router.go` were contracted and the legacy list was empty. At that baseline, four `ANY` registrations expanded to 661 concrete method/path pairs in generated metadata. Use the generator and route coverage checks for current counts as endpoints are added. Static resources, the main application WebSocket, and other transport services registered by `kernel/server/serve.go` are outside this API route inventory.diff --git a/docs/API-CONTRACTS.zh-CN.md b/docs/API-CONTRACTS.zh-CN.mdindex e869f0a47c..e040883431 100644--- a/docs/API-CONTRACTS.zh-CN.md+++ b/docs/API-CONTRACTS.zh-CN.md@@ -30,11 +30,11 @@笔记本创建、重命名、删除、关闭、图标更新和排序已接入类型契约。重命名、删除和图标更新会去除笔记本 ID 两端空白;关闭保留空白并交给 ID 校验。空名称和空图标仍交给业务层处理,重命名失败保留提示显示时长。-加密笔记本生命周期接口原样保留密码,包括首尾空白及仅含空白的字符串。字符串选项 `nonempty` 仅拒绝空字符串,不执行规范化;必填密码字段同时拒绝缺失、null 和非字符串值。备份导入原样保留表单中的密码文本及其可选字段行为,由模型层执行认证。分钟数截断与负值归零、管理员权限、租约获取和挂载失败回滚保持不变。密钥派生、密文格式及恢复材料仍由模型层维护。+加密笔记本生命周期接口使用类型化请求与响应,保留密码去除两端空白、分钟数截断与负值归零、管理员权限、租约获取和挂载失败回滚。密钥派生、密文格式及恢复材料仍由模型层维护。## 兼容要求-加密笔记本系统锁屏接口保留管理员鉴权和只读检查。布尔开关保存在系统配置中,不进入密钥备份的认证数据。`TestAPIContractNotebookSystemLock` 覆盖配置持久化、关闭开关、独立于闲置时间、多笔记本(包括仅解锁未挂载的笔记本)、重复锁定、锁定后拒绝读取,以及重新解锁后认证读取未改变的密文。该测试已包含在下文的内核全量命令中,也可单独运行 `go test -tags "fts5 sqlcipher" ./api -run 'TestAPIContractNotebook(SystemLock|CryptoAuthorization|PasswordRecovery)$' -count=1`。`TestNotebookSystemLockContract` 覆盖严格布尔输入,`TestRouteCoverage` 检查路由注册和处理器绑定。+加密笔记本系统锁屏接口保留管理员鉴权和只读检查。布尔开关保存在系统配置中,不进入密钥备份的认证数据。`TestAPIContractNotebookSystemLock` 覆盖配置持久化、关闭开关、独立于闲置时间、多笔记本(包括仅解锁未挂载的笔记本)、重复锁定、锁定后拒绝读取,以及重新解锁后认证读取未改变的密文。该测试已包含在下文的内核全量命令中,也可单独运行 `go test -tags "fts5 sqlcipher" ./api -run 'TestAPIContractNotebook(SystemLock|CryptoAuthorization)$' -count=1`。`TestNotebookSystemLockContract` 覆盖严格布尔输入,`TestRouteCoverage` 检查路由注册和处理器绑定。2026 年 9 月 14 日迁移完成时,`kernel/api/router.go` 中的 629 条方法和路径注册均已接入契约,旧路由清单为空。该基线中的 4 条 `ANY` 注册在生成声明中展开为 661 条具体方法和路径。后续新增接口时,以生成器和路由覆盖检查的统计为准。由 `kernel/server/serve.go` 注册的静态资源、应用主 WebSocket 和其他传输服务不属于这份 API 路由清单。diff --git a/kernel/api/contract_basics_test.go b/kernel/api/contract_basics_test.goindex 249e284bc0..3e522ebb28 100644--- a/kernel/api/contract_basics_test.go+++ b/kernel/api/contract_basics_test.go@@ -52,13 +52,13 @@ func TestAPIContractBasicRequests(t *testing.T) {{"/api/notebook/reorder", `{}`, reorderNotebooks, -1},{"/api/notebook/openNotebook", `{"notebook":"invalid"}`, openNotebook, -1},{"/api/notebook/getNotebookConf", `{"notebook":" 20260101000000-abcdefg "}`, getNotebookConf, -1},- {"/api/notebook/enableEncryptedNotebooks", `{"password":""}`, enableEncryptedNotebooks, -1},+ {"/api/notebook/enableEncryptedNotebooks", `{"password":" "}`, enableEncryptedNotebooks, -1},{"/api/notebook/createEncryptedNotebook", `{"name":"name","password":null}`, createEncryptedNotebook, -1},{"/api/notebook/unlockNotebook", `{"notebook":"invalid","password":"password"}`, unlockNotebook, -1},{"/api/notebook/unlockAndOpenNotebook", `{"notebook":"invalid","password":"password"}`, unlockAndOpenNotebook, -1},{"/api/notebook/lockNotebook", `{"notebook":"invalid"}`, lockNotebook, -1},{"/api/notebook/setNotebookCryptoAutoLock", `{"autoLockMinutes":"1"}`, setNotebookCryptoAutoLock, -1},- {"/api/notebook/changeMasterPassword", `{"oldPassword":"old","newPassword":""}`, changeMasterPassword, -1},+ {"/api/notebook/changeMasterPassword", `{"oldPassword":"old","newPassword":" "}`, changeMasterPassword, -1},{"/api/notebook/createNotebook", `{}`, createNotebook, -1},{"/api/notebook/setNotebookIcon", `{"notebook":"../escape","icon":""}`, setNotebookIcon, -1},{"/api/notebook/renameNotebook", `{"notebook":"invalid","name":"name"}`, renameNotebook, -1},diff --git a/kernel/api/contract_notebook_password_test.go b/kernel/api/contract_notebook_password_test.godeleted file mode 100644index c997801e16..0000000000--- a/kernel/api/contract_notebook_password_test.go+++ /dev/null@@ -1,161 +0,0 @@-package api--import (- "bytes"- "context"- "encoding/json"- "mime/multipart"- "net/http"- "net/http/httptest"- "os"- "os/exec"- "path/filepath"- "strings"- "testing"- "time"-- "github.com/gin-gonic/gin"- "github.com/siyuan-note/siyuan/kernel/conf"- "github.com/siyuan-note/siyuan/kernel/model"- "github.com/siyuan-note/siyuan/kernel/sql"- "github.com/siyuan-note/siyuan/kernel/util"-)--func TestAPIContractNotebookPasswordRecovery(t *testing.T) {- const helper = "SIYUAN_TEST_NOTEBOOK_PASSWORD_RECOVERY"- if os.Getenv(helper) != "1" {- // 加密缓存和数据库属于进程级状态,在独立进程中验证完整恢复链路。- ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)- defer cancel()- command := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestAPIContractNotebookPasswordRecovery$", "-test.v")- command.Env = append(os.Environ(), helper+"=1")- if output, err := command.CombinedOutput(); err != nil {- t.Fatalf("password recovery subprocess failed: %v\n%s", err, output)- }- return- }- root := t.TempDir()- util.WorkspaceDir = root- util.DataDir, util.TempDir = filepath.Join(root, "data"), filepath.Join(root, "temp")- util.ConfDir, util.HistoryDir = filepath.Join(root, "conf"), filepath.Join(root, "history")- util.QueueDir = filepath.Join(util.TempDir, "queue")- util.DBPath, util.HistoryDBPath = filepath.Join(util.TempDir, "siyuan.db"), filepath.Join(util.TempDir, "history.db")- util.AssetContentDBPath, util.BlockTreeDBPath = filepath.Join(util.TempDir, "asset_content.db"), filepath.Join(util.TempDir, "blocktree.db")- for _, dir := range []string{util.DataDir, util.TempDir, util.ConfDir, util.HistoryDir} {- if err := os.MkdirAll(dir, 0755); err != nil {- t.Fatal(err)- }- }- model.Conf = model.NewAppConf()- model.Conf.NotebookCrypto, model.Conf.FileTree = conf.NewNotebookCrypto(), conf.NewFileTree()- model.Conf.Sync = conf.NewSync()- model.Conf.Editor, model.Conf.Search, model.Conf.Export = conf.NewEditor(), conf.NewSearch(), conf.NewExport()- sql.InitDatabase(true)- sql.InitHistoryDatabase(true)- sql.InitAssetContentDatabase(true)- defer sql.CloseDatabase()- const originalPassword = " old password\t"- const newPassword = "\u00a0new password\u3000"- // 使用未经过接口规范化的模型入口准备已有密码,模拟升级前创建的密钥域。- if err := model.EnableEncryptedNotebook(originalPassword); err != nil {- t.Fatal(err)- }- salt := bytes.Clone(model.Conf.NotebookCrypto.MasterSalt)- boxID, err := model.CreateEncryptedBox("Password recovery", originalPassword)- if err != nil {- t.Fatal(err)- }- dek, err := model.GetDEK(boxID)- if err != nil {- t.Fatal(err)- }- const assetName = "fixture.bin"- ciphertext, err := model.EncryptAsset(boxID, assetName, assetName, dek, []byte("existing encrypted data"))- if err != nil {- t.Fatal(err)- }- model.Unmount(boxID)- model.LockBox(boxID)- gin.SetMode(gin.TestMode)- engine := gin.New()- engine.Use(boxLeaseMiddleware)- engine.POST("/api/notebook/enableEncryptedNotebooks", enableEncryptedNotebooks)- engine.POST("/api/notebook/unlockNotebook", unlockNotebook)- engine.POST("/api/notebook/unlockAndOpenNotebook", unlockAndOpenNotebook)- engine.POST("/api/notebook/changeMasterPassword", changeMasterPassword)- engine.POST("/api/notebook/importNotebookCryptoBackup", importNotebookCryptoBackup)- request := func(req *http.Request, success bool) {- t.Helper()- recorder := httptest.NewRecorder()- engine.ServeHTTP(recorder, req)- requireAPIContract(t, http.MethodPost, req.URL.Path, recorder)- var response struct {- Code int `json:"code"`- }- if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || (response.Code == 0) != success {- t.Fatalf("%s: unexpected response %s, %v", req.URL.Path, recorder.Body.String(), err)- }- }- post := func(endpoint string, body map[string]string, success bool) {- t.Helper()- data, _ := json.Marshal(body)- req := httptest.NewRequest(http.MethodPost, "/api/notebook/"+endpoint, bytes.NewReader(data))- req.Header.Set("Content-Type", "application/json")- request(req, success)- }- verifyContent := func() {- t.Helper()- key, err := model.GetDEK(boxID)- if err != nil {- t.Fatal(err)- }- plain, err := model.DecryptAsset(boxID, assetName, key, ciphertext)- if err != nil || string(plain) != "existing encrypted data" || !bytes.Equal(salt, model.Conf.NotebookCrypto.MasterSalt) {- t.Fatalf("existing data or master salt changed: %v", err)- }- model.Unmount(boxID)- model.LockBox(boxID)- }- post("enableEncryptedNotebooks", map[string]string{"password": originalPassword}, true)- for _, endpoint := range []string{"unlockNotebook", "unlockAndOpenNotebook"} {- post(endpoint, map[string]string{"notebook": boxID, "password": strings.TrimSpace(originalPassword)}, false)- post(endpoint, map[string]string{"notebook": boxID, "password": originalPassword}, true)- verifyContent()- }- post("changeMasterPassword", map[string]string{"oldPassword": strings.TrimSpace(originalPassword), "newPassword": newPassword}, false)- post("changeMasterPassword", map[string]string{"oldPassword": originalPassword, "newPassword": newPassword}, true)- post("unlockNotebook", map[string]string{"notebook": boxID, "password": strings.TrimSpace(newPassword)}, false)- post("unlockNotebook", map[string]string{"notebook": boxID, "password": newPassword}, true)- verifyContent()- backupPath, err := model.ExportNotebookCryptoBackup()- if err != nil {- t.Fatal(err)- }- backup, err := os.ReadFile(filepath.Join(util.TempDir, "export", filepath.Base(backupPath)))- if err != nil {- t.Fatal(err)- }- model.Conf.NotebookCrypto = conf.NewNotebookCrypto()- for _, password := range []string{strings.TrimSpace(newPassword), newPassword} {- var body bytes.Buffer- writer := multipart.NewWriter(&body)- file, err := writer.CreateFormFile("file", "backup.json")- if err != nil {- t.Fatal(err)- }- if _, err = file.Write(backup); err != nil {- t.Fatal(err)- }- if err = writer.WriteField("password", password); err != nil {- t.Fatal(err)- }- if err = writer.Close(); err != nil {- t.Fatal(err)- }- req := httptest.NewRequest(http.MethodPost, "/api/notebook/importNotebookCryptoBackup", &body)- req.Header.Set("Content-Type", writer.FormDataContentType())- request(req, password == newPassword)- }- post("unlockNotebook", map[string]string{"notebook": boxID, "password": newPassword}, true)- verifyContent()-}diff --git a/kernel/apicontract/decode.go b/kernel/apicontract/decode.goindex c825219b3d..d8a19be77d 100644--- a/kernel/apicontract/decode.go+++ b/kernel/apicontract/decode.go@@ -120,9 +120,6 @@ func decodeRequestFields(value reflect.Value, fields map[string]json.RawMessage)}value.Field(i).SetString(trimmed)}- if has("nonempty") && value.Field(i).String() == "" {- return fmt.Errorf("Field [%s] must not be empty", name)- }for _, option := range strings.Split(field.Tag.Get("api"), ",") {if strings.HasPrefix(option, "enum=") {if field.Type.Kind() != reflect.String {diff --git a/kernel/apicontract/notebook.go b/kernel/apicontract/notebook.goindex 421075ce9c..040f867ea2 100644--- a/kernel/apicontract/notebook.go+++ b/kernel/apicontract/notebook.go@@ -89,7 +89,7 @@ type EncryptedNotebookStatusData struct {}type NotebookPasswordRequest struct {- Password string `json:"password" api:"nonempty"`+ Password string `json:"password" api:"trim"`}type CreateEncryptedNotebookRequest struct {@@ -103,8 +103,8 @@ type UnlockNotebookRequest struct {}type ChangeMasterPasswordRequest struct {- OldPassword string `json:"oldPassword" api:"nonempty"`- NewPassword string `json:"newPassword" api:"nonempty"`+ OldPassword string `json:"oldPassword" api:"trim"`+ NewPassword string `json:"newPassword" api:"trim"`}type NotebookCryptoAutoLockRequest struct {diff --git a/kernel/apicontract/notebook_test.go b/kernel/apicontract/notebook_test.goindex 86d942bef5..842e549ec4 100644--- a/kernel/apicontract/notebook_test.go+++ b/kernel/apicontract/notebook_test.go@@ -2,63 +2,10 @@ package apicontractimport ("encoding/json"- "mime/multipart""strings""testing")-func TestNotebookPasswordBytes(t *testing.T) {- for _, password := range []string{" secret ", " ", "\tpassword\n", "\u00a0password\u3000"} {- encoded, _ := json.Marshal(password)- body := `{"notebook":"20260101000000-abcdefg","name":"Encrypted","password":` + string(encoded) + `}`- enabled, err := EnableEncryptedNotebooks.Decode(strings.NewReader(body))- if err != nil || enabled.Password != password {- t.Fatalf("enable changed password bytes: %v", err)- }- created, err := CreateEncryptedNotebook.Decode(strings.NewReader(body))- if err != nil || created.Password != password {- t.Fatalf("create changed password bytes: %v", err)- }- for _, endpoint := range []Endpoint[UnlockNotebookRequest, Null]{UnlockNotebook, UnlockAndOpenNotebook} {- unlocked, err := endpoint.Decode(strings.NewReader(body))- if err != nil || unlocked.Password != password {- t.Fatalf("%s changed password bytes: %v", endpoint.Definition().Path, err)- }- }- changed, err := ChangeMasterPassword.Decode(strings.NewReader(`{"oldPassword":` + string(encoded) + `,"newPassword":` + string(encoded) + `}`))- if err != nil || changed.OldPassword != password || changed.NewPassword != password {- t.Fatalf("password change normalized input: %v", err)- }- form := &multipart.Form{Value: map[string][]string{"password": {password}}, File: map[string][]*multipart.FileHeader{"file": {{Filename: "backup.json"}}}}- backup, err := ImportNotebookCryptoBackup.DecodeMultipart(form)- if err != nil || backup.Password != password {- t.Fatalf("backup import changed password bytes: %v", err)- }- }- for _, field := range []string{"oldPassword", "newPassword"} {- for _, invalid := range []string{"", `null`, `""`, `123`} {- body := map[string]json.RawMessage{"oldPassword": json.RawMessage(`"old"`), "newPassword": json.RawMessage(`"new"`)}- if invalid == "" {- delete(body, field)- } else {- body[field] = json.RawMessage(invalid)- }- data, _ := json.Marshal(body)- if _, err := ChangeMasterPassword.Decode(strings.NewReader(string(data))); err == nil {- t.Fatalf("invalid %s accepted: %s", field, data)- }- }- }- for _, values := range []map[string][]string{nil, {"password": {""}}} {- request, err := ImportNotebookCryptoBackup.DecodeMultipart(&multipart.Form{- Value: values, File: map[string][]*multipart.FileHeader{"file": {{Filename: "backup.json"}}},- })- if err != nil || request.Password != "" {- t.Fatalf("backup password authentication must remain model validation: %v", err)- }- }-}-func TestReorderNotebookCompatibility(t *testing.T) {request, err := ReorderNotebooks.Decode(strings.NewReader(`{"SOURCEIDS":[null,"id"],"TARGETID":"target","POSITION":"before"}`))if err != nil || len(request.SourceIDs) != 2 || request.SourceIDs[0] != "" || request.TargetID != "target" || request.Position != "before" {@@ -87,10 +34,10 @@ func TestReorderNotebookCompatibility(t *testing.T) {func TestNotebookCryptoRequestCompatibility(t *testing.T) {request, err := UnlockNotebook.Decode(strings.NewReader(`{"notebook":" 20260101000000-abcdefg ","password":" secret "}`))- if err != nil || request.Notebook != "20260101000000-abcdefg" || request.Password != " secret " {- t.Fatalf("notebook normalization must preserve the original password: %v", err)+ if err != nil || request.Notebook != "20260101000000-abcdefg" || request.Password != "secret" {+ t.Fatalf("notebook and password trimming changed: %v", err)}- for _, body := range []string{`{}`, `{"password":null}`, `{"password":""}`, `{"password":123}`} {+ for _, body := range []string{`{}`, `{"password":null}`, `{"password":" "}`, `{"password":123}`} {if _, err := EnableEncryptedNotebooks.Decode(strings.NewReader(body)); err == nil {t.Fatal("invalid password accepted")}diff --git a/kernel/apicontract/schema.go b/kernel/apicontract/schema.goindex a425501941..e0bb95b820 100644--- a/kernel/apicontract/schema.go+++ b/kernel/apicontract/schema.go@@ -484,7 +484,7 @@ func (b *schemaBuilder) fields(object *Schema, t reflect.Type, input bool) errorif field.Type.Kind() != reflect.Pointer || field.Type.Elem().Kind() != reflect.Struct {return fmt.Errorf("legacyobject requires a struct pointer: %s.%s", t, name)}- case option == "trim", option == "nonempty", option == "ignoretype", strings.HasPrefix(option, "enum="):+ case option == "trim", option == "ignoretype", strings.HasPrefix(option, "enum="):if field.Type.Kind() != reflect.String {return fmt.Errorf("API option %s requires a string: %s.%s", option, t, name)}