diff --git a/plugins/web/abi_extra.go b/plugins/web/abi_extra.go index 7855e29..15b0c57 100644 --- a/plugins/web/abi_extra.go +++ b/plugins/web/abi_extra.go @@ -8,14 +8,50 @@ import "C" import ( "fmt" + "strconv" "github.com/marqdo/marqdo/plugins/web/internal/app" + "github.com/marqdo/marqdo/plugins/web/internal/auth" "github.com/marqdo/marqdo/plugins/web/internal/db" "github.com/marqdo/marqdo/plugins/web/internal/form" "github.com/marqdo/marqdo/plugins/web/internal/httpx" "github.com/marqdo/marqdo/plugins/web/internal/middleware" + "github.com/marqdo/marqdo/plugins/web/internal/password" + "github.com/marqdo/marqdo/plugins/web/internal/session" ) +func argUint64(args map[string]any, def uint64, keys ...string) uint64 { + for _, k := range keys { + v, ok := args[k] + if !ok || v == nil { + continue + } + switch t := v.(type) { + case float64: + if t > 0 { + return uint64(t) + } + case int: + if t > 0 { + return uint64(t) + } + case int64: + if t > 0 { + return uint64(t) + } + case uint64: + if t > 0 { + return t + } + case string: + if n, e := strconv.ParseUint(t, 10, 64); e == nil && n > 0 { + return n + } + } + } + return def +} + func txnOpt(args map[string]any) string { s, _ := argStr(args, "txn", "事务") return s @@ -260,3 +296,170 @@ func web_listen(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { out, err := httpx.Listen(appBag, entryDir()) return replyJSON(outJSON, errMsg, out, err) } + +//export web_password_hash +func web_password_hash(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + pw, err := argStrReq(args, "password", "密码") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + out, err := password.HashResult(pw) + return replyJSON(outJSON, errMsg, out, err) +} + +//export web_session_new +func web_session_new(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + ttl := argUint64(args, 3600, "ttl_sec", "ttl", "session_ttl") + return replyJSON(outJSON, errMsg, session.New(ttl), nil) +} + +//export web_session_set +func web_session_set(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + id, err := argStrReq(args, "id", "session_id") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + key, err := argStrReq(args, "key") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + return replyJSON(outJSON, errMsg, session.Set(id, key, args["value"]), nil) +} + +//export web_session_get +func web_session_get(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + id, err := argStrReq(args, "id", "session_id") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + key, err := argStrReq(args, "key") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + return replyJSON(outJSON, errMsg, session.Get(id, key), nil) +} + +//export web_session_del +func web_session_del(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + id, err := argStrReq(args, "id", "session_id") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + key, err := argStrReq(args, "key") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + return replyJSON(outJSON, errMsg, session.Del(id, key), nil) +} + +//export web_session_destroy +func web_session_destroy(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + id, err := argStrReq(args, "id", "session_id") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + return replyJSON(outJSON, errMsg, session.Destroy(id), nil) +} + +//export web_auth_login +func web_auth_login(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + username, err := argStrReq(args, "username", "用户名", "用户") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + pw, err := argStrReq(args, "password", "密码") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + ttl := argUint64(args, 3600, "session_ttl", "ttl_sec", "ttl") + out := auth.Login(username, pw, args["users"], ttl) + return replyJSON(outJSON, errMsg, out, nil) +} + +//export web_auth_check +func web_auth_check(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + id, err := argStrReq(args, "session_id", "id") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + return replyJSON(outJSON, errMsg, auth.Check(id), nil) +} + +//export web_auth_logout +func web_auth_logout(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + id, err := argStrReq(args, "session_id", "id") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + return replyJSON(outJSON, errMsg, auth.Logout(id), nil) +} + +//export web_auth_new +func web_auth_new(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + ttl := argUint64(args, 3600, "session_ttl", "ttl_sec", "ttl") + return replyJSON(outJSON, errMsg, auth.New(args["users"], ttl), nil) +} + +//export web_app_auth +func web_app_auth(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + out, err := app.Auth(asPageMap(args["app"]), args["users"], args) + return replyJSON(outJSON, errMsg, out, err) +} + +//export web_app_gate +func web_app_gate(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + path, err := argStrReq(args, "path", "路径") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + out, err := app.Gate(asPageMap(args["app"]), path, args) + return replyJSON(outJSON, errMsg, out, err) +} diff --git a/plugins/web/go.mod b/plugins/web/go.mod index 6e795e9..14f6b9e 100644 --- a/plugins/web/go.mod +++ b/plugins/web/go.mod @@ -2,7 +2,10 @@ module github.com/marqdo/marqdo/plugins/web go 1.25.0 -require modernc.org/sqlite v1.34.5 +require ( + golang.org/x/crypto v0.41.0 + modernc.org/sqlite v1.34.5 +) require ( github.com/dustin/go-humanize v1.0.1 // indirect diff --git a/plugins/web/go.sum b/plugins/web/go.sum index fc3fc1d..a794716 100644 --- a/plugins/web/go.sum +++ b/plugins/web/go.sum @@ -12,6 +12,8 @@ github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOF github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4= +golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc= golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk= golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40= golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= diff --git a/plugins/web/internal/app/app.go b/plugins/web/internal/app/app.go index b8757af..3f235a0 100644 --- a/plugins/web/internal/app/app.go +++ b/plugins/web/internal/app/app.go @@ -1,9 +1,11 @@ -// Package app ports minimal app bag helpers (new + route) for offline smoke. +// Package app ports minimal app bag helpers (new + route + auth + gate) for offline smoke. package app import ( "fmt" "strings" + + "github.com/marqdo/marqdo/plugins/web/internal/session" ) // New builds an app bag matching Rust web_app_new defaults used by zh-smoke. @@ -29,6 +31,9 @@ func New(args map[string]any) map[string]any { if s := strOpt(args, "后台前缀", ""); s != "" { adminPrefix = s } + if p, err := NormalizeAdminPrefix(adminPrefix); err == nil { + adminPrefix = p + } out := map[string]any{ "page": page, "db": dbv, @@ -70,8 +75,9 @@ func New(args map[string]any) map[string]any { } // Route registers path → page on app.routes and stamps page._route. +// When admin=true, paths under admin_prefix are reserved (c0 frees /admin when admin=false). func Route(appBag map[string]any, path string, page any) (map[string]any, error) { - path, err := normalizeRoutePath(path) + path, err := NormalizeRoutePath(path, appBag) if err != nil { return nil, err } @@ -140,9 +146,8 @@ func Static(appBag map[string]any, dir, mount string) (map[string]any, error) { return nil, fmt.Errorf("static mount `%s` is reserved", mount) } if boolish(appBag["admin"]) { - prefix := strOpt(appBag, "admin_prefix", "/admin") - prefix = NormalizeStaticMount(prefix) - if mount == prefix || strings.HasPrefix(mount, prefix+"/") { + prefix := AdminPrefix(appBag) + if pathUnderPrefix(mount, prefix) { return nil, fmt.Errorf("static mount `%s` is reserved", mount) } } @@ -152,20 +157,240 @@ func Static(appBag map[string]any, dir, mount string) (map[string]any, error) { return out, nil } -func normalizeRoutePath(raw string) (string, error) { +// Auth wires users + default admin gate (Rust web_app_auth). +// opts may include session_ttl, admin_prefix/后台前缀, login_redirect/登录回跳, +// logout_redirect/登出回跳, login_path/登录路径. +func Auth(appBag map[string]any, users any, opts map[string]any) (map[string]any, error) { + if opts == nil { + opts = map[string]any{} + } + out := clone(appBag) + sessionTTL := uint64(3600) + if v, ok := opts["session_ttl"]; ok { + if n, ok := asUint64(v); ok && n > 0 { + sessionTTL = n + } + } + if p := firstStr(opts, "admin_prefix", "后台前缀"); p != "" { + np, err := NormalizeAdminPrefix(p) + if err != nil { + return nil, err + } + out["admin_prefix"] = np + } + if v := firstStr(opts, "login_redirect", "登录回跳"); v != "" { + out["login_redirect"] = v + } + if v := firstStr(opts, "logout_redirect", "登出回跳"); v != "" { + out["logout_redirect"] = v + } + if v := firstStr(opts, "login_path", "登录路径"); v != "" { + out["login_path"] = v + } + prefix := AdminPrefix(out) + loginPath := strOpt(out, "login_path", "") + if loginPath == "" { + loginPath = prefix + "/login" + } + out["login_path"] = loginPath + out["auth"] = map[string]any{ + "users": users, + "session_ttl": float64(sessionTTL), + } + gates := gatesOf(out) + if !hasAdminGate(gates, prefix) { + gates = append(gates, map[string]any{ + "path": prefix, + "roles": []any{"admin"}, + "match": "prefix", + "on_deny": "redirect", + "exclude": []any{loginPath}, + }) + out["gates"] = gates + } else { + out["gates"] = gates + } + return out, nil +} + +// Gate appends an RBAC gate (Rust web_app_gate). +// opts: roles/角色, match/匹配, on_deny/拒绝, exclude/排除. +func Gate(appBag map[string]any, path string, opts map[string]any) (map[string]any, error) { + if opts == nil { + opts = map[string]any{} + } + path = strings.TrimSpace(path) + if path == "" { + return nil, fmt.Errorf("missing `path`") + } + rolesRaw := firstStr(opts, "roles", "角色") + if rolesRaw == "" { + rolesRaw = "admin" + } + roles := session.ParseRolesCSV(rolesRaw) + roleAny := make([]any, len(roles)) + for i, r := range roles { + roleAny[i] = r + } + matchMode := firstStr(opts, "match", "匹配") + if matchMode == "" { + matchMode = "prefix" + } + onDeny := firstStr(opts, "on_deny", "拒绝") + if onDeny == "" { + onDeny = "forbid" + } + entry := map[string]any{ + "path": path, + "roles": roleAny, + "match": matchMode, + "on_deny": onDeny, + } + if v, ok := first(opts, "exclude", "排除"); ok && v != nil { + entry["exclude"] = v + } + out := clone(appBag) + gates := gatesOf(out) + gates = append(gates, entry) + out["gates"] = gates + return out, nil +} + +// NormalizeAdminPrefix cleans and validates admin_prefix. +func NormalizeAdminPrefix(raw string) (string, error) { + path, err := cleanMountPath(raw) + if err != nil { + return "", err + } + if path == "/" { + return "", fmt.Errorf("admin_prefix cannot be `/`") + } + if path == "/_form" || strings.HasPrefix(path, "/_form/") || + path == "/_part" || strings.HasPrefix(path, "/_part/") { + return "", fmt.Errorf("admin_prefix `%s` collides with framework paths", path) + } + return path, nil +} + +// AdminPrefix returns the active admin mount from an app bag. +func AdminPrefix(appBag map[string]any) string { + s := strOpt(appBag, "admin_prefix", "/admin") + if p, err := NormalizeAdminPrefix(s); err == nil { + return p + } + return "/admin" +} + +// NormalizeRoutePath applies Rust reserved-path rules for the app bag. +func NormalizeRoutePath(raw string, appBag map[string]any) (string, error) { + path, err := cleanMountPath(raw) + if err != nil { + return "", err + } + if path == "/" { + return "", fmt.Errorf("route path `/` is reserved for the home page") + } + staticMount := NormalizeStaticMount(strOpt(appBag, "static_mount", "/static")) + if isFrameworkReserved(path, staticMount) { + return "", fmt.Errorf("route path `%s` is reserved", path) + } + if boolish(appBag["admin"]) && pathUnderPrefix(path, AdminPrefix(appBag)) { + return "", fmt.Errorf("route path `%s` is reserved", path) + } + return path, nil +} + +func cleanMountPath(raw string) (string, error) { s := strings.TrimSpace(raw) if s == "" { - return "", fmt.Errorf("empty route path") + return "", fmt.Errorf("path is empty") } if !strings.HasPrefix(s, "/") { s = "/" + s } - if s != "/" { - s = strings.TrimRight(s, "/") + for len(s) > 1 && strings.HasSuffix(s, "/") { + s = strings.TrimSuffix(s, "/") } return s, nil } +func pathUnderPrefix(path, prefix string) bool { + return path == prefix || strings.HasPrefix(path, prefix+"/") +} + +func isFrameworkReserved(path, staticMount string) bool { + return path == "/_form" || strings.HasPrefix(path, "/_form/") || + path == "/_part" || strings.HasPrefix(path, "/_part/") || + pathUnderPrefix(path, staticMount) +} + +func gatesOf(appBag map[string]any) []any { + if g, ok := appBag["gates"].([]any); ok { + out := make([]any, len(g)) + copy(out, g) + return out + } + return []any{} +} + +func hasAdminGate(gates []any, prefix string) bool { + want := strings.TrimSuffix(prefix, "/") + for _, g := range gates { + m, ok := g.(map[string]any) + if !ok { + continue + } + p, _ := m["path"].(string) + cleaned := strings.TrimSuffix(strings.TrimSuffix(p, "*"), "/") + if cleaned == want { + return true + } + } + return false +} + +func first(m map[string]any, keys ...string) (any, bool) { + for _, k := range keys { + if v, ok := m[k]; ok && v != nil { + return v, true + } + } + return nil, false +} + +func firstStr(m map[string]any, keys ...string) string { + v, ok := first(m, keys...) + if !ok { + return "" + } + s, _ := v.(string) + return strings.TrimSpace(s) +} + +func asUint64(v any) (uint64, bool) { + switch t := v.(type) { + case uint64: + return t, true + case int: + if t < 0 { + return 0, false + } + return uint64(t), true + case int64: + if t < 0 { + return 0, false + } + return uint64(t), true + case float64: + if t < 0 { + return 0, false + } + return uint64(t), true + default: + return 0, false + } +} + func clone(m map[string]any) map[string]any { out := make(map[string]any, len(m)) for k, v := range m { diff --git a/plugins/web/internal/app/app_test.go b/plugins/web/internal/app/app_test.go index 749f0be..638e420 100644 --- a/plugins/web/internal/app/app_test.go +++ b/plugins/web/internal/app/app_test.go @@ -60,3 +60,104 @@ func TestStaticRejectsReserved(t *testing.T) { t.Fatalf("admin mount: want reserved, got %v", err) } } + +func TestRouteFreesAdminWhenDisabled(t *testing.T) { + a := app.New(map[string]any{"admin": false}) + page := map[string]any{"title": "news"} + out, err := app.Route(a, "/admin/news", page) + if err != nil { + t.Fatal(err) + } + routes := out["routes"].(map[string]any) + if routes["/admin/news"] == nil { + t.Fatal("missing route") + } +} + +func TestRouteCustomPrefixFreesAdmin(t *testing.T) { + a := app.New(map[string]any{"admin": true, "admin_prefix": "/desk"}) + out, err := app.Route(a, "/admin/news", map[string]any{"title": "news"}) + if err != nil { + t.Fatal(err) + } + if out["routes"].(map[string]any)["/admin/news"] == nil { + t.Fatal("missing") + } + _, err = app.Route(a, "/desk/x", map[string]any{"title": "x"}) + if err == nil || !strings.Contains(err.Error(), "reserved") { + t.Fatalf("want reserved under /desk, got %v", err) + } +} + +func TestAuthDefaultGate(t *testing.T) { + a := app.New(map[string]any{"admin": true}) + users := map[string]any{ + "用户名": []any{"admin"}, + "密码": []any{"secret"}, + "角色": []any{"admin"}, + } + out, err := app.Auth(a, users, nil) + if err != nil { + t.Fatal(err) + } + if out["login_path"] != "/admin/login" { + t.Fatalf("login_path=%v", out["login_path"]) + } + gates := out["gates"].([]any) + g0 := gates[0].(map[string]any) + if g0["path"] != "/admin" || g0["match"] != "prefix" || g0["on_deny"] != "redirect" { + t.Fatalf("gate=%v", g0) + } + ex := g0["exclude"].([]any) + if len(ex) != 1 || ex[0] != "/admin/login" { + t.Fatalf("exclude=%v", ex) + } +} + +func TestAuthCustomPrefix(t *testing.T) { + a := app.New(map[string]any{"admin": true}) + out, err := app.Auth(a, []any{}, map[string]any{ + "admin_prefix": "/desk", + "login_redirect": "/desk", + "logout_redirect": "/desk/login", + }) + if err != nil { + t.Fatal(err) + } + if out["admin_prefix"] != "/desk" || out["login_redirect"] != "/desk" { + t.Fatalf("%v", out) + } + g0 := out["gates"].([]any)[0].(map[string]any) + if g0["path"] != "/desk" { + t.Fatalf("gate path=%v", g0["path"]) + } +} + +func TestGateCustomFields(t *testing.T) { + a := app.New(map[string]any{"admin": false}) + out, err := app.Gate(a, "/desk", map[string]any{ + "roles": "admin", + "match": "prefix", + "on_deny": "redirect", + "exclude": "/desk/login", + }) + if err != nil { + t.Fatal(err) + } + g0 := out["gates"].([]any)[0].(map[string]any) + if g0["path"] != "/desk" || g0["match"] != "prefix" || g0["on_deny"] != "redirect" { + t.Fatalf("%v", g0) + } + if g0["exclude"] != "/desk/login" { + t.Fatalf("exclude=%v", g0["exclude"]) + } + out2, err := app.Gate(a, "/write*", map[string]any{"roles": "admin,author"}) + if err != nil { + t.Fatal(err) + } + g1 := out2["gates"].([]any)[0].(map[string]any) + roles := g1["roles"].([]any) + if g1["path"] != "/write*" || len(roles) != 2 { + t.Fatalf("%v", g1) + } +} diff --git a/plugins/web/internal/auth/auth.go b/plugins/web/internal/auth/auth.go new file mode 100644 index 0000000..c6868de --- /dev/null +++ b/plugins/web/internal/auth/auth.go @@ -0,0 +1,129 @@ +// Package auth ports login/check/logout and credential checks from the Rust web plugin. +package auth + +import ( + "fmt" + "strconv" + "strings" + + "github.com/marqdo/marqdo/plugins/web/internal/password" + "github.com/marqdo/marqdo/plugins/web/internal/session" + "github.com/marqdo/marqdo/plugins/web/internal/table" +) + +var ( + userKeys = []string{"用户名", "用户", "username", "user", "账号"} + passKeys = []string{"密码", "password", "pass", "口令"} + roleKeys = []string{"角色", "role", "roles"} +) + +// New builds an auth bag: {"users":…,"session_ttl":N} (web_auth_new). +func New(users any, sessionTTL uint64) map[string]any { + if sessionTTL == 0 { + sessionTTL = 3600 + } + return map[string]any{ + "users": users, + "session_ttl": float64(sessionTTL), + } +} + +// CheckCredentials validates username/password against a users table (GFM or row list). +// Missing role defaults to "admin". Returns username, role, ok. +func CheckCredentials(users any, username, pass string) (string, string, bool) { + rowsAny := table.AsRows(users) + rows, ok := rowsAny.([]any) + if !ok { + return "", "", false + } + for _, row := range rows { + m, ok := row.(map[string]any) + if !ok { + continue + } + u := pickCell(m, userKeys) + p := pickCell(m, passKeys) + if u == username && password.Verify(pass, p) { + role := pickCell(m, roleKeys) + if role == "" { + role = "admin" + } + return u, strings.ToLower(role), true + } + } + return "", "", false +} + +func pickCell(m map[string]any, keys []string) string { + for _, k := range keys { + if v, ok := m[k]; ok { + return cellStr(v) + } + } + return "" +} + +func cellStr(v any) string { + switch t := v.(type) { + case nil: + return "" + case string: + return t + case bool: + return strconv.FormatBool(t) + case float64: + if t == float64(int64(t)) { + return strconv.FormatInt(int64(t), 10) + } + return strconv.FormatFloat(t, 'f', -1, 64) + case int: + return strconv.Itoa(t) + case int64: + return strconv.FormatInt(t, 10) + default: + return fmt.Sprint(t) + } +} + +// Login validates credentials and creates a session. +// Success: {"ok":true,"session_id":…,"username":…,"role":…} +// Failure: {"ok":false} +func Login(username, pass string, users any, sessionTTL uint64) map[string]any { + u, role, ok := CheckCredentials(users, username, pass) + if !ok { + return map[string]any{"ok": false} + } + id := session.NewID(sessionTTL) + session.SetValue(id, "username", u) + session.SetValue(id, "role", role) + return map[string]any{ + "ok": true, + "session_id": id, + "username": u, + "role": role, + } +} + +// Check returns session auth state (web_auth_check). +func Check(sessionID string) map[string]any { + v, ok := session.GetValue(sessionID, "username") + if !ok { + return map[string]any{"ok": false} + } + u, _ := v.(string) + if u == "" { + return map[string]any{"ok": false} + } + role := "admin" + if rv, rok := session.GetValue(sessionID, "role"); rok { + if s, ok := rv.(string); ok && s != "" { + role = s + } + } + return map[string]any{"ok": true, "username": u, "role": role} +} + +// Logout destroys the session (web_auth_logout). +func Logout(sessionID string) map[string]any { + return map[string]any{"ok": session.DestroyID(sessionID)} +} diff --git a/plugins/web/internal/auth/auth_test.go b/plugins/web/internal/auth/auth_test.go new file mode 100644 index 0000000..c06b83f --- /dev/null +++ b/plugins/web/internal/auth/auth_test.go @@ -0,0 +1,80 @@ +package auth_test + +import ( + "testing" + + "github.com/marqdo/marqdo/plugins/web/internal/auth" + "github.com/marqdo/marqdo/plugins/web/internal/password" + "github.com/marqdo/marqdo/plugins/web/internal/session" +) + +func usersEN() any { + return []any{ + map[string]any{"username": "admin", "password": "secret"}, + map[string]any{"用户": "站长", "密码": "pw123"}, + } +} + +func usersZHTable() any { + return map[string]any{ + "行": []any{"1"}, + "用户": []any{"admin"}, + "密码": []any{"secret"}, + } +} + +func TestLoginCheckLogout(t *testing.T) { + session.Configure(session.Config{TTLSec: 3600}) + session.Reset(3600) + r := auth.Login("admin", "secret", usersEN(), 0) + if r["ok"] != true { + t.Fatalf("login: %v", r) + } + sid, _ := r["session_id"].(string) + if sid == "" || r["username"] != "admin" || r["role"] != "admin" { + t.Fatalf("login fields: %v", r) + } + check := auth.Check(sid) + if check["ok"] != true || check["username"] != "admin" { + t.Fatalf("check: %v", check) + } + bad := auth.Login("admin", "wrong", usersEN(), 0) + if bad["ok"] != false { + t.Fatalf("bad login: %v", bad) + } + out := auth.Logout(sid) + if out["ok"] != true { + t.Fatalf("logout: %v", out) + } + if auth.Check(sid)["ok"] != false { + t.Fatal("after logout still ok") + } +} + +func TestGFMUsersTable(t *testing.T) { + session.Reset(3600) + r := auth.Login("admin", "secret", usersZHTable(), 120) + if r["ok"] != true { + t.Fatalf("gfm login: %v", r) + } +} + +func TestHashedPasswordLogin(t *testing.T) { + session.Reset(3600) + hash, err := password.Hash("secret") + if err != nil { + t.Fatal(err) + } + users := []any{map[string]any{"username": "admin", "password": hash}} + r := auth.Login("admin", "secret", users, 0) + if r["ok"] != true { + t.Fatalf("hashed login: %v", r) + } +} + +func TestAuthNew(t *testing.T) { + bag := auth.New(usersEN(), 120) + if bag["session_ttl"] != float64(120) { + t.Fatalf("%v", bag) + } +} diff --git a/plugins/web/internal/password/password.go b/plugins/web/internal/password/password.go new file mode 100644 index 0000000..50a55fd --- /dev/null +++ b/plugins/web/internal/password/password.go @@ -0,0 +1,123 @@ +// Package password ports argon2id hashing from the Rust web plugin. +package password + +import ( + "crypto/rand" + "crypto/subtle" + "encoding/base64" + "fmt" + "strconv" + "strings" + + "golang.org/x/crypto/argon2" +) + +// Defaults match Rust argon2::Argon2::default() (argon2id, m=19456, t=2, p=1). +const ( + timeCost = 2 + memoryKiB = 19456 + parallelism = 1 + keyLen = 32 + saltLen = 16 +) + +// IsHashed reports whether stored looks like an argon2 PHC string. +func IsHashed(stored string) bool { + return strings.HasPrefix(stored, "$argon2") +} + +// Hash returns an argon2id PHC string for plaintext password. +func Hash(password string) (string, error) { + if password == "" { + return "", fmt.Errorf("password must not be empty") + } + salt := make([]byte, saltLen) + if _, err := rand.Read(salt); err != nil { + return "", fmt.Errorf("getrandom: %w", err) + } + sum := argon2.IDKey([]byte(password), salt, timeCost, memoryKiB, uint8(parallelism), keyLen) + b64Salt := base64.RawStdEncoding.EncodeToString(salt) + b64Hash := base64.RawStdEncoding.EncodeToString(sum) + return fmt.Sprintf("$argon2id$v=19$m=%d,t=%d,p=%d$%s$%s", + memoryKiB, timeCost, parallelism, b64Salt, b64Hash), nil +} + +// HashResult is the ABI shape for web_password_hash: {"hash":"…"}. +func HashResult(password string) (map[string]any, error) { + h, err := Hash(password) + if err != nil { + return nil, err + } + return map[string]any{"hash": h}, nil +} + +// Verify checks plaintext against an argon2 PHC hash, or legacy plaintext equality +// (dev / gold tests). +func Verify(password, encoded string) bool { + if password == "" || encoded == "" { + return false + } + if IsHashed(encoded) { + return verifyArgon2(password, encoded) + } + return password == encoded +} + +func verifyArgon2(password, encoded string) bool { + // $argon2id$v=19$m=19456,t=2,p=1$salt$hash + parts := strings.Split(encoded, "$") + // "", "argon2id", "v=19", "m=…,t=…,p=…", salt, hash + if len(parts) != 6 { + return false + } + if parts[1] != "argon2id" && parts[1] != "argon2i" && parts[1] != "argon2d" { + return false + } + var m uint32 + var t, p uint32 + for _, kv := range strings.Split(parts[3], ",") { + k, v, ok := strings.Cut(kv, "=") + if !ok { + return false + } + n, err := strconv.ParseUint(v, 10, 32) + if err != nil { + return false + } + switch k { + case "m": + m = uint32(n) + case "t": + t = uint32(n) + case "p": + p = uint32(n) + } + } + if m == 0 || t == 0 || p == 0 { + return false + } + salt, err := base64.RawStdEncoding.DecodeString(parts[4]) + if err != nil { + salt, err = base64.StdEncoding.DecodeString(parts[4]) + if err != nil { + return false + } + } + want, err := base64.RawStdEncoding.DecodeString(parts[5]) + if err != nil { + want, err = base64.StdEncoding.DecodeString(parts[5]) + if err != nil { + return false + } + } + var got []byte + switch parts[1] { + case "argon2id": + got = argon2.IDKey([]byte(password), salt, t, m, uint8(p), uint32(len(want))) + case "argon2i": + got = argon2.Key([]byte(password), salt, t, m, uint8(p), uint32(len(want))) + default: + return false + } + return subtle.ConstantTimeCompare(got, want) == 1 +} diff --git a/plugins/web/internal/password/password_test.go b/plugins/web/internal/password/password_test.go new file mode 100644 index 0000000..9af3a28 --- /dev/null +++ b/plugins/web/internal/password/password_test.go @@ -0,0 +1,52 @@ +package password_test + +import ( + "strings" + "testing" + + "github.com/marqdo/marqdo/plugins/web/internal/password" +) + +func TestHashAndVerifyRoundtrip(t *testing.T) { + hash, err := password.Hash("secret") + if err != nil { + t.Fatal(err) + } + if !password.IsHashed(hash) { + t.Fatalf("not PHC: %q", hash) + } + if !strings.HasPrefix(hash, "$argon2id$") { + t.Fatalf("want argon2id prefix, got %q", hash) + } + if !password.Verify("secret", hash) { + t.Fatal("verify secret failed") + } + if password.Verify("wrong", hash) { + t.Fatal("wrong password should fail") + } + out, err := password.HashResult("secret") + if err != nil { + t.Fatal(err) + } + if out["hash"] == nil || out["hash"] == "" { + t.Fatalf("HashResult shape: %v", out) + } +} + +func TestLegacyPlaintext(t *testing.T) { + if !password.Verify("secret", "secret") { + t.Fatal("plaintext equality") + } + if password.Verify("other", "secret") { + t.Fatal("plaintext mismatch") + } + if password.Verify("", "secret") || password.Verify("secret", "") { + t.Fatal("empty should fail") + } +} + +func TestEmptyHashError(t *testing.T) { + if _, err := password.Hash(""); err == nil { + t.Fatal("expected error") + } +} diff --git a/plugins/web/internal/ratelimit/ratelimit.go b/plugins/web/internal/ratelimit/ratelimit.go new file mode 100644 index 0000000..42b8e93 --- /dev/null +++ b/plugins/web/internal/ratelimit/ratelimit.go @@ -0,0 +1,95 @@ +// Package ratelimit ports login attempt throttling from the Rust web plugin. +package ratelimit + +import ( + "fmt" + "sync" + "time" +) + +const ( + maxFails = 5 + windowSec = 900 // 15 minutes + lockMsg = "Too many failed login attempts. Try again in about 15 minutes." +) + +type window struct { + count uint32 + start int64 +} + +var ( + mu sync.Mutex + attempts map[string]*window +) + +func nowSecs() int64 { + return time.Now().Unix() +} + +func key(ip, username string) string { + return ip + "|" + username +} + +// Reset clears attempt counters (between listens / tests). +func Reset() { + mu.Lock() + defer mu.Unlock() + attempts = map[string]*window{} +} + +func ensureMap() { + if attempts == nil { + attempts = map[string]*window{} + } +} + +// Check returns an error when the client is temporarily locked out. +func Check(ip, username string) error { + k := key(ip, username) + now := nowSecs() + mu.Lock() + defer mu.Unlock() + ensureMap() + w, ok := attempts[k] + if !ok { + return nil + } + if now-w.start < windowSec && w.count >= maxFails { + return fmt.Errorf("%s", lockMsg) + } + if now-w.start >= windowSec { + delete(attempts, k) + } + return nil +} + +// RecordFailure increments the failure counter for IP+username. +func RecordFailure(ip, username string) { + k := key(ip, username) + now := nowSecs() + mu.Lock() + defer mu.Unlock() + ensureMap() + w, ok := attempts[k] + if !ok { + attempts[k] = &window{count: 1, start: now} + return + } + if now-w.start >= windowSec { + w.count = 0 + w.start = now + } + if w.count < ^uint32(0) { + w.count++ + } +} + +// ClearSuccess removes the counter after a successful login. +func ClearSuccess(ip, username string) { + k := key(ip, username) + mu.Lock() + defer mu.Unlock() + ensureMap() + delete(attempts, k) +} diff --git a/plugins/web/internal/ratelimit/ratelimit_test.go b/plugins/web/internal/ratelimit/ratelimit_test.go new file mode 100644 index 0000000..9faca65 --- /dev/null +++ b/plugins/web/internal/ratelimit/ratelimit_test.go @@ -0,0 +1,22 @@ +package ratelimit_test + +import ( + "testing" + + "github.com/marqdo/marqdo/plugins/web/internal/ratelimit" +) + +func TestLocksAfterMaxFails(t *testing.T) { + ratelimit.Reset() + ip, user := "127.0.0.1", "admin" + for i := 0; i < 5; i++ { + ratelimit.RecordFailure(ip, user) + } + if err := ratelimit.Check(ip, user); err == nil { + t.Fatal("expected lockout") + } + ratelimit.ClearSuccess(ip, user) + if err := ratelimit.Check(ip, user); err != nil { + t.Fatalf("cleared: %v", err) + } +} diff --git a/plugins/web/internal/session/session.go b/plugins/web/internal/session/session.go new file mode 100644 index 0000000..a4df5e2 --- /dev/null +++ b/plugins/web/internal/session/session.go @@ -0,0 +1,437 @@ +// Package session ports in-memory / SQLite session store from the Rust web plugin. +package session + +import ( + "crypto/rand" + "encoding/hex" + "encoding/json" + "fmt" + "strings" + "sync" + "time" + + "github.com/marqdo/marqdo/plugins/web/internal/db" +) + +const ( + sessionTable = "_marqdo_sessions" + csrfKey = "_csrf" + defaultTTL = 3600 +) + +// Config controls session backend. +type Config struct { + DBURL string + TTLSec uint64 + CookieSecure bool +} + +var ( + cfgMu sync.Mutex + cfg = Config{TTLSec: defaultTTL} + + memMu sync.Mutex + mem = map[string]memRec{} + memTTL uint64 = defaultTTL +) + +type memRec struct { + exp uint64 + data map[string]any +} + +func nowSecs() uint64 { + return uint64(time.Now().Unix()) +} + +func cloneData(m map[string]any) map[string]any { + out := make(map[string]any, len(m)) + for k, v := range m { + out[k] = v + } + return out +} + +// Configure sets session backend before listen or offline ABI calls. +func Configure(c Config) { + ttl := c.TTLSec + if ttl == 0 { + ttl = defaultTTL + } + c.TTLSec = ttl + if c.DBURL != "" { + _ = ensureSessionTable(c.DBURL) + } + cfgMu.Lock() + cfg = c + cfgMu.Unlock() +} + +func getCfg() Config { + cfgMu.Lock() + defer cfgMu.Unlock() + return cfg +} + +// Reset clears in-memory sessions (tests / each listen). +func Reset(ttlSec uint64) { + ttl := ttlSec + if ttl == 0 { + ttl = defaultTTL + } + cfgMu.Lock() + cfg.TTLSec = ttl + if cfg.DBURL == "" { + // keep cookie_secure / db as-is when already configured + } + cfgMu.Unlock() + memMu.Lock() + mem = map[string]memRec{} + memTTL = ttl + memMu.Unlock() +} + +func ensureSessionTable(url string) error { + _, err := db.Exec(url, fmt.Sprintf(` +CREATE TABLE IF NOT EXISTS "%s" ( + id TEXT PRIMARY KEY, + expires_at INTEGER NOT NULL, + data TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_marqdo_sessions_exp ON "%s"(expires_at);`, sessionTable, sessionTable), nil) + return err +} + +func pruneMem() { + now := nowSecs() + for id, rec := range mem { + if rec.exp <= now { + delete(mem, id) + } + } +} + +func pruneSQL(url string) { + now := int64(nowSecs()) + _, _ = db.Exec(url, fmt.Sprintf(`DELETE FROM "%s" WHERE expires_at <= ?`, sessionTable), []any{now}) +} + +func secureRandomID() (string, error) { + b := make([]byte, 32) + if _, err := rand.Read(b); err != nil { + return "", err + } + return hex.EncodeToString(b), nil +} + +func randomCSRF() (string, error) { + b := make([]byte, 24) + if _, err := rand.Read(b); err != nil { + return "", err + } + return hex.EncodeToString(b), nil +} + +func ensureCSRF(data map[string]any) (string, error) { + if v, ok := data[csrfKey].(string); ok && v != "" { + return v, nil + } + t, err := randomCSRF() + if err != nil { + return "", err + } + data[csrfKey] = t + return t, nil +} + +func loadSQL(url, id string) (uint64, map[string]any, bool) { + q, err := db.Query(url, fmt.Sprintf(`SELECT expires_at, data FROM "%s" WHERE id = ?`, sessionTable), []any{id}) + if err != nil { + return 0, nil, false + } + rows, _ := q["rows"].([]any) + if len(rows) == 0 { + return 0, nil, false + } + row, ok := rows[0].(map[string]any) + if !ok { + return 0, nil, false + } + exp := uint64(asInt64(row["expires_at"])) + dataS, _ := row["data"].(string) + data := map[string]any{} + _ = json.Unmarshal([]byte(dataS), &data) + if data == nil { + data = map[string]any{} + } + return exp, data, true +} + +func asInt64(v any) int64 { + switch t := v.(type) { + case int64: + return t + case float64: + return int64(t) + case int: + return int64(t) + default: + return 0 + } +} + +func saveSQL(url, id string, exp uint64, data map[string]any) error { + raw, err := json.Marshal(data) + if err != nil { + return err + } + _, err = db.Exec(url, fmt.Sprintf(` +INSERT INTO "%s" (id, expires_at, data) VALUES (?, ?, ?) +ON CONFLICT(id) DO UPDATE SET expires_at = excluded.expires_at, data = excluded.data`, sessionTable), + []any{id, int64(exp), string(raw)}) + return err +} + +func deleteSQL(url, id string) { + _, _ = db.Exec(url, fmt.Sprintf(`DELETE FROM "%s" WHERE id = ?`, sessionTable), []any{id}) +} + +func touchExpiry(ttl uint64) uint64 { + return nowSecs() + ttl +} + +func getRecord(id string) (map[string]any, bool) { + c := getCfg() + now := nowSecs() + if c.DBURL != "" { + pruneSQL(c.DBURL) + exp, data, ok := loadSQL(c.DBURL, id) + if !ok { + return nil, false + } + if exp <= now { + deleteSQL(c.DBURL, id) + return nil, false + } + return data, true + } + memMu.Lock() + defer memMu.Unlock() + pruneMem() + rec, ok := mem[id] + if !ok { + return nil, false + } + if rec.exp <= now { + delete(mem, id) + return nil, false + } + return cloneData(rec.data), true +} + +func putRecord(id string, exp uint64, data map[string]any) bool { + c := getCfg() + if c.DBURL != "" { + return saveSQL(c.DBURL, id, exp, data) == nil + } + memMu.Lock() + defer memMu.Unlock() + mem[id] = memRec{exp: exp, data: cloneData(data)} + return true +} + +// NewID creates a session and returns its id (optional ttl; 0 = configured default). +func NewID(ttlSec uint64) string { + c := getCfg() + ttl := ttlSec + if ttl == 0 { + ttl = c.TTLSec + } + if ttl == 0 { + ttl = defaultTTL + } + if ttlSec > 0 { + cfgMu.Lock() + cfg.TTLSec = ttl + cfgMu.Unlock() + } + id, err := secureRandomID() + if err != nil { + id = fmt.Sprintf("fallback-%d", nowSecs()) + } + data := map[string]any{} + _, _ = ensureCSRF(data) + exp := touchExpiry(ttl) + if c.DBURL != "" { + pruneSQL(c.DBURL) + _ = saveSQL(c.DBURL, id, exp, data) + } else { + memMu.Lock() + memTTL = ttl + pruneMem() + mem[id] = memRec{exp: exp, data: data} + memMu.Unlock() + } + return id +} + +// New is ABI shape web_session_new → {"id":"…"}. +func New(ttlSec uint64) map[string]any { + return map[string]any{"id": NewID(ttlSec)} +} + +// Set stores a key (sliding expiry). ABI: {"ok":bool}. +func Set(id, key string, value any) map[string]any { + return map[string]any{"ok": SetValue(id, key, value)} +} + +// SetValue is the low-level setter. +func SetValue(id, key string, value any) bool { + data, ok := getRecord(id) + if !ok { + return false + } + data[key] = value + return putRecord(id, touchExpiry(getCfg().TTLSec), data) +} + +// Get is ABI shape: {"ok":true,"value":…} or {"ok":false}. +func Get(id, key string) map[string]any { + v, ok := GetValue(id, key) + if !ok { + return map[string]any{"ok": false} + } + return map[string]any{"ok": true, "value": v} +} + +// GetValue returns the value and whether it existed (sliding expiry on hit). +func GetValue(id, key string) (any, bool) { + data, ok := getRecord(id) + if !ok { + return nil, false + } + v, exists := data[key] + if !exists { + return nil, false + } + putRecord(id, touchExpiry(getCfg().TTLSec), data) + return v, true +} + +// Del removes a key. ABI: {"ok":bool}. +func Del(id, key string) map[string]any { + return map[string]any{"ok": DelKey(id, key)} +} + +// DelKey is the low-level deleter. +func DelKey(id, key string) bool { + data, ok := getRecord(id) + if !ok { + return false + } + if _, exists := data[key]; !exists { + return false + } + delete(data, key) + return putRecord(id, touchExpiry(getCfg().TTLSec), data) +} + +// Destroy removes a session. ABI: {"ok":bool}. +func Destroy(id string) map[string]any { + return map[string]any{"ok": DestroyID(id)} +} + +// DestroyID is the low-level destroyer. +func DestroyID(id string) bool { + c := getCfg() + if c.DBURL != "" { + deleteSQL(c.DBURL, id) + return true + } + memMu.Lock() + defer memMu.Unlock() + _, ok := mem[id] + if ok { + delete(mem, id) + } + return ok +} + +// CSRFFor returns (creating if needed) the CSRF token for a session. +func CSRFFor(id string) (string, bool) { + data, ok := getRecord(id) + if !ok { + return "", false + } + tok, err := ensureCSRF(data) + if err != nil { + return "", false + } + putRecord(id, touchExpiry(getCfg().TTLSec), data) + return tok, true +} + +// ValidateCSRF checks token against session. +func ValidateCSRF(id, token string) bool { + if token == "" { + return false + } + v, ok := GetValue(id, csrfKey) + if !ok { + return false + } + s, _ := v.(string) + return s == token +} + +// SessionCookie builds Set-Cookie for marqdo_sid. +func SessionCookie(id string, ttlSec uint64, secure bool) string { + s := fmt.Sprintf("marqdo_sid=%s; HttpOnly; Path=/; SameSite=Lax; Max-Age=%d", id, ttlSec) + if secure { + s += "; Secure" + } + return s +} + +// IDFromCookie parses marqdo_sid from a Cookie header. +func IDFromCookie(cookieHeader string) (string, bool) { + if cookieHeader == "" { + return "", false + } + for _, part := range strings.Split(cookieHeader, ";") { + p := strings.TrimSpace(part) + if v, ok := strings.CutPrefix(p, "marqdo_sid="); ok { + v = strings.Trim(v, `"`) + if v != "" { + return v, true + } + } + } + return "", false +} + +// ParseRolesCSV splits "admin,author" into lowercased roles. +func ParseRolesCSV(raw string) []string { + var out []string + for _, part := range strings.Split(raw, ",") { + part = strings.TrimSpace(part) + if part != "" { + out = append(out, strings.ToLower(part)) + } + } + return out +} + +// RoleAllowed reports whether role is in allowed (empty allowed = all). +func RoleAllowed(role string, allowed []string) bool { + if len(allowed) == 0 { + return true + } + role = strings.ToLower(role) + for _, a := range allowed { + if strings.EqualFold(a, role) { + return true + } + } + return false +} diff --git a/plugins/web/internal/session/session_test.go b/plugins/web/internal/session/session_test.go new file mode 100644 index 0000000..0054b67 --- /dev/null +++ b/plugins/web/internal/session/session_test.go @@ -0,0 +1,86 @@ +package session_test + +import ( + "os" + "path/filepath" + "testing" + + "github.com/marqdo/marqdo/plugins/web/internal/db" + "github.com/marqdo/marqdo/plugins/web/internal/session" +) + +func TestSessionSetGetDel(t *testing.T) { + session.Configure(session.Config{TTLSec: 3600}) + session.Reset(3600) + id := session.NewID(0) + if id == "" { + t.Fatal("empty id") + } + if !session.SetValue(id, "username", "admin") { + t.Fatal("set") + } + v, ok := session.GetValue(id, "username") + if !ok || v != "admin" { + t.Fatalf("get=%v ok=%v", v, ok) + } + got := session.Get(id, "username") + if got["ok"] != true || got["value"] != "admin" { + t.Fatalf("Get ABI: %v", got) + } + if !session.DelKey(id, "username") { + t.Fatal("del") + } + if _, ok := session.GetValue(id, "username"); ok { + t.Fatal("del leftover") + } + if !session.DestroyID(id) { + t.Fatal("destroy") + } +} + +func TestCSRFAndCookie(t *testing.T) { + session.Reset(3600) + id := session.NewID(0) + tok, ok := session.CSRFFor(id) + if !ok || tok == "" { + t.Fatal("csrf") + } + if !session.ValidateCSRF(id, tok) { + t.Fatal("validate") + } + if session.ValidateCSRF(id, "bad") { + t.Fatal("bad csrf") + } + cookie := session.SessionCookie(id, 3600, false) + got, ok := session.IDFromCookie("theme=light; " + cookie) + if !ok || got != id { + t.Fatalf("cookie parse %q != %q", got, id) + } +} + +func TestSessionPersistsInSQLite(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "persist.db") + url := "sqlite:" + path + db.ResetPool() + session.Configure(session.Config{DBURL: url, TTLSec: 3600}) + id := session.NewID(0) + if !session.SetValue(id, "theme", "dark") { + t.Fatal("set") + } + session.Configure(session.Config{DBURL: url, TTLSec: 3600}) + v, ok := session.GetValue(id, "theme") + if !ok || v != "dark" { + t.Fatalf("persist get=%v ok=%v", v, ok) + } + _ = os.RemoveAll(dir) +} + +func TestNewABI(t *testing.T) { + session.Reset(120) + out := session.New(120) + id, _ := out["id"].(string) + if id == "" { + t.Fatal(out) + } +} diff --git a/plugins/web/plugin.go b/plugins/web/plugin.go index 2295f8d..2a144cb 100644 --- a/plugins/web/plugin.go +++ b/plugins/web/plugin.go @@ -85,6 +85,18 @@ extern int web_app_mount_form(char *args_json, char **out_json, char **err_msg); extern int web_app_static(char *args_json, char **out_json, char **err_msg); extern int web_app_middleware(char *args_json, char **out_json, char **err_msg); extern int web_listen(char *args_json, char **out_json, char **err_msg); +extern int web_password_hash(char *args_json, char **out_json, char **err_msg); +extern int web_session_new(char *args_json, char **out_json, char **err_msg); +extern int web_session_set(char *args_json, char **out_json, char **err_msg); +extern int web_session_get(char *args_json, char **out_json, char **err_msg); +extern int web_session_del(char *args_json, char **out_json, char **err_msg); +extern int web_session_destroy(char *args_json, char **out_json, char **err_msg); +extern int web_auth_login(char *args_json, char **out_json, char **err_msg); +extern int web_auth_check(char *args_json, char **out_json, char **err_msg); +extern int web_auth_logout(char *args_json, char **out_json, char **err_msg); +extern int web_auth_new(char *args_json, char **out_json, char **err_msg); +extern int web_app_auth(char *args_json, char **out_json, char **err_msg); +extern int web_app_gate(char *args_json, char **out_json, char **err_msg); static int register_core(void) { if (host_register((char *)"web_go_ready", (char *)"", web_go_ready) != 0) return 1; @@ -123,6 +135,18 @@ static int register_core(void) { if (host_register((char *)"web_app_static", (char *)"app,dir,mount", web_app_static) != 0) return 1; if (host_register((char *)"web_app_middleware", (char *)"app,cors,security,compress,body_limit,json_routes,access_log,cache_control,proxy,invoke", web_app_middleware) != 0) return 1; if (host_register((char *)"web_listen", (char *)"app", web_listen) != 0) return 1; + if (host_register((char *)"web_password_hash", (char *)"password", web_password_hash) != 0) return 1; + if (host_register((char *)"web_session_new", (char *)"ttl_sec", web_session_new) != 0) return 1; + if (host_register((char *)"web_session_set", (char *)"id,key,value", web_session_set) != 0) return 1; + if (host_register((char *)"web_session_get", (char *)"id,key", web_session_get) != 0) return 1; + if (host_register((char *)"web_session_del", (char *)"id,key", web_session_del) != 0) return 1; + if (host_register((char *)"web_session_destroy", (char *)"id", web_session_destroy) != 0) return 1; + if (host_register((char *)"web_auth_login", (char *)"username,password,users,session_ttl", web_auth_login) != 0) return 1; + if (host_register((char *)"web_auth_check", (char *)"session_id", web_auth_check) != 0) return 1; + if (host_register((char *)"web_auth_logout", (char *)"session_id", web_auth_logout) != 0) return 1; + if (host_register((char *)"web_auth_new", (char *)"users,session_ttl", web_auth_new) != 0) return 1; + if (host_register((char *)"web_app_auth", (char *)"app,users,session_ttl,admin_prefix,login_redirect,logout_redirect,login_path", web_app_auth) != 0) return 1; + if (host_register((char *)"web_app_gate", (char *)"app,path,roles,match,on_deny,exclude", web_app_gate) != 0) return 1; return 0; } */