From 5e85b13f12e281a319ff4fc832a2962ab4f8d7b2 Mon Sep 17 00:00:00 2001 From: 2018wzh Date: Sat, 3 Oct 2026 01:47:06 +0800 Subject: [PATCH 01/28] feat: make deployment compatibility explicit and expose reusable authentication --- README.md | 23 ++- auth/auth.go | 43 ++++++ client/README.md | 14 +- client/client.go | 43 ++++-- client/client_test.go | 2 +- client/compatibility_test.go | 85 ++++++++++- cmd/geektrust/init_cmd.go | 4 +- .../init_permissions_windows_test.go | 2 +- cmd/geektrust/library.go | 19 ++- cmd/geektrust/main.go | 14 +- cmd/geektrust/main_test.go | 2 +- config.example.toml | 40 +++++- deployment/profile.go | 74 ++++++++++ docs/TECHNICAL.md | 4 +- go.mod | 2 +- internal/config/compatibility_test.go | 92 ++++++++---- internal/config/config.go | 78 ++++------ internal/config/config_test.go | 2 +- internal/config/init.go | 11 +- internal/idsauth/keystore.go | 2 +- internal/inbound/http.go | 2 +- internal/inbound/inbound_test.go | 4 +- internal/inbound/server.go | 4 +- internal/inbound/socks5.go | 2 +- internal/l3/auth.go | 13 +- internal/l3/auth_test.go | 28 +++- internal/l3/dialer.go | 8 +- internal/l3/gvisor.go | 2 +- internal/l3/icmp.go | 4 +- internal/l3/session_regression_test.go | 8 +- internal/resolver/adaptive_test.go | 4 +- internal/resolver/resolver.go | 2 +- internal/resolver/resolver_test.go | 4 +- internal/sdpc/authconfig.go | 4 +- internal/sdpc/authconfig_test.go | 7 +- internal/sdpc/login.go | 16 ++- internal/sdpc/login_test.go | 34 +++++ internal/session/authentication_test.go | 50 +++++++ internal/session/events.go | 2 +- internal/session/events_test.go | 4 +- internal/session/live_test.go | 2 +- internal/session/provider.go | 135 +++++++++++------- internal/session/provider_test.go | 4 +- internal/session/routing.go | 20 +-- internal/session/routing_test.go | 16 ++- internal/session/store.go | 2 +- internal/tunnel/reconnect.go | 4 +- internal/tunnel/reconnect_regression_test.go | 2 +- internal/tunnel/reconnect_test.go | 4 +- internal/tunnel/tcp.go | 43 ++++-- internal/tunnel/tcp_test.go | 42 +++++- internal/tunnel/tunnel.go | 2 +- internal/webui/broker.go | 2 +- internal/webui/broker_test.go | 2 +- internal/webui/hub.go | 4 +- internal/webui/hub_test.go | 4 +- internal/webui/server.go | 6 +- internal/webui/server_test.go | 4 +- 58 files changed, 789 insertions(+), 267 deletions(-) create mode 100644 auth/auth.go create mode 100644 deployment/profile.go create mode 100644 internal/sdpc/login_test.go create mode 100644 internal/session/authentication_test.go diff --git a/README.md b/README.md index 713d1f0..97102e8 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ geekTrust 是 aTrust VPN 的纯用户态客户端。它不创建虚拟网卡、 - 使用 IDS passkey 免密码登录。 - client 模式在首次短信验证后会尝试绑定授信终端。绑定成功后,会话失效时可静默重登,通常不再要求短信。 -- TCP 优先使用网关原生流式通道;不可用或不兼容时自动回退到 L3 隧道。 +- TCP 优先使用网关原生流式通道;显式开启兼容选项后,流式命令不支持或提前关闭时可回退到 L3 隧道。 - UDP 和 TCP 回退流量由 gVisor 用户态 IPv4 栈处理。 - 会话自动恢复;有多条网关线路时错峰竞速,直接使用最先完成 TLS 握手的连接。 @@ -128,6 +128,27 @@ listen = "127.0.0.1:8081" SOCKS5 和 HTTP 代理没有身份认证,只应监听 `127.0.0.1`。如果改成 `0.0.0.0`,同一网络中的其他设备也能使用你的 VPN 会话。 +### 部署兼容选项 + +所有控制器默认采用严格模式,不再根据学校域名启用兼容行为。 +在配置文件中添加 `[compatibility]`,只开启目标部署需要的选项: + +```toml +[compatibility] +fallback_app_id = "" +fallback_gateways = [] +gateway_server_name = "" +missing_gateway_group_fallback = false +tcp_to_l3_fallback = false +``` + +应用 ID 和网关地址仅用于缺失数据时的兜底;已有资源规则和非空网关组优先。 +TCP→L3 回退不覆盖认证拒绝、连接不允许、不可达或取消。 +TLS 域名覆盖仍验证证书;选项拼写错误会拒绝加载配置。 +修改后重新启动客户端;关闭选项后,缓存会话不会恢复旧的兜底网关。 +旧的顶层 `app_id` 已移除,请明确填写 `compatibility.fallback_app_id`。 +上海科大的可选值和进程元数据覆盖示例见 [config.example.toml](config.example.toml)。 + ### browser 兼容模式 只有在控制器不支持 client 模式时,才把 `client_type` 设为 `browser`。browser 模式不能绑定授信终端,会话彻底失效后可能再次要求短信。 diff --git a/auth/auth.go b/auth/auth.go new file mode 100644 index 0000000..3338492 --- /dev/null +++ b/auth/auth.go @@ -0,0 +1,43 @@ +// Package auth defines the authentication boundary shared by embedders and the +// controller. It contains no terminal, storage, or school-specific behavior. +package auth + +import ( + "context" + "errors" + "net/http" + "time" +) + +var ErrUnsupported = errors.New("unsupported authentication method") +var ErrRequired = errors.New("authentication input required") + +type UnsupportedError struct{ Method string } + +func (e *UnsupportedError) Error() string { return ErrUnsupported.Error() } +func (e *UnsupportedError) Unwrap() error { return ErrUnsupported } + +type Challenge struct { + Method string + ExpiresAt time.Time +} + +type RequiredError struct{ Challenge Challenge } + +func (e *RequiredError) Error() string { return ErrRequired.Error() } +func (e *RequiredError) Unwrap() error { return ErrRequired } + +// Handler waits for user input using ctx. The caller owns how the prompt is +// displayed; the SDK never includes the submitted answer in an event or log. +type Handler func(context.Context, Challenge) (string, error) + +type ControllerRequest struct { + URL, DeviceID, Platform, ClientType, LoginDomain string + // CSRFToken comes from the initial controller authConfig response. + CSRFToken string +} + +// ControllerLogin replaces the built-in identity-to-CAS authentication chain. +// On success it leaves the authenticated controller cookies in http.Client.Jar. +// The SDK checks onlineInfo and fetches policy before accepting the session. +type ControllerLogin func(context.Context, *http.Client, ControllerRequest) error diff --git a/client/README.md b/client/README.md index c0189c4..8351e23 100644 --- a/client/README.md +++ b/client/README.md @@ -1,10 +1,10 @@ # client -`client` 封装认证、会话、资源解析和 TCP/UDP 连接,供项目内复用。 +`client` 封装认证、会话、资源解析和 TCP/UDP 连接,供其他 Go 项目直接引用。 它不启动代理监听器,也不创建 TUN 或修改系统路由、DNS。 ```go -import "geektrust/client" +import "github.com/ShanghaitechGeekPie/geektrust/client" c, err := client.New(client.Options{ ControllerURL: controllerURL, @@ -25,7 +25,13 @@ defer conn.Close() - `ClientMode` 默认为 false,即 browser 模式;设为 true 后,首次短信验证成功时会尝试绑定授信终端。 - `BlobStore` 收到的是凭据或会话的明文字节,调用方负责保密、原子写入和持久化。同一 passkey 使用同一认证器串行更新计数器;保存失败不会提交断言。 - 认证遵循调用方的 context,允许等待短信输入;网络连接和解析设有超时。连接建立后,用 `SetDeadline` 控制读写。`Close` 会取消操作并关闭自有连接。 -- TCP 优先遵循服务端 L3 偏好,否则先尝试流式 TCP;协议不兼容或连接建立失败时可退回 L3,明确的目标拒绝和取消不会触发回退。 -- 上海科大保留旧配置的 `app_id` 兜底和网关/DNS 覆盖;其他控制器默认要求资源策略明确授权。 +- TCP 优先遵循服务端 L3 偏好,否则先尝试流式 TCP;仅显式设置 `Compatibility.TCPToL3Fallback` 后,网关明确不支持流式命令或在建立阶段提前关闭时才可退回 L3,明确的目标拒绝和取消不会触发回退。 +- 所有控制器均默认严格模式,不按域名推断兼容行为。`Options.Compatibility` 使用公开的 `deployment.Compatibility`,与 TOML `[compatibility]` 字段一一对应;可分别配置应用 ID、缺失网关地址、TLS 域名、缺失网关组和 TCP→L3 回退。网关列表只筛选已分配线路,不覆盖非空的网关组。删除或关闭选项后,新客户端立即采用严格行为,缓存会话不会恢复旧的兜底地址。 +- `LoginDomain` 显式选择 CAS 域;默认从控制器发现。`ControllerLogin` 可替换整个控制器登录流程,通过共享 HTTP CookieJar 建立会话,SDK 随后检查在线状态和资源。`ChallengeHandler` 接收带到期时间的短信验证请求;未提供交互处理器返回 `auth.ErrRequired`,未知认证方式返回 `auth.ErrUnsupported`。 - 默认 TLS 验证 CA。`GatewayTrustStore` 是显式启用的私有证书 TOFU 兜底,正常 CA 验证通过时不强制检查已有 pin;调用方负责持久保存 pin。 - UDP 保留数据报边界,payload 上限为 1372 字节。`ExchangePacket` 仅支持未分片 IPv4 ICMP Echo;实际可用性取决于控制器授权和网关支持。IPv6 目标未实现。 + +`Info.Implemented` 仅表示库已经实现的协议能力;`Resources` 表示控制器下发的授权范围, +`OpenTransport` 返回已建立线路和实际分配的 IPv4 地址。它们均不保证任意目标可达。 +`Compatibility.ProcessIdentity` 可以覆盖流式 TCP 和 L3 的进程名、平台和路径,并统一重新计算指纹。 +未配置时保留各自已实现的协议元数据;这些值与宿主操作系统无关,不代表平台连接验证结果。 diff --git a/client/client.go b/client/client.go index 0436daf..29fc1f0 100644 --- a/client/client.go +++ b/client/client.go @@ -16,13 +16,16 @@ import ( "strings" "sync" "time" + "unicode" - "geektrust/internal/config" - "geektrust/internal/idsauth" - "geektrust/internal/l3" - "geektrust/internal/resolver" - "geektrust/internal/session" - "geektrust/internal/tunnel" + "github.com/ShanghaitechGeekPie/geektrust/auth" + "github.com/ShanghaitechGeekPie/geektrust/deployment" + "github.com/ShanghaitechGeekPie/geektrust/internal/config" + "github.com/ShanghaitechGeekPie/geektrust/internal/idsauth" + "github.com/ShanghaitechGeekPie/geektrust/internal/l3" + "github.com/ShanghaitechGeekPie/geektrust/internal/resolver" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" + "github.com/ShanghaitechGeekPie/geektrust/internal/tunnel" ) // BlobStore is scoped to a single identity/deployment by the embedding application. @@ -105,7 +108,7 @@ func ValidatePasskey(b []byte) error { } type Options struct { - AppID string + Compatibility deployment.Compatibility Gateways []string DNS []string ControllerURL string @@ -114,6 +117,8 @@ type Options struct { LoginDomain string ClientMode bool Authenticator Authenticator + ControllerLogin auth.ControllerLogin + ChallengeHandler auth.Handler SessionStore BlobStore Transport http.RoundTripper DialContext func(context.Context, string, string) (net.Conn, error) @@ -121,7 +126,6 @@ type Options struct { GatewayTLSConfig *tls.Config GatewayTrustStore GatewayTrustStore Logger *slog.Logger - PromptSMS func(context.Context) (string, error) } type Capabilities struct{ IPv4TCP, IPv4UDP, IPv4ICMP, IPv6Targets, IPv6Gateway bool } @@ -132,7 +136,8 @@ type Resource struct { type Info struct { Gateways, DNS []string Resources []Resource - Capabilities Capabilities + // Implemented describes library support, not negotiated or authorized access. + Implemented Capabilities } type TransportInfo struct { Gateway string @@ -178,12 +183,15 @@ func New(opts Options) (*Client, error) { if len(opts.DeviceID) != 32 || strings.Trim(opts.DeviceID, "0123456789ABCDEF") != "" { return nil, errors.New("persistent 32-character uppercase hexadecimal device ID required") } - if opts.Authenticator == nil { + if opts.Authenticator == nil && opts.ControllerLogin == nil { return nil, errors.New("authenticator required") } if opts.Platform == "" { opts.Platform = "Mac" } + if len(opts.Platform) > 64 || strings.IndexFunc(opts.Platform, unicode.IsControl) >= 0 { + return nil, errors.New("platform must be at most 64 bytes without control characters") + } if opts.Logger == nil { opts.Logger = slog.New(slog.NewTextHandler(io.Discard, nil)) } @@ -191,9 +199,16 @@ func New(opts Options) (*Client, error) { if opts.ClientMode { mode = "client" } - cfg := &config.Config{BaseURL: strings.TrimRight(opts.ControllerURL, "/"), DeviceID: opts.DeviceID, Platform: opts.Platform, LoginDomain: opts.LoginDomain, ClientType: mode, AppID: opts.AppID, Gateways: append([]string(nil), opts.Gateways...), DNS: append([]string(nil), opts.DNS...)} - p := session.NewProvider(cfg, opts.Logger, opts.PromptSMS) - p.Authenticate = opts.Authenticator.Authenticate + cfg := &config.Config{BaseURL: strings.TrimRight(opts.ControllerURL, "/"), DeviceID: opts.DeviceID, Platform: opts.Platform, LoginDomain: opts.LoginDomain, ClientType: mode, Compatibility: opts.Compatibility.Clone(), Gateways: append([]string(nil), opts.Gateways...), DNS: append([]string(nil), opts.DNS...)} + if err := cfg.Compatibility.Validate(); err != nil { + return nil, err + } + p := session.NewProvider(cfg, opts.Logger, nil) + if opts.Authenticator != nil { + p.Authenticate = opts.Authenticator.Authenticate + } + p.ControllerLogin = opts.ControllerLogin + p.ChallengeHandler = opts.ChallengeHandler p.Transport = opts.Transport var ownedTransport *http.Transport if p.Transport == nil { @@ -267,7 +282,7 @@ func (c *Client) Connect(parent context.Context) (Info, error) { if c.closed { return Info{}, ErrClosed } - info := Info{Gateways: append([]string(nil), cred.Gateways...), DNS: append([]string(nil), cred.DNS...), Capabilities: Capabilities{IPv4TCP: true, IPv4UDP: true, IPv6Gateway: true}} + info := Info{Gateways: append([]string(nil), cred.Gateways...), DNS: append([]string(nil), cred.DNS...), Implemented: Capabilities{IPv4TCP: true, IPv4UDP: true, IPv4ICMP: true, IPv6Gateway: true}} for _, r := range cred.Policy.IPRules { address := "" switch { diff --git a/client/client_test.go b/client/client_test.go index 4e2658e..b937a73 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -14,7 +14,7 @@ import ( "golang.org/x/net/dns/dnsmessage" - "geektrust/internal/idsauth" + "github.com/ShanghaitechGeekPie/geektrust/internal/idsauth" ) type testGatewayPins struct { diff --git a/client/compatibility_test.go b/client/compatibility_test.go index a2ac040..5382622 100644 --- a/client/compatibility_test.go +++ b/client/compatibility_test.go @@ -4,13 +4,16 @@ import ( "context" "crypto/tls" "errors" + "github.com/ShanghaitechGeekPie/geektrust/auth" "io" "net/http" + "net/url" "strings" "testing" "time" - "geektrust/internal/config" + "github.com/ShanghaitechGeekPie/geektrust/deployment" + "github.com/ShanghaitechGeekPie/geektrust/internal/config" ) type compatibilityStore string @@ -32,9 +35,11 @@ func (compatibilityTransport) RoundTrip(r *http.Request) (*http.Response, error) return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}, nil } -func TestShanghaiTechOptionsPreserveLegacyConfig(t *testing.T) { +func TestExplicitCompatibilityOptions(t *testing.T) { template := &tls.Config{} options := Options{ + Compatibility: deployment.Compatibility{FallbackAppID: "custom-app", GatewayServerName: "gateway.example"}, + LoginDomain: "custom-domain", ControllerURL: config.DefaultBaseURL, DeviceID: "0123456789ABCDEF0123456789ABCDEF", Gateways: []string{"override:441"}, DNS: []string{"10.0.0.53"}, @@ -56,13 +61,13 @@ func TestShanghaiTechOptionsPreserveLegacyConfig(t *testing.T) { t.Fatal("configured routing overrides lost") } target, err := c.resolver.Resolve(context.Background(), "192.0.2.1", 443) - if err != nil || target.AppID != config.DefaultAppID { + if err != nil || target.AppID != "custom-app" { t.Fatal("legacy application fallback lost") } - if c.provider.ActiveSDPC().LoginDomain != config.DefaultLoginDomain { + if c.provider.ActiveSDPC().LoginDomain != "custom-domain" { t.Fatal("legacy CAS domain lost") } - if c.manager.GatewayTLSConfig.ServerName != "vpn.shanghaitech.edu.cn" || template.ServerName != "" { + if c.manager.GatewayTLSConfig.ServerName != "gateway.example" || template.ServerName != "" { t.Fatal("gateway certificate identity missing or caller TLS config mutated") } } @@ -88,3 +93,73 @@ func TestAuthenticationUsesCallerDeadline(t *testing.T) { t.Fatal("authentication fixture not exercised") } } + +type controllerTransport func(*http.Request) (*http.Response, error) + +func (f controllerTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +func TestCustomControllerLogin(t *testing.T) { + calls := 0 + transport := controllerTransport(func(r *http.Request) (*http.Response, error) { + if r.URL.Path == "/passport/v1/public/authConfig" { + return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"code":0,"data":{"security":{"csrfToken":"synthetic"},"authServerInfoList":[{"authType":"auth/cas","loginDomain":"a"},{"authType":"auth/cas","loginDomain":"b"}]}}`))}, nil + } + return (compatibilityTransport{}).RoundTrip(r) + }) + c, err := New(Options{ + ControllerURL: "https://controller.example", DeviceID: "0123456789ABCDEF0123456789ABCDEF", + Transport: transport, Compatibility: deployment.Compatibility{FallbackGateways: []string{"gateway.example:441"}}, + ControllerLogin: func(ctx context.Context, httpClient *http.Client, request auth.ControllerRequest) error { + calls++ + if request.URL != "https://controller.example" || request.LoginDomain != "" || request.CSRFToken != "synthetic" { + t.Fatal("custom authentication received implicit CAS configuration") + } + origin, _ := url.Parse(request.URL) + httpClient.Jar.SetCookies(origin, []*http.Cookie{{Name: "sid", Value: "synthetic"}}) + return nil + }, + }) + if err != nil { + t.Fatal(err) + } + defer c.Close() + info, err := c.Connect(context.Background()) + if err != nil || calls != 1 { + t.Fatalf("custom login calls=%d err=%v", calls, err) + } + if !info.Implemented.IPv4ICMP || info.Implemented.IPv6Targets || len(info.Resources) != 0 { + t.Fatal("implementation and authorization were conflated") + } +} + +func TestRestoredSessionUsesCurrentCompatibility(t *testing.T) { + state := compatibilityStore(`{"sid":"synthetic","device_id":"0123456789ABCDEF0123456789ABCDEF","client_type":"browser","cookies":[{"name":"sid","value":"synthetic"}],"gateways":["stale.example:441"]}`) + for _, enabled := range []bool{true, false} { + options := Options{ControllerURL: config.DefaultBaseURL, DeviceID: "0123456789ABCDEF0123456789ABCDEF", Transport: compatibilityTransport{}, SessionStore: state, + Authenticator: AuthenticatorFunc(func(context.Context, *http.Client) (string, error) { return "", errors.New("synthetic no fresh login") }), + } + if enabled { + options.Compatibility = deployment.Compatibility{FallbackAppID: "app", FallbackGateways: []string{"configured.example:441"}, TCPToL3Fallback: true} + } + c, err := New(options) + if err != nil { + t.Fatal(err) + } + if enabled { + options.Compatibility.FallbackGateways[0] = "mutated.example:441" + } + info, err := c.Connect(context.Background()) + if enabled { + if err != nil || len(info.Gateways) != 1 || info.Gateways[0] != "configured.example:441" { + t.Fatalf("configured fallback lost: %v", err) + } + cred, err := c.provider.Credential(context.Background()) + if err != nil || !cred.AllowTCPFallback || cred.MissingGatewayGroupFallback { + t.Fatal("independent compatibility switches not preserved") + } + } else if err == nil { + t.Fatal("cached gateways re-enabled a removed compatibility setting") + } + c.Close() + } +} diff --git a/cmd/geektrust/init_cmd.go b/cmd/geektrust/init_cmd.go index 7628a2c..95a9628 100644 --- a/cmd/geektrust/init_cmd.go +++ b/cmd/geektrust/init_cmd.go @@ -12,8 +12,8 @@ import ( "golang.org/x/text/unicode/norm" - "geektrust/internal/config" - "geektrust/internal/privatefile" + "github.com/ShanghaitechGeekPie/geektrust/internal/config" + "github.com/ShanghaitechGeekPie/geektrust/internal/privatefile" ) const passkeyToolSource = "git+https://github.com/vvbbnn00/shanghaitech-ids-passkey.git" diff --git a/cmd/geektrust/init_permissions_windows_test.go b/cmd/geektrust/init_permissions_windows_test.go index ab76b77..727b938 100644 --- a/cmd/geektrust/init_permissions_windows_test.go +++ b/cmd/geektrust/init_permissions_windows_test.go @@ -11,7 +11,7 @@ import ( "golang.org/x/sys/windows" - "geektrust/internal/config" + "github.com/ShanghaitechGeekPie/geektrust/internal/config" ) // Only call this on fixtures created by the test, never user directories. diff --git a/cmd/geektrust/library.go b/cmd/geektrust/library.go index 11cb5ec..d047090 100644 --- a/cmd/geektrust/library.go +++ b/cmd/geektrust/library.go @@ -7,19 +7,26 @@ import ( "log/slog" "net/http" - "geektrust/client" - "geektrust/internal/config" - "geektrust/internal/idsauth" - "geektrust/internal/session" + "github.com/ShanghaitechGeekPie/geektrust/auth" + "github.com/ShanghaitechGeekPie/geektrust/client" + "github.com/ShanghaitechGeekPie/geektrust/internal/config" + "github.com/ShanghaitechGeekPie/geektrust/internal/idsauth" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" ) // Command wiring owns paths and terminal interaction; the library sees neither. func commandClient(cfg *config.Config, logger *slog.Logger) (*client.Client, error) { return client.New(client.Options{ + Compatibility: cfg.Compatibility, ControllerURL: cfg.BaseURL, DeviceID: cfg.DeviceID, Platform: cfg.Platform, LoginDomain: cfg.LoginDomain, ClientMode: cfg.ClientType == "client", - AppID: cfg.AppID, Gateways: cfg.Gateways, DNS: cfg.DNS, - Logger: logger, PromptSMS: smsPrompt, + Gateways: cfg.Gateways, DNS: cfg.DNS, + Logger: logger, ChallengeHandler: func(ctx context.Context, challenge auth.Challenge) (string, error) { + if challenge.Method != "auth/sms" { + return "", &auth.UnsupportedError{Method: challenge.Method} + } + return smsPrompt(ctx) + }, SessionStore: commandSessionStore{session.NewStore(cfg.StateFile)}, Authenticator: client.AuthenticatorFunc(func(ctx context.Context, h *http.Client) (string, error) { k, err := idsauth.LoadKeystore(cfg.Keystore) diff --git a/cmd/geektrust/main.go b/cmd/geektrust/main.go index fb39259..8d9b2ed 100644 --- a/cmd/geektrust/main.go +++ b/cmd/geektrust/main.go @@ -20,13 +20,13 @@ import ( "syscall" "time" - "geektrust/internal/config" - "geektrust/internal/inbound" - "geektrust/internal/l3" - "geektrust/internal/resolver" - "geektrust/internal/session" - "geektrust/internal/tunnel" - "geektrust/internal/webui" + "github.com/ShanghaitechGeekPie/geektrust/internal/config" + "github.com/ShanghaitechGeekPie/geektrust/internal/inbound" + "github.com/ShanghaitechGeekPie/geektrust/internal/l3" + "github.com/ShanghaitechGeekPie/geektrust/internal/resolver" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" + "github.com/ShanghaitechGeekPie/geektrust/internal/tunnel" + "github.com/ShanghaitechGeekPie/geektrust/internal/webui" ) // version is replaced by scripts/package-release.sh through the Go linker. diff --git a/cmd/geektrust/main_test.go b/cmd/geektrust/main_test.go index 3923cd8..5bf8696 100644 --- a/cmd/geektrust/main_test.go +++ b/cmd/geektrust/main_test.go @@ -9,7 +9,7 @@ import ( "strings" "testing" - "geektrust/internal/config" + "github.com/ShanghaitechGeekPie/geektrust/internal/config" ) func TestBuildVersion(t *testing.T) { diff --git a/config.example.toml b/config.example.toml index 3755374..893dac9 100644 --- a/config.example.toml +++ b/config.example.toml @@ -10,17 +10,18 @@ device_id = "REPLACE_WITH_32_UPPERCASE_HEX" # ---- 控制器 ---- base_url = "https://vpn.shanghaitech.edu.cn" -platform = "Mac" # 区分大小写,必须为 Mac +platform = "Mac" # 控制器协议参数,大小写敏感,与运行操作系统无关 # client 模式会在首次短信验证后尝试绑定授信终端,绑定成功后通常不再要求短信。 # 省略时默认为 browser。 client_type = "client" -# 可选:没有路由规则匹配时使用的兜底 appId。上海科技大学控制器会自动使用下面的值。 -# app_id = "681165d0-1c77-11ed-8650-cd35a51aa42a" +# 留空时从控制器发现 CAS 登录域,多登录域时必须明确选择。 +login_domain = "" # ---- 网关线路 ---- -# 留空时使用服务端下发的线路;填写后改用这里的地址(host:port,端口默认 441)。 +# 留空 = 从上游 clientResource 自动获取(nodeGroup 地址); +# 填写则筛选服务端分配的网关(格式 host:port,默认端口 441),不会跨组覆盖。 gateways = [] # gateways = ["119.78.254.241:441", "59.78.171.241:441"] @@ -36,9 +37,38 @@ dns = [] state_file = "./state.enc" # ---- 日志 ---- -# debug / info / warn / error log_level = "info" +# ---- 部署兼容选项 ---- +# 默认严格模式;不根据控制器域名自动启用。修改后重新启动客户端。 +[compatibility] +# 仅在资源规则没有匹配时提交此 appId;仍由服务端验证授权。 +fallback_app_id = "" +# 仅在当前控制器未下发任何网关时使用;必须写完整 host:port。 +fallback_gateways = [] +# IP 网关使用的 TLS 证书域名;不会关闭证书验证。 +gateway_server_name = "" +# 指定网关组缺少地址时,允许使用已下发的完整网关列表。 +missing_gateway_group_fallback = false +# TCP 流协议不兼容时尝试 L3;明确拒绝、不可达、取消不触发回退。 +tcp_to_l3_fallback = false + +# 上海科大旧部署需要兼容时,可逐项将上述值替换为: +# fallback_app_id = "681165d0-1c77-11ed-8650-cd35a51aa42a" +# fallback_gateways = ["119.78.254.241:441", "59.78.171.241:441"] +# gateway_server_name = "vpn.shanghaitech.edu.cn" +# missing_gateway_group_fallback = true +# tcp_to_l3_fallback = true +# 如需指定 CAS 登录域,在文件顶部设置 login_domain = "Shanghaitech.edu.cn"。 + +# 可选:覆盖发送给网关的进程元数据。字段必须全部填写。 +# 未配置时沿用已实现的协议值:流式 TCP 为 Linux Chrome/SSH,L3 为 macOS aTrust。 +# 这些字段不代表本机进程检测结果,也不改变授权。 +# [compatibility.process_identity] +# name = "my-client" +# platform = "Windows" +# path = "my-client.exe" + # ---- 代理入口 ---- # 两个代理都没有认证,只应监听回环地址(127.0.0.1)。监听其他地址会让 # 同一网络中的其他设备使用你的 VPN 会话。 diff --git a/deployment/profile.go b/deployment/profile.go new file mode 100644 index 0000000..0b5aed5 --- /dev/null +++ b/deployment/profile.go @@ -0,0 +1,74 @@ +// Package deployment defines explicit protocol compatibility settings shared by +// configuration files and embedded clients. No behavior is selected by hostname. +package deployment + +import ( + "fmt" + "net" + "strconv" + "strings" + "unicode" +) + +// Compatibility is opt-in. Its zero value uses controller policy without +// deployment-specific fallbacks. These settings never override a server denial. +type Compatibility struct { + ProcessIdentity *ProcessIdentity `toml:"process_identity" json:"process_identity,omitempty"` + FallbackAppID string `toml:"fallback_app_id" json:"fallback_app_id,omitempty"` + FallbackGateways []string `toml:"fallback_gateways" json:"fallback_gateways,omitempty"` + GatewayServerName string `toml:"gateway_server_name" json:"gateway_server_name,omitempty"` + MissingGatewayGroupFallback bool `toml:"missing_gateway_group_fallback" json:"missing_gateway_group_fallback,omitempty"` + TCPToL3Fallback bool `toml:"tcp_to_l3_fallback" json:"tcp_to_l3_fallback,omitempty"` +} + +// Clone separates an active client's settings from caller-owned configuration. +func (c Compatibility) Clone() Compatibility { + if c.ProcessIdentity != nil { + identity := *c.ProcessIdentity + c.ProcessIdentity = &identity + } + c.FallbackGateways = append([]string(nil), c.FallbackGateways...) + return c +} + +func (c Compatibility) Validate() error { + if c.ProcessIdentity != nil { + if err := c.ProcessIdentity.Validate(); err != nil { + return err + } + } + if len(c.FallbackAppID) > 256 || strings.IndexFunc(c.FallbackAppID, unicode.IsControl) >= 0 { + return fmt.Errorf("compatibility.fallback_app_id must be at most 256 characters without control characters") + } + if c.GatewayServerName != "" { + name := c.GatewayServerName + if len(name) > 253 || strings.ContainsAny(name, "/\\:@?# \t\r\n") || strings.IndexFunc(name, unicode.IsControl) >= 0 { + return fmt.Errorf("compatibility.gateway_server_name must be a TLS hostname without a port") + } + } + for _, address := range c.FallbackGateways { + host, port, err := net.SplitHostPort(address) + number, portErr := strconv.Atoi(port) + if err != nil || host == "" || portErr != nil || number < 1 || number > 65535 || strings.ContainsAny(host, "/\\@?# \t\r\n") { + return fmt.Errorf("compatibility.fallback_gateways entries must be host:port with port 1-65535") + } + } + return nil +} + +// ProcessIdentity overrides the process metadata sent to the gateway. It is +// protocol metadata, not a claim about a locally running or verified process. +type ProcessIdentity struct { + Name string `toml:"name" json:"name"` + Platform string `toml:"platform" json:"platform"` + Path string `toml:"path" json:"path"` +} + +func (p ProcessIdentity) Validate() error { + for _, value := range []string{p.Name, p.Platform, p.Path} { + if strings.TrimSpace(value) == "" || len(value) > 4096 || strings.IndexFunc(value, unicode.IsControl) >= 0 { + return fmt.Errorf("compatibility.process_identity requires name, platform and path without control characters (max 4096 bytes each)") + } + } + return nil +} diff --git a/docs/TECHNICAL.md b/docs/TECHNICAL.md index b955292..33081d0 100644 --- a/docs/TECHNICAL.md +++ b/docs/TECHNICAL.md @@ -451,7 +451,7 @@ TCP 不需要经过 §6 至 §8 的 L3 小包数据面。客户端对目标应 ``` 认证与目标地址必须合并写入,也不能在连接结果前额外发送空数据帧;否则部分网关 -会接受初始化后关闭第一段应用数据。流式通道不可用或直连命令不兼容时, +会接受初始化后关闭第一段应用数据。显式启用 `compatibility.tcp_to_l3_fallback` 且流式命令不支持或建立阶段提前关闭时, 回退到下述 L3 路径。 --- @@ -634,7 +634,7 @@ geekTrust 提供 SOCKS5 CONNECT/UDP ASSOCIATE 和 HTTP/1.1 CONNECT/CONNECT-UDP 1. 客户端发 `0x05 `;服务器回 `0x05 0x00`(无认证)。 2. 客户端发 `0x05 0x01 0x00 `。 3. 按 §4.2 选择目标 IP、TCP `appId` 和可选域名;优先建立 §5.5 流式通道, - 流式通道不可用或网关不兼容时回退到 §6 至 §8 L3 路径;无法解析时回 + 显式开启 `compatibility.tcp_to_l3_fallback` 后,流式命令不支持或建立阶段提前关闭时回退到 §6 至 §8 L3 路径;无法解析时回 `REP=0x04`,拨号失败回 `REP=0x05`。 4. 成功后回 `REP=0x00`,再进行支持半关闭的双向 TCP 中继。 diff --git a/go.mod b/go.mod index 9964ca4..01a34e9 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module geektrust +module github.com/ShanghaitechGeekPie/geektrust go 1.24.13 diff --git a/internal/config/compatibility_test.go b/internal/config/compatibility_test.go index e3edf76..32d81f4 100644 --- a/internal/config/compatibility_test.go +++ b/internal/config/compatibility_test.go @@ -3,43 +3,83 @@ package config import ( "os" "path/filepath" + "strings" "testing" ) -func TestLegacyShanghaiTechConfig(t *testing.T) { - for _, body := range []string{ - "keystore = 'synthetic.keystore'\n", - "keystore = 'synthetic.keystore'\ndevice_id = '0123456789ABCDEF0123456789ABCDEF'\nclient_type = 'client'\ngateways = ['gateway.example']\ndns = ['10.0.0.53']\n", +func TestCompatibilityConfigIsExplicit(t *testing.T) { + for _, controller := range []string{DefaultBaseURL, "https://vpn.ecnu.edu.cn", "https://vpn.example.org"} { + t.Run(controller, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.toml") + base := "keystore = 'synthetic.keystore'\nbase_url = '" + controller + "'\n" + for _, enabled := range []bool{false, true, false} { + body := base + if enabled { + body += `login_domain = "custom-domain" +[compatibility] +fallback_app_id = "custom-app" +fallback_gateways = ["gateway.example:441", "[2001:db8::1]:441"] +gateway_server_name = "gateway.example" +missing_gateway_group_fallback = true +tcp_to_l3_fallback = true +` + } + if err := os.WriteFile(path, []byte(body), 0600); err != nil { + t.Fatal(err) + } + c, err := Load(path) + if err != nil { + t.Fatal(err) + } + if c.Compatibility.TCPToL3Fallback != enabled || c.Compatibility.MissingGatewayGroupFallback != enabled || (c.Compatibility.FallbackAppID != "") != enabled || (len(c.Compatibility.FallbackGateways) > 0) != enabled || (c.GatewayServerName() != "") != enabled || (c.LoginDomain != "") != enabled { + t.Fatalf("unexpected settings for enabled=%v: %+v", enabled, c.Compatibility) + } + after, err := os.ReadFile(path) + if err != nil || string(after) != body { + t.Fatal("loading changed original configuration") + } + } + }) + } +} + +func TestCompatibilityConfigRejectsMistakes(t *testing.T) { + for _, setting := range []string{ + "[compatibility]\ntcp_to_l3_fallbak = true", + "[compatibility]\nfallback_gateways = ['gateway:0']", + "[compatibility]\nfallback_gateways = ['gateway']", + "[compatibility]\ngateway_server_name = 'https://gateway'", + "app_id = 'removed-setting'", } { path := filepath.Join(t.TempDir(), "config.toml") - if err := os.WriteFile(path, []byte(body), 0600); err != nil { + if err := os.WriteFile(path, []byte("keystore = 'synthetic.keystore'\n"+setting), 0600); err != nil { t.Fatal(err) } - c, err := Load(path) - if err != nil { - t.Fatal(err) - } - if c.AppID != DefaultAppID || c.LoginDomain != DefaultLoginDomain || c.GatewayServerName() != "vpn.shanghaitech.edu.cn" { - t.Fatalf("legacy defaults lost: app=%s login=%s", c.AppID, c.LoginDomain) - } - after, err := os.ReadFile(path) - if err != nil || string(after) != body { - t.Fatal("loading changed the original configuration") + if _, err := Load(path); err == nil { + t.Fatalf("accepted invalid setting: %s", setting) } } } -func TestControllerDefaultsAreScoped(t *testing.T) { - c := &Config{BaseURL: DefaultBaseURL, AppID: "custom-app", LoginDomain: "custom-domain"} - c.ApplyControllerDefaults() - if c.AppID != "custom-app" || c.LoginDomain != "custom-domain" { - t.Fatal("explicit settings were overwritten") +func TestGeneratedConfigDefaultsToStrictCompatibility(t *testing.T) { + cfg, err := PrepareInitialConfig(InitOptions{}) + if err != nil { + t.Fatal(err) } - for _, base := range []string{"https://vpn.ecnu.edu.cn", "https://vpn.shanghaitech.edu.cn.invalid"} { - c = &Config{BaseURL: base} - c.ApplyControllerDefaults() - if c.AppID != "" || c.LoginDomain != "" || c.GatewayServerName() != "" { - t.Fatal("ShanghaiTech defaults leaked to another controller") - } + data := renderInitialConfig(cfg) + if !strings.Contains(string(data), "[compatibility]") { + t.Fatal("missing discoverable settings") + } + path := filepath.Join(t.TempDir(), "config.toml") + if err := os.WriteFile(path, data, 0600); err != nil { + t.Fatal(err) + } + loaded, err := Load(path) + if err != nil { + t.Fatal(err) + } + + if loaded.Compatibility.TCPToL3Fallback || loaded.Compatibility.MissingGatewayGroupFallback || loaded.Compatibility.FallbackAppID != "" || loaded.GatewayServerName() != "" { + t.Fatal("generated config enabled compatibility") } } diff --git a/internal/config/config.go b/internal/config/config.go index a781651..3779d72 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -4,12 +4,14 @@ package config import ( "fmt" "net" - "net/url" "os" "strconv" "strings" + "unicode" "github.com/BurntSushi/toml" + + "github.com/ShanghaitechGeekPie/geektrust/deployment" ) // DefaultDeviceID is the legacy shared browser-mode identifier. It remains @@ -20,29 +22,24 @@ const DefaultDeviceID = "84B5B45FE73EC0036C3E97717308447F" // DefaultBaseURL is the ShanghaiTech aTrust controller. const DefaultBaseURL = "https://vpn.shanghaitech.edu.cn" -// DefaultAppID preserves the legacy ShanghaiTech fallback for incomplete policies. -const DefaultAppID = "681165d0-1c77-11ed-8650-cd35a51aa42a" - -const DefaultLoginDomain = "Shanghaitech.edu.cn" - // DefaultWebListen is the default loopback address of the status panel. const DefaultWebListen = "127.0.0.1:8081" // Config is the top-level configuration. type Config struct { - Keystore string `toml:"keystore"` - DeviceID string `toml:"device_id"` - BaseURL string `toml:"base_url"` - Platform string `toml:"platform"` - ClientType string `toml:"client_type"` - AppID string `toml:"app_id"` - LoginDomain string `toml:"login_domain"` - Gateways []string `toml:"gateways"` - DNS []string `toml:"dns"` - StateFile string `toml:"state_file"` - LogLevel string `toml:"log_level"` - Inbound Inbound `toml:"inbound"` - Web WebConfig `toml:"web"` + Compatibility deployment.Compatibility `toml:"compatibility"` + Keystore string `toml:"keystore"` + DeviceID string `toml:"device_id"` + BaseURL string `toml:"base_url"` + Platform string `toml:"platform"` + ClientType string `toml:"client_type"` + LoginDomain string `toml:"login_domain"` + Gateways []string `toml:"gateways"` + DNS []string `toml:"dns"` + StateFile string `toml:"state_file"` + LogLevel string `toml:"log_level"` + Inbound Inbound `toml:"inbound"` + Web WebConfig `toml:"web"` } // Inbound holds the proxy listener configuration. @@ -78,9 +75,13 @@ func Load(path string) (*Config, error) { return nil, fmt.Errorf("read config: %w", err) } var cfg Config - if err := toml.Unmarshal(data, &cfg); err != nil { + meta, err := toml.Decode(string(data), &cfg) + if err != nil { return nil, fmt.Errorf("parse config %s: %w", path, err) } + if keys := meta.Undecoded(); len(keys) != 0 { + return nil, fmt.Errorf("unknown configuration field %s", keys[0]) + } cfg.applyDefaults() if err := cfg.validate(); err != nil { return nil, fmt.Errorf("config %s: %w", path, err) @@ -109,13 +110,15 @@ func (c *Config) applyDefaults() { c.ClientType = "browser" } c.BaseURL = strings.TrimRight(c.BaseURL, "/") - c.ApplyControllerDefaults() if c.Web.Listen == "" { c.Web.Listen = DefaultWebListen } } func (c *Config) validate() error { + if err := c.Compatibility.Validate(); err != nil { + return err + } if c.Keystore == "" { return fmt.Errorf("keystore path is required") } @@ -125,9 +128,9 @@ func (c *Config) validate() error { if !strings.HasPrefix(c.BaseURL, "https://") && !strings.HasPrefix(c.BaseURL, "http://") { return fmt.Errorf("base_url must be an http(s) URL, got %q", c.BaseURL) } - // platform is case sensitive server-side; catch the common mistakes early. - if c.Platform != "Mac" { - return fmt.Errorf("platform must be exactly \"Mac\" (case sensitive), got %q", c.Platform) + // Platform is a server-defined, case-sensitive protocol value, not GOOS. + if len(c.Platform) > 64 || strings.IndexFunc(c.Platform, unicode.IsControl) >= 0 { + return fmt.Errorf("platform must be at most 64 bytes without control characters") } for i, gw := range c.Gateways { host, port, err := SplitHostPort(gw) @@ -236,30 +239,7 @@ func SplitHostPort(addr string) (host string, port string, err error) { return host, port, nil } -// IsShanghaiTech limits legacy fallbacks to the original supported controller. -func (c *Config) IsShanghaiTech() bool { - u, err := url.Parse(c.BaseURL) - return err == nil && strings.EqualFold(u.Hostname(), "vpn.shanghaitech.edu.cn") -} - -// ApplyControllerDefaults also applies when the configuration is built by the client package. -func (c *Config) ApplyControllerDefaults() { - if !c.IsShanghaiTech() { - return - } - if c.AppID == "" { - c.AppID = DefaultAppID - } - if c.LoginDomain == "" { - c.LoginDomain = DefaultLoginDomain - } -} - -// GatewayServerName preserves the certificate identity used by ShanghaiTech's -// IP-addressed gateways without disabling certificate verification. +// GatewayServerName returns an explicit TLS certificate identity override. func (c *Config) GatewayServerName() string { - if c.IsShanghaiTech() { - return "vpn.shanghaitech.edu.cn" - } - return "" + return c.Compatibility.GatewayServerName } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index c5750b1..822b0df 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -74,7 +74,7 @@ func TestLoadValidation(t *testing.T) { cases := map[string]string{ "missing keystore": `device_id = "84B5B45FE73EC0036C3E97717308447F"`, "bad device_id": "keystore = \"k\"\ndevice_id = \"lowercasehex\"", - "bad platform": "keystore = \"k\"\nplatform = \"mac\"", + "bad platform": "keystore = \"k\"\nplatform = \"bad\\nvalue\"", "bad dns": "keystore = \"k\"\ndns = [\"dns.example.com\"]", "bad log level": "keystore = \"k\"\nlog_level = \"verbose\"", "bad client type": "keystore = \"k\"\nclient_type = \"desktop\"", diff --git a/internal/config/init.go b/internal/config/init.go index 1907127..da13bbc 100644 --- a/internal/config/init.go +++ b/internal/config/init.go @@ -11,7 +11,7 @@ import ( "strconv" "strings" - "geektrust/internal/privatefile" + "github.com/ShanghaitechGeekPie/geektrust/internal/privatefile" ) // InitOptions controls the initial config written by Initialize. @@ -110,6 +110,15 @@ state_file = %s gateways = [] dns = [] log_level = %s +login_domain = "" + +# Deployment-specific behavior is opt-in. See config.example.toml. +[compatibility] +fallback_app_id = "" +fallback_gateways = [] +gateway_server_name = "" +missing_gateway_group_fallback = false +tcp_to_l3_fallback = false [inbound.socks5] enabled = true diff --git a/internal/idsauth/keystore.go b/internal/idsauth/keystore.go index 148852b..86f9558 100644 --- a/internal/idsauth/keystore.go +++ b/internal/idsauth/keystore.go @@ -12,7 +12,7 @@ import ( "os" "path/filepath" - "geektrust/internal/privatefile" + "github.com/ShanghaitechGeekPie/geektrust/internal/privatefile" ) // keystoreMagic prefixes every default-format keystore file diff --git a/internal/inbound/http.go b/internal/inbound/http.go index deee18f..1429334 100644 --- a/internal/inbound/http.go +++ b/internal/inbound/http.go @@ -16,7 +16,7 @@ import ( "sync" "time" - "geektrust/internal/resolver" + "github.com/ShanghaitechGeekPie/geektrust/internal/resolver" ) const connectUDPPathPrefix = "/.well-known/masque/udp/" diff --git a/internal/inbound/inbound_test.go b/internal/inbound/inbound_test.go index 57b70ed..59b106b 100644 --- a/internal/inbound/inbound_test.go +++ b/internal/inbound/inbound_test.go @@ -14,8 +14,8 @@ import ( "testing" "time" - "geektrust/internal/config" - "geektrust/internal/resolver" + "github.com/ShanghaitechGeekPie/geektrust/internal/config" + "github.com/ShanghaitechGeekPie/geektrust/internal/resolver" ) // mockDialer echoes everything it receives, proving end-to-end relay. diff --git a/internal/inbound/server.go b/internal/inbound/server.go index 9f4f928..a515b2f 100644 --- a/internal/inbound/server.go +++ b/internal/inbound/server.go @@ -12,8 +12,8 @@ import ( "sync" "time" - "geektrust/internal/config" - "geektrust/internal/resolver" + "github.com/ShanghaitechGeekPie/geektrust/internal/config" + "github.com/ShanghaitechGeekPie/geektrust/internal/resolver" ) const ( diff --git a/internal/inbound/socks5.go b/internal/inbound/socks5.go index 54505f8..d2c1f34 100644 --- a/internal/inbound/socks5.go +++ b/internal/inbound/socks5.go @@ -10,7 +10,7 @@ import ( "strconv" "time" - "geektrust/internal/resolver" + "github.com/ShanghaitechGeekPie/geektrust/internal/resolver" ) // SOCKS5 constants (RFC 1928). diff --git a/internal/l3/auth.go b/internal/l3/auth.go index 4284bb2..d0908b2 100644 --- a/internal/l3/auth.go +++ b/internal/l3/auth.go @@ -7,6 +7,8 @@ import ( "fmt" "net" "time" + + "github.com/ShanghaitechGeekPie/geektrust/deployment" ) const ( @@ -70,7 +72,7 @@ var procFingerprint = fmt.Sprintf("%X", sha256.Sum256([]byte(procPath))) // buildAuthRequestIP serializes a per-flow auth body. domain is the original // hostname for wildcard-authorized targets (empty otherwise). -func buildAuthRequestIP(sid, appID, deviceID, dstIP string, dstPort int, vip net.IP, srcPort uint16, conntrackHash uint64, domain string, protocol int) ([]byte, error) { +func buildAuthRequestIP(sid, appID, deviceID, dstIP string, dstPort int, vip net.IP, srcPort uint16, conntrackHash uint64, domain string, protocol int, identity *deployment.ProcessIdentity) ([]byte, error) { network, err := protocolName(protocol) if err != nil { return nil, err @@ -86,6 +88,13 @@ func buildAuthRequestIP(sid, appID, deviceID, dstIP string, dstPort int, vip net p.Fingerprint = procFingerprint p.Description = "TrustAppClosed" p.Path = procPath + if identity != nil { + if err := identity.Validate(); err != nil { + return nil, err + } + p.Name, p.Platform, p.Path = identity.Name, identity.Platform, identity.Path + p.Fingerprint = fmt.Sprintf("%X", sha256.Sum256([]byte(p.Path))) + } p.Version = "TrustAppClosed" p.SecurityEnv = "normal" env.Application.Runtime.ProcessTrusted = "TRUSTED" @@ -108,7 +117,7 @@ func buildAuthRequestIP(sid, appID, deviceID, dstIP string, dstPort int, vip net SrcPort: int(srcPort), }, Domain: domain, - ProcHash: procFingerprint, + ProcHash: p.Fingerprint, XRequestSig: "", } return json.Marshal(req) diff --git a/internal/l3/auth_test.go b/internal/l3/auth_test.go index eae090c..2752792 100644 --- a/internal/l3/auth_test.go +++ b/internal/l3/auth_test.go @@ -2,15 +2,18 @@ package l3 import ( "crypto/md5" + "crypto/sha256" "encoding/json" "fmt" "net" "strings" "testing" + + "github.com/ShanghaitechGeekPie/geektrust/deployment" ) func TestBuildAuthRequestIPShape(t *testing.T) { - body, err := buildAuthRequestIP("sid", "681165d0-1c77-11ed-8650-cd35a51aa42a", "84B5B45FE73EC0036C3E97717308447F", "10.15.45.163", 443, net.IPv4(10, 19, 240, 43).To4(), 30001, 1, "", protocolTCP) + body, err := buildAuthRequestIP("sid", "681165d0-1c77-11ed-8650-cd35a51aa42a", "84B5B45FE73EC0036C3E97717308447F", "10.15.45.163", 443, net.IPv4(10, 19, 240, 43).To4(), 30001, 1, "", protocolTCP, nil) if err != nil { t.Fatal(err) } @@ -87,7 +90,7 @@ func TestBuildAuthRequestIPShape(t *testing.T) { // domain is omitted when empty; when set it sits between ip and procHash. withDomain, err := buildAuthRequestIP("sid", "app", "84B5B45FE73EC0036C3E97717308447F", - "180.101.49.44", 443, net.IPv4(10, 19, 240, 43).To4(), 30002, 2, "www.baidu.com", protocolTCP) + "180.101.49.44", 443, net.IPv4(10, 19, 240, 43).To4(), 30002, 2, "www.baidu.com", protocolTCP, nil) if err != nil { t.Fatal(err) } @@ -128,7 +131,7 @@ func TestBuildAuthRequestIPShape(t *testing.T) { func TestBuildAuthRequestIPUDP(t *testing.T) { body, err := buildAuthRequestIP("sid", "app", "device", "10.13.87.17", 53, - net.IPv4(10, 19, 240, 43).To4(), 30001, 1, "", protocolUDP) + net.IPv4(10, 19, 240, 43).To4(), 30001, 1, "", protocolUDP, nil) if err != nil { t.Fatal(err) } @@ -145,7 +148,7 @@ func TestBuildAuthRequestIPUDP(t *testing.T) { } func TestBuildAuthRequestICMP(t *testing.T) { - body, err := buildAuthRequestIP("sid", "app", "device", "192.0.2.1", 0, net.IPv4(10, 0, 0, 1), 0, 1, "", protocolICMP) + body, err := buildAuthRequestIP("sid", "app", "device", "192.0.2.1", 0, net.IPv4(10, 0, 0, 1), 0, 1, "", protocolICMP, nil) if err != nil { t.Fatal(err) } @@ -160,3 +163,20 @@ func TestBuildAuthRequestICMP(t *testing.T) { t.Fatal("unknown protocol accepted") } } + +func TestConfiguredProcessIdentity(t *testing.T) { + identity := &deployment.ProcessIdentity{Name: "custom-client", Platform: "Windows", Path: "custom-client.exe"} + body, err := buildAuthRequestIP("sid", "app", "device", "192.0.2.1", 443, net.IPv4(10, 0, 0, 1), 30000, 1, "", protocolTCP, identity) + if err != nil { + t.Fatal(err) + } + var request authRequestIP + if err := json.Unmarshal(body, &request); err != nil { + t.Fatal(err) + } + process := request.Env.Application.Runtime.Process + fingerprint := fmt.Sprintf("%X", sha256.Sum256([]byte(identity.Path))) + if process.Name != identity.Name || process.Platform != identity.Platform || process.Path != identity.Path || process.Fingerprint != fingerprint || request.ProcHash != fingerprint { + t.Fatal("configured identity not used consistently") + } +} diff --git a/internal/l3/dialer.go b/internal/l3/dialer.go index 903fe92..f0f9e4f 100644 --- a/internal/l3/dialer.go +++ b/internal/l3/dialer.go @@ -10,8 +10,8 @@ import ( "syscall" "time" - "geektrust/internal/session" - "geektrust/internal/tunnel" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" + "github.com/ShanghaitechGeekPie/geektrust/internal/tunnel" ) const ( @@ -55,7 +55,7 @@ func (d *Dialer) Dial(ctx context.Context, ip string, port int, appID, domain st if err == nil { return conn, nil } - if !tunnel.ShouldFallbackToL3(err) { + if !cred.AllowTCPFallback || !tunnel.ShouldFallbackToL3(err) { return nil, err } d.Logger.Debug("direct TCP unavailable; falling back to L3", "ip", ip, "port", port, "err", err) @@ -234,7 +234,7 @@ func (d *Dialer) authorizeFlow(ctx context.Context, ip string, port int, appID, authID := tun.NextAuthID() // Tunnel establishment may refresh the session after cred was read. - body, err := buildAuthRequestIP(tun.SID(), appID, cred.DeviceID, ip, port, tun.VIP(), srcPort, authID, domain, protocol) + body, err := buildAuthRequestIP(tun.SID(), appID, cred.DeviceID, ip, port, tun.VIP(), srcPort, authID, domain, protocol, cred.ProcessIdentity) if err != nil { flow.release() return nil, err diff --git a/internal/l3/gvisor.go b/internal/l3/gvisor.go index 4cd219e..1249d8a 100644 --- a/internal/l3/gvisor.go +++ b/internal/l3/gvisor.go @@ -10,7 +10,7 @@ import ( "sync" "time" - "geektrust/internal/tunnel" + "github.com/ShanghaitechGeekPie/geektrust/internal/tunnel" "github.com/metacubex/gvisor/pkg/buffer" "github.com/metacubex/gvisor/pkg/tcpip" diff --git a/internal/l3/icmp.go b/internal/l3/icmp.go index 1634e49..ce2afd9 100644 --- a/internal/l3/icmp.go +++ b/internal/l3/icmp.go @@ -9,7 +9,7 @@ import ( "net" "time" - "geektrust/internal/tunnel" + "github.com/ShanghaitechGeekPie/geektrust/internal/tunnel" ) const ( @@ -57,7 +57,7 @@ func (d *Dialer) ExchangePacket(ctx context.Context, packet []byte) ([]byte, err defer tun.UnregisterConn(id) authID := tun.NextAuthID() // ICMP has no transport ports; only the Echo identifier is rewritten below. - body, err := buildAuthRequestIP(tun.SID(), app, cred.DeviceID, destination.String(), 0, tun.VIP(), 0, authID, "", protocolICMP) + body, err := buildAuthRequestIP(tun.SID(), app, cred.DeviceID, destination.String(), 0, tun.VIP(), 0, authID, "", protocolICMP, cred.ProcessIdentity) if err != nil { return nil, err } diff --git a/internal/l3/session_regression_test.go b/internal/l3/session_regression_test.go index 2547b20..fcf7230 100644 --- a/internal/l3/session_regression_test.go +++ b/internal/l3/session_regression_test.go @@ -17,10 +17,10 @@ import ( "testing" "time" - "geektrust/internal/frame" - "geektrust/internal/sdpc" - "geektrust/internal/session" - "geektrust/internal/tunnel" + "github.com/ShanghaitechGeekPie/geektrust/internal/frame" + "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" + "github.com/ShanghaitechGeekPie/geektrust/internal/tunnel" ) type flowSessionProvider struct { diff --git a/internal/resolver/adaptive_test.go b/internal/resolver/adaptive_test.go index 4b41118..6b277bf 100644 --- a/internal/resolver/adaptive_test.go +++ b/internal/resolver/adaptive_test.go @@ -13,8 +13,8 @@ import ( "testing" "time" - "geektrust/internal/sdpc" - "geektrust/internal/session" + "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" "golang.org/x/net/dns/dnsmessage" ) diff --git a/internal/resolver/resolver.go b/internal/resolver/resolver.go index 9cf197a..22b616b 100644 --- a/internal/resolver/resolver.go +++ b/internal/resolver/resolver.go @@ -13,7 +13,7 @@ import ( "strings" "time" - "geektrust/internal/session" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" ) type TunnelDialer interface { diff --git a/internal/resolver/resolver_test.go b/internal/resolver/resolver_test.go index 3f5aec3..852d89c 100644 --- a/internal/resolver/resolver_test.go +++ b/internal/resolver/resolver_test.go @@ -8,8 +8,8 @@ import ( "testing" "time" - "geektrust/internal/sdpc" - "geektrust/internal/session" + "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" ) func TestIsFakeIP(t *testing.T) { diff --git a/internal/sdpc/authconfig.go b/internal/sdpc/authconfig.go index c149cfb..d353c4f 100644 --- a/internal/sdpc/authconfig.go +++ b/internal/sdpc/authconfig.go @@ -18,7 +18,7 @@ type AuthConfig struct { // AuthConfig fetches /passport/v1/public/authConfig and stores the csrf token // for subsequent calls. -func (c *Client) AuthConfig(ctx context.Context) (*AuthConfig, error) { +func (c *Client) AuthConfig(ctx context.Context, selectCASDomain bool) (*AuthConfig, error) { var data struct { AuthServerInfoList []struct { AuthType string `json:"authType"` @@ -43,7 +43,7 @@ func (c *Client) AuthConfig(ctx context.Context) (*AuthConfig, error) { return nil, &APIError{Op: "authConfig", Code: -1, Message: "response missing security.csrfToken"} } c.csrf = data.Security.CsrfToken - if c.LoginDomain == "" { + if selectCASDomain && c.LoginDomain == "" { var selected string for _, method := range data.AuthServerInfoList { if method.AuthType != "auth/cas" || method.LoginDomain == "" { diff --git a/internal/sdpc/authconfig_test.go b/internal/sdpc/authconfig_test.go index 2c740b2..c646fe2 100644 --- a/internal/sdpc/authconfig_test.go +++ b/internal/sdpc/authconfig_test.go @@ -15,15 +15,18 @@ func TestAmbiguousCASDomainDoesNotChangeSelection(t *testing.T) { defer server.Close() c := NewClient(server.URL, "Mac", "synthetic-device", server.Client()) for i := 0; i < 2; i++ { - if _, err := c.AuthConfig(context.Background()); err == nil { + if _, err := c.AuthConfig(context.Background(), true); err == nil { t.Fatal("ambiguous CAS selection accepted") } if c.LoginDomain != "" { t.Fatal("failed discovery changed the selected domain") } } + if _, err := c.AuthConfig(context.Background(), false); err != nil { + t.Fatal("custom controller login must not require CAS domain selection:", err) + } c.LoginDomain = "explicit" - if _, err := c.AuthConfig(context.Background()); err != nil { + if _, err := c.AuthConfig(context.Background(), true); err != nil { t.Fatal(err) } if c.LoginDomain != "explicit" { diff --git a/internal/sdpc/login.go b/internal/sdpc/login.go index 3bb64c6..39fcbd4 100644 --- a/internal/sdpc/login.go +++ b/internal/sdpc/login.go @@ -6,6 +6,8 @@ import ( "fmt" "net/http" "net/url" + + "github.com/ShanghaitechGeekPie/geektrust/auth" ) // CasTicket runs the CAS redirect chain: @@ -139,14 +141,22 @@ func (c *Client) AuthCheck(ctx context.Context) (needSMS bool, err error) { return false, err } if data.NextService != "" { - return data.NextService == "auth/sms", nil + switch data.NextService { + case "auth/sms": + return true, nil + default: + return false, &auth.UnsupportedError{Method: data.NextService} + } } + needSMS = false for _, item := range data.NextServiceList { if item.AuthType == "auth/sms" { - return true, nil + needSMS = true + } else { + return false, &auth.UnsupportedError{Method: item.AuthType} } } - return false, nil + return needSMS, nil } // SendSMS triggers the verification text. diff --git a/internal/sdpc/login_test.go b/internal/sdpc/login_test.go new file mode 100644 index 0000000..22f3f98 --- /dev/null +++ b/internal/sdpc/login_test.go @@ -0,0 +1,34 @@ +package sdpc + +import ( + "context" + "errors" + "fmt" + "github.com/ShanghaitechGeekPie/geektrust/auth" + "net/http" + "net/http/httptest" + "testing" +) + +func TestAuthCheckRejectsUnknownSteps(t *testing.T) { + for _, tc := range []struct { + body string + sms, unsupported bool + }{ + {`{}`, false, false}, + {`{"nextService":"auth/sms"}`, true, false}, + {`{"nextServiceList":[{"authType":"auth/sms"}]}`, true, false}, + {`{"nextService":"auth/captcha","nextServiceList":[{"authType":"auth/sms"}]}`, false, true}, + {`{"nextServiceList":[{"authType":"auth/captcha"}]}`, false, true}, + } { + t.Run(tc.body, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, `{"code":0,"data":%s}`, tc.body) })) + defer server.Close() + client := NewClient(server.URL, "Mac", "device", server.Client()) + sms, err := client.AuthCheck(context.Background()) + if sms != tc.sms || errors.Is(err, auth.ErrUnsupported) != tc.unsupported || (!tc.unsupported && err != nil) { + t.Fatalf("sms=%v err=%v", sms, err) + } + }) + } +} diff --git a/internal/session/authentication_test.go b/internal/session/authentication_test.go new file mode 100644 index 0000000..6c1566f --- /dev/null +++ b/internal/session/authentication_test.go @@ -0,0 +1,50 @@ +package session + +import ( + "context" + "errors" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "github.com/ShanghaitechGeekPie/geektrust/auth" + "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" +) + +func TestMissingChallengeHandlerReturnsTypedError(t *testing.T) { + p := &Provider{} + _, err := p.smsFlow(context.Background(), nil) + var required *auth.RequiredError + if !errors.Is(err, auth.ErrRequired) || !errors.As(err, &required) || required.Challenge.Method != "auth/sms" { + t.Fatalf("unexpected challenge error: %v", err) + } +} + +func TestCancelledChallengeDoesNotSubmitAnswer(t *testing.T) { + var submissions atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Query().Get("action") == "checkcode" { + submissions.Add(1) + } + io.WriteString(w, `{"code":0,"data":{}}`) + })) + defer server.Close() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + p := &Provider{logger: slog.New(slog.NewTextHandler(io.Discard, nil)), ChallengeHandler: func(ctx context.Context, challenge auth.Challenge) (string, error) { + deadline, ok := ctx.Deadline() + if !ok || !deadline.Equal(challenge.ExpiresAt) || time.Until(deadline) > time.Minute { + t.Fatal("challenge missing bounded lifetime") + } + cancel() + return "synthetic-answer", nil + }} + _, err := p.smsFlow(ctx, sdpc.NewClient(server.URL, "Mac", "device", server.Client())) + if !errors.Is(err, context.Canceled) || submissions.Load() != 0 { + t.Fatalf("err=%v submissions=%d", err, submissions.Load()) + } +} diff --git a/internal/session/events.go b/internal/session/events.go index 1bb344f..a529f71 100644 --- a/internal/session/events.go +++ b/internal/session/events.go @@ -5,7 +5,7 @@ import ( "regexp" "time" - "geektrust/internal/sdpc" + "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" ) // EventKind identifies a session lifecycle event. diff --git a/internal/session/events_test.go b/internal/session/events_test.go index 440e858..b8fbb65 100644 --- a/internal/session/events_test.go +++ b/internal/session/events_test.go @@ -14,8 +14,8 @@ import ( "testing" "time" - "geektrust/internal/config" - "geektrust/internal/sdpc" + "github.com/ShanghaitechGeekPie/geektrust/internal/config" + "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" ) // recordObserver collects events and lets tests hook individual kinds. diff --git a/internal/session/live_test.go b/internal/session/live_test.go index 0035614..9871eca 100644 --- a/internal/session/live_test.go +++ b/internal/session/live_test.go @@ -8,7 +8,7 @@ import ( "testing" "time" - "geektrust/internal/config" + "github.com/ShanghaitechGeekPie/geektrust/internal/config" ) type ephemeralStore struct{} diff --git a/internal/session/provider.go b/internal/session/provider.go index 70ce973..78d7f56 100644 --- a/internal/session/provider.go +++ b/internal/session/provider.go @@ -11,9 +11,11 @@ import ( "sync" "time" - "geektrust/internal/config" - "geektrust/internal/idsauth" - "geektrust/internal/sdpc" + "github.com/ShanghaitechGeekPie/geektrust/auth" + "github.com/ShanghaitechGeekPie/geektrust/deployment" + "github.com/ShanghaitechGeekPie/geektrust/internal/config" + "github.com/ShanghaitechGeekPie/geektrust/internal/idsauth" + "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" ) // errSMSAuthSessionExpired marks an expiration discovered after the user has @@ -23,19 +25,21 @@ var errSMSAuthSessionExpired = errors.New("SMS authentication session expired") // Credential is everything the tunnel and resolver need from a live session. type Credential struct { + ProcessIdentity *deployment.ProcessIdentity // AppID is the legacy fallback; matched resource rules always take priority. - AppID string - LegacyRouting bool - GatewayOverride bool - Original *Credential - SID string - DeviceID string - Username string - ConnectionID string - CsrfToken string - Cookies []*http.Cookie - Gateways []string - DNS []string + AppID string + MissingGatewayGroupFallback bool + GatewayOverride bool + AllowTCPFallback bool + Original *Credential + SID string + DeviceID string + Username string + ConnectionID string + CsrfToken string + Cookies []*http.Cookie + Gateways []string + DNS []string // Policy is the full routing policy (domain/IP/CIDR × port → appId) // from clientResource. Policy *sdpc.Resource @@ -62,13 +66,15 @@ type CredentialProvider interface { // credentials, restoring a persisted session or re-logging in silently // when the controller does not request SMS. type Provider struct { - cfg *config.Config - logger *slog.Logger - prompt SMSPrompter - smsHandler SMSHandler // set by SetSMSHandler during web wiring - store StateStore - Authenticate func(context.Context, *http.Client) (string, error) - Transport http.RoundTripper + cfg *config.Config + logger *slog.Logger + prompt SMSPrompter + smsHandler SMSHandler // set by SetSMSHandler during web wiring + store StateStore + Authenticate func(context.Context, *http.Client) (string, error) + ControllerLogin auth.ControllerLogin + ChallengeHandler auth.Handler + Transport http.RoundTripper mu sync.Mutex cur *Credential @@ -99,7 +105,7 @@ type refreshCall struct { // requires SMS then returns an error. func NewProvider(cfg *config.Config, logger *slog.Logger, prompt SMSPrompter) *Provider { normalized := *cfg - normalized.ApplyControllerDefaults() + normalized.Compatibility = cfg.Compatibility.Clone() cfg = &normalized return &Provider{ cfg: cfg, @@ -470,7 +476,7 @@ func (p *Provider) restore(ctx context.Context) (*Credential, *SessionInfo, erro if !info.IsOnline { return nil, nil, errors.New("persisted session is offline") } - cred, err := p.finishLogin(ctx, sc, st.Gateways, info.Username) + cred, err := p.finishLogin(ctx, sc, info.Username) if err != nil { return nil, nil, err } @@ -514,6 +520,31 @@ func (p *Provider) login(ctx context.Context) (*Credential, *SessionInfo, error) func (p *Provider) loginOnce(ctx context.Context) (*Credential, *SessionInfo, error) { jar, _ := cookiejar.New(nil) hc := &http.Client{Jar: jar, Timeout: 30 * time.Second, Transport: p.Transport} + if p.ControllerLogin != nil { + sc := p.newSDPC(hc) + if _, err := sc.AuthConfig(ctx, false); err != nil { + return nil, nil, err + } + request := auth.ControllerRequest{URL: p.cfg.BaseURL, DeviceID: p.cfg.DeviceID, Platform: p.cfg.Platform, ClientType: sc.ClientType, LoginDomain: sc.LoginDomain, CSRFToken: sc.CSRF()} + if err := p.ControllerLogin(ctx, hc, request); err != nil { + return nil, nil, err + } + if sc.SID() == "" { + return nil, nil, errors.New("controller authentication did not establish a session") + } + info, err := sc.OnlineInfo(ctx) + if err != nil { + return nil, nil, err + } + if !info.IsOnline { + return nil, nil, errors.New("controller authentication reports offline") + } + cred, err := p.finishLogin(ctx, sc, info.Username) + if err != nil { + return nil, nil, err + } + return cred, newSessionInfo(info, cred, p.cfg.ClientType), nil + } authenticate := p.Authenticate if authenticate == nil { authenticate = func(ctx context.Context, hc *http.Client) (string, error) { @@ -531,7 +562,7 @@ func (p *Provider) loginOnce(ctx context.Context) (*Credential, *SessionInfo, er return nil, nil, fmt.Errorf("identity authentication: %w", err) } sc := p.newSDPC(hc) - ac, err := sc.AuthConfig(ctx) + ac, err := sc.AuthConfig(ctx, true) if err != nil { return nil, nil, err } @@ -582,7 +613,7 @@ func (p *Provider) loginOnce(ctx context.Context) (*Credential, *SessionInfo, er p.logger.Info("device bound as trusted terminal") } } - cred, err := p.finishLogin(ctx, sc, nil, info.Username) + cred, err := p.finishLogin(ctx, sc, info.Username) if err != nil { return nil, nil, err } @@ -591,8 +622,8 @@ func (p *Provider) loginOnce(ctx context.Context) (*Credential, *SessionInfo, er // smsFlow completes controller-requested SMS verification. func (p *Provider) smsFlow(ctx context.Context, sc *sdpc.Client) (string, error) { - if p.smsHandler == nil && p.prompt == nil { - return "", errors.New("the controller requires SMS verification, but no prompt is available") + if p.smsHandler == nil && p.prompt == nil && p.ChallengeHandler == nil { + return "", &auth.RequiredError{Challenge: auth.Challenge{Method: "auth/sms"}} } if err := sc.SendSMS(ctx); err != nil { // 75500401: a code was already sent and is still valid — verify it @@ -605,7 +636,16 @@ func (p *Provider) smsFlow(ctx context.Context, sc *sdpc.Client) (string, error) } var code string var promptErr error - if p.smsHandler != nil { + if p.ChallengeHandler != nil { + challengeCtx, cancel := context.WithTimeout(ctx, time.Minute) + defer cancel() + ctx = challengeCtx + expires, _ := challengeCtx.Deadline() + code, promptErr = p.ChallengeHandler(challengeCtx, auth.Challenge{Method: "auth/sms", ExpiresAt: expires}) + if err := challengeCtx.Err(); err != nil { + return "", err + } + } else if p.smsHandler != nil { // Keep typed controller errors for the web layer. An expired auth // session also carries the private restart marker consumed by login. resendFn := func(ctx context.Context) error { @@ -633,8 +673,8 @@ func (p *Provider) smsFlow(ctx context.Context, sc *sdpc.Client) (string, error) } // finishLogin pulls clientResource, assembles the Credential and persists the -// state file. gatewaysOverride comes from the persisted state (if any). -func (p *Provider) finishLogin(ctx context.Context, sc *sdpc.Client, gatewaysOverride []string, username string) (*Credential, error) { +// state file. Routing always uses the current policy and explicit configuration. +func (p *Provider) finishLogin(ctx context.Context, sc *sdpc.Client, username string) (*Credential, error) { res, err := sc.ClientResource(ctx) if err != nil { return nil, fmt.Errorf("clientResource: %w", err) @@ -645,11 +685,8 @@ func (p *Provider) finishLogin(ctx context.Context, sc *sdpc.Client, gatewaysOve if len(gateways) == 0 { gateways = res.Gateways } - if len(gateways) == 0 && len(gatewaysOverride) > 0 { - gateways = gatewaysOverride - } - if len(gateways) == 0 && p.cfg.IsShanghaiTech() { - gateways = []string{"119.78.254.241:441", "59.78.171.241:441"} + if len(gateways) == 0 { + gateways = append([]string(nil), p.cfg.Compatibility.FallbackGateways...) } if len(gateways) == 0 { return nil, fmt.Errorf("controller supplied no gateway addresses") @@ -660,18 +697,20 @@ func (p *Provider) finishLogin(ctx context.Context, sc *sdpc.Client, gatewaysOve } cred := &Credential{ - AppID: p.cfg.AppID, - LegacyRouting: p.cfg.IsShanghaiTech(), - GatewayOverride: len(p.cfg.Gateways) != 0, - SID: sc.SID(), - DeviceID: p.cfg.DeviceID, - Username: username, - ConnectionID: fmt.Sprintf("%X-%d", md5.Sum([]byte(p.cfg.DeviceID)), time.Now().UnixMicro()), - CsrfToken: sc.CSRF(), - Cookies: sc.Cookies(), - Gateways: gateways, - DNS: dns, - Policy: res, + ProcessIdentity: p.cfg.Compatibility.ProcessIdentity, + AppID: p.cfg.Compatibility.FallbackAppID, + MissingGatewayGroupFallback: p.cfg.Compatibility.MissingGatewayGroupFallback, + AllowTCPFallback: p.cfg.Compatibility.TCPToL3Fallback, + GatewayOverride: len(p.cfg.Gateways) != 0, + SID: sc.SID(), + DeviceID: p.cfg.DeviceID, + Username: username, + ConnectionID: fmt.Sprintf("%X-%d", md5.Sum([]byte(p.cfg.DeviceID)), time.Now().UnixMicro()), + CsrfToken: sc.CSRF(), + Cookies: sc.Cookies(), + Gateways: gateways, + DNS: dns, + Policy: res, } records := make([]CookieRecord, 0, len(cred.Cookies)) diff --git a/internal/session/provider_test.go b/internal/session/provider_test.go index 085572c..66cf613 100644 --- a/internal/session/provider_test.go +++ b/internal/session/provider_test.go @@ -16,8 +16,8 @@ import ( "testing" "time" - "geektrust/internal/config" - "geektrust/internal/sdpc" + "github.com/ShanghaitechGeekPie/geektrust/internal/config" + "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" ) type smsHandlerFunc func(context.Context, func(context.Context) error) (string, error) diff --git a/internal/session/routing.go b/internal/session/routing.go index 1bffc19..0cbefa7 100644 --- a/internal/session/routing.go +++ b/internal/session/routing.go @@ -1,7 +1,7 @@ package session -// GatewaysForGroup respects explicit configuration overrides. ShanghaiTech also -// retains the old flattened-list fallback for incomplete controller responses. +// GatewaysForGroup restricts configured gateways to the assigned group. Missing +// groups may use the flattened list only when compatibility explicitly allows it. func (c *Credential) GatewaysForGroup(group string) []string { var assigned []string if c.Policy != nil { @@ -11,6 +11,14 @@ func (c *Credential) GatewaysForGroup(group string) []string { assigned = c.Policy.NodeGroups[group] } } + if len(assigned) == 0 && (group == "" || c.MissingGatewayGroupFallback) { + if c.Policy != nil { + assigned = c.Policy.Gateways + } + if len(assigned) == 0 { + assigned = c.Gateways + } + } if c.GatewayOverride { var matching []string for _, addr := range assigned { @@ -21,13 +29,7 @@ func (c *Credential) GatewaysForGroup(group string) []string { } } } - if len(matching) != 0 { - return matching - } - return append([]string(nil), c.Gateways...) - } - if len(assigned) == 0 && (group == "" || c.LegacyRouting) { - assigned = c.Gateways + return matching } return append([]string(nil), assigned...) } diff --git a/internal/session/routing_test.go b/internal/session/routing_test.go index 40d7794..b41fe2d 100644 --- a/internal/session/routing_test.go +++ b/internal/session/routing_test.go @@ -4,25 +4,27 @@ import ( "reflect" "testing" - "geektrust/internal/sdpc" + "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" ) func TestGatewaySelectionCompatibility(t *testing.T) { policy := &sdpc.Resource{Gateways: []string{"a:441", "b:441"}, NodeGroups: map[string][]string{"g": {"a:441"}}, AppNodeGroups: map[string]string{"app": "g"}, MajorNodeGroup: "g"} for _, tt := range []struct { - name, group string - override, legacy bool - configured, want []string + name, group string + override, fallback bool + configured, want []string }{ {"assigned", "g", false, false, []string{"a:441", "b:441"}, []string{"a:441"}}, {"configured intersection", "g", true, true, []string{"a:441", "b:441"}, []string{"a:441"}}, - {"explicit alternate", "g", true, true, []string{"alternate:441"}, []string{"alternate:441"}}, - {"legacy missing group", "missing", false, true, []string{"a:441", "b:441"}, []string{"a:441", "b:441"}}, + {"explicit alternate rejected", "g", true, true, []string{"alternate:441"}, nil}, + {"enabled missing group", "missing", false, true, []string{"a:441", "b:441"}, []string{"a:441", "b:441"}}, + {"missing group with filter", "missing", true, true, []string{"b:441"}, []string{"b:441"}}, + {"missing group excludes unassigned", "missing", true, true, []string{"other:441"}, nil}, {"strict missing group", "missing", false, false, []string{"a:441", "b:441"}, nil}, {"no group", "", false, false, []string{"a:441", "b:441"}, []string{"a:441", "b:441"}}, } { t.Run(tt.name, func(t *testing.T) { - c := &Credential{Policy: policy, Gateways: tt.configured, GatewayOverride: tt.override, LegacyRouting: tt.legacy} + c := &Credential{Policy: policy, Gateways: tt.configured, GatewayOverride: tt.override, MissingGatewayGroupFallback: tt.fallback} if got := c.GatewaysForGroup(tt.group); !reflect.DeepEqual(got, tt.want) { t.Fatalf("got %v want %v", got, tt.want) } diff --git a/internal/session/store.go b/internal/session/store.go index 8f876e2..124581c 100644 --- a/internal/session/store.go +++ b/internal/session/store.go @@ -16,7 +16,7 @@ import ( "path/filepath" "time" - "geektrust/internal/privatefile" + "github.com/ShanghaitechGeekPie/geektrust/internal/privatefile" ) // State is the persisted session (encrypted, 0600). diff --git a/internal/tunnel/reconnect.go b/internal/tunnel/reconnect.go index 797594a..4c5bab9 100644 --- a/internal/tunnel/reconnect.go +++ b/internal/tunnel/reconnect.go @@ -12,8 +12,8 @@ import ( "sync" "time" - "geektrust/internal/frame" - "geektrust/internal/session" + "github.com/ShanghaitechGeekPie/geektrust/internal/frame" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" ) const ( diff --git a/internal/tunnel/reconnect_regression_test.go b/internal/tunnel/reconnect_regression_test.go index a1ccb66..7618de4 100644 --- a/internal/tunnel/reconnect_regression_test.go +++ b/internal/tunnel/reconnect_regression_test.go @@ -18,7 +18,7 @@ import ( "testing" "time" - "geektrust/internal/session" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" ) type reconnectTestProvider struct { diff --git a/internal/tunnel/reconnect_test.go b/internal/tunnel/reconnect_test.go index cf2e2ac..fde786d 100644 --- a/internal/tunnel/reconnect_test.go +++ b/internal/tunnel/reconnect_test.go @@ -10,8 +10,8 @@ import ( "testing" "time" - "geektrust/internal/sdpc" - "geektrust/internal/session" + "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" ) type managerTestProvider struct{} diff --git a/internal/tunnel/tcp.go b/internal/tunnel/tcp.go index e8e565d..485805d 100644 --- a/internal/tunnel/tcp.go +++ b/internal/tunnel/tcp.go @@ -16,7 +16,7 @@ import ( "syscall" "time" - "geektrust/internal/session" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" ) const ( @@ -64,6 +64,14 @@ type tcpAuthRequest struct { XRequestSig string `json:"xRequestSig"` } +// TCPAuthError is an explicit gateway authentication rejection. It is terminal +// across both gateway selection and stream-to-L3 compatibility fallback. +type TCPAuthError struct{ Code int64 } + +func (e *TCPAuthError) Error() string { + return fmt.Sprintf("direct TCP protocol rejected request: code %d", e.Code) +} + // TCPStatusError is the gateway's SOCKS-style result for opening the target. type TCPStatusError struct { Status byte @@ -115,16 +123,17 @@ func ShouldFallbackToL3(err error) bool { if err == nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { return false } - var status *TCPStatusError - if !errors.As(err, &status) { - return true - } - switch status.Status { - case 0x03, 0x04, 0x05, 0x06: + var rejected *TCPAuthError + if errors.As(err, &rejected) { return false - default: - return true } + var status *TCPStatusError + if errors.As(err, &status) { + return status.Status == 0x07 || status.Status == 0x08 + } + // Only incomplete setup exchanges can indicate an unsupported stream path. + // TLS verification, authentication rejection and unknown failures are terminal. + return errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) } // DialTCP opens an aTrust TCP proxy connection. TCP uses the server's stream @@ -165,6 +174,10 @@ func (m *Manager) DialTCP(ctx context.Context, ip string, port int, appID, domai return tunneled, nil } lastErr = err + var rejected *TCPAuthError + if errors.As(err, &rejected) { + return nil, err + } var status *TCPStatusError if errors.As(err, &status) && status.Status != 0x01 { return nil, err @@ -259,6 +272,14 @@ func buildTCPRequest(cred *session.Credential, ip string, port int, appID, domai processName, processPath = "ssh", "/usr/bin/ssh" fingerprint = fmt.Sprintf("%X", sha256.Sum256([]byte(processPath))) } + processPlatform := "Linux" + if identity := cred.ProcessIdentity; identity != nil { + if err := identity.Validate(); err != nil { + return nil, err + } + processName, processPath, processPlatform = identity.Name, identity.Path, identity.Platform + fingerprint = fmt.Sprintf("%X", sha256.Sum256([]byte(processPath))) + } req := tcpAuthRequest{ SID: cred.SID, AppID: appID, URL: "tcp://" + dest, DeviceID: cred.DeviceID, ConnectionID: connectionID, @@ -266,7 +287,7 @@ func buildTCPRequest(cred *session.Credential, ip string, port int, appID, domai } p := &req.Env.Application.Runtime.Process *p = tcpProcess{ - Name: processName, DigitalSignature: "TrustAppClosed", Platform: "Linux", + Name: processName, DigitalSignature: "TrustAppClosed", Platform: processPlatform, Fingerprint: fingerprint, Description: "TrustAppClosed", Path: processPath, Version: "TrustAppClosed", SecurityEnv: "normal", } @@ -341,7 +362,7 @@ func readTCPProtocolResponse(reader io.Reader) error { return fmt.Errorf("decode direct TCP protocol response: %w", err) } if response.Code != 0 { - return fmt.Errorf("direct TCP protocol rejected request: code %d: %s", response.Code, response.Message) + return &TCPAuthError{Code: response.Code} } return nil } diff --git a/internal/tunnel/tcp_test.go b/internal/tunnel/tcp_test.go index 81bf95b..4a69b24 100644 --- a/internal/tunnel/tcp_test.go +++ b/internal/tunnel/tcp_test.go @@ -9,11 +9,13 @@ import ( "errors" "io" "net" + "strings" "syscall" "testing" - "geektrust/internal/sdpc" - "geektrust/internal/session" + "github.com/ShanghaitechGeekPie/geektrust/deployment" + "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" ) func TestBuildTCPRequestCombinesAuthAndDestination(t *testing.T) { @@ -199,13 +201,43 @@ func TestDirectGatewaysUsesAssignedNodeGroup(t *testing.T) { } } -func TestLegacyTCPFallbackBoundaries(t *testing.T) { - for _, err := range []error{nil, context.Canceled, context.DeadlineExceeded, &TCPStatusError{Status: 0x03}, &TCPStatusError{Status: 0x04}, &TCPStatusError{Status: 0x05}, &TCPStatusError{Status: 0x06}} { +func TestTCPFallbackBoundaries(t *testing.T) { + for _, err := range []error{nil, errors.Join(&TCPAuthError{Code: 403}, io.EOF), errors.New("unclassified failure"), context.Canceled, context.DeadlineExceeded, &TCPStatusError{Status: 0x01}, &TCPStatusError{Status: 0x02}, &TCPStatusError{Status: 0x03}, &TCPStatusError{Status: 0x04}, &TCPStatusError{Status: 0x05}, &TCPStatusError{Status: 0x06}} { if ShouldFallbackToL3(err) { t.Fatalf("unexpected fallback: %v", err) } } - if !ShouldFallbackToL3(&TCPStatusError{Status: 0x02}) || !ShouldFallbackToL3(io.EOF) { + if !ShouldFallbackToL3(&TCPStatusError{Status: 0x07}) || !ShouldFallbackToL3(io.EOF) { t.Fatal("legacy protocol/setup fallback removed") } } + +func TestTCPAuthenticationDenialNeverFallsBack(t *testing.T) { + body := []byte(`{"code":403,"message":"sensitive-server-text"}`) + packet := make([]byte, 2) + binary.BigEndian.PutUint16(packet, uint16(len(body))) + err := readTCPProtocolResponse(bytes.NewReader(append(packet, body...))) + if err == nil || ShouldFallbackToL3(err) { + t.Fatal("authentication denial was accepted or retried") + } + if strings.Contains(err.Error(), "sensitive-server-text") { + t.Fatal("server response leaked") + } +} + +func TestTCPConfiguredProcessIdentity(t *testing.T) { + identity := &deployment.ProcessIdentity{Name: "custom-client", Platform: "Windows", Path: "custom-client.exe"} + packet, err := buildTCPRequest(&session.Credential{ProcessIdentity: identity}, "192.0.2.1", 22, "app", "") + if err != nil { + t.Fatal(err) + } + length := int(binary.BigEndian.Uint16(packet[5:7])) + var request tcpAuthRequest + if err := json.Unmarshal(packet[7:7+length], &request); err != nil { + t.Fatal(err) + } + process := request.Env.Application.Runtime.Process + if process.Name != identity.Name || process.Platform != identity.Platform || process.Path != identity.Path || process.Fingerprint != request.ProcHash || process.Fingerprint == chromeFingerprint { + t.Fatal("configured identity overridden by port heuristic") + } +} diff --git a/internal/tunnel/tunnel.go b/internal/tunnel/tunnel.go index 5ba39b2..eda9f2f 100644 --- a/internal/tunnel/tunnel.go +++ b/internal/tunnel/tunnel.go @@ -22,7 +22,7 @@ import ( "sync/atomic" "time" - "geektrust/internal/frame" + "github.com/ShanghaitechGeekPie/geektrust/internal/frame" ) const ( diff --git a/internal/webui/broker.go b/internal/webui/broker.go index e1521cd..c4188f5 100644 --- a/internal/webui/broker.go +++ b/internal/webui/broker.go @@ -10,7 +10,7 @@ import ( "strings" "sync" - "geektrust/internal/sdpc" + "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" ) // ErrNoPending is returned by claims and resends when no SMS verification is diff --git a/internal/webui/broker_test.go b/internal/webui/broker_test.go index e97cabc..ecb6895 100644 --- a/internal/webui/broker_test.go +++ b/internal/webui/broker_test.go @@ -11,7 +11,7 @@ import ( "testing" "time" - "geektrust/internal/sdpc" + "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" ) type promptResult struct { diff --git a/internal/webui/hub.go b/internal/webui/hub.go index a1456ab..7c91f4d 100644 --- a/internal/webui/hub.go +++ b/internal/webui/hub.go @@ -9,8 +9,8 @@ import ( "sync" "time" - "geektrust/internal/config" - "geektrust/internal/session" + "github.com/ShanghaitechGeekPie/geektrust/internal/config" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" ) // Panel states (§6.1 of docs/WEBUI.md). diff --git a/internal/webui/hub_test.go b/internal/webui/hub_test.go index fa5fb98..49287fd 100644 --- a/internal/webui/hub_test.go +++ b/internal/webui/hub_test.go @@ -6,8 +6,8 @@ import ( "testing" "time" - "geektrust/internal/config" - "geektrust/internal/session" + "github.com/ShanghaitechGeekPie/geektrust/internal/config" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" ) func testConfig(clientType string) *config.Config { diff --git a/internal/webui/server.go b/internal/webui/server.go index 905a561..f1d82d2 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -15,9 +15,9 @@ import ( "strings" "time" - "geektrust/internal/config" - "geektrust/internal/sdpc" - "geektrust/internal/session" + "github.com/ShanghaitechGeekPie/geektrust/internal/config" + "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" ) //go:embed all:dist diff --git a/internal/webui/server_test.go b/internal/webui/server_test.go index b6f7e06..a8a8709 100644 --- a/internal/webui/server_test.go +++ b/internal/webui/server_test.go @@ -15,8 +15,8 @@ import ( "testing" "time" - "geektrust/internal/sdpc" - "geektrust/internal/session" + "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" ) type fakeProvider struct { From f383a7b6ba33cafe89c529ebea6ebf57fd8ce88a Mon Sep 17 00:00:00 2001 From: 2018wzh Date: Sat, 3 Oct 2026 02:14:57 +0800 Subject: [PATCH 02/28] feat: allow embedders to restrict resolved destinations --- client/README.md | 2 ++ client/client.go | 38 +++++++++++++++++++++---------- client/packet.go | 15 ++++++++++++- client/target_test.go | 52 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 94 insertions(+), 13 deletions(-) create mode 100644 client/target_test.go diff --git a/client/README.md b/client/README.md index 8351e23..f85a840 100644 --- a/client/README.md +++ b/client/README.md @@ -35,3 +35,5 @@ defer conn.Close() `OpenTransport` 返回已建立线路和实际分配的 IPv4 地址。它们均不保证任意目标可达。 `Compatibility.ProcessIdentity` 可以覆盖流式 TCP 和 L3 的进程名、平台和路径,并统一重新计算指纹。 未配置时保留各自已实现的协议元数据;这些值与宿主操作系统无关,不代表平台连接验证结果。 + +`Options.CheckTarget` 可在解析出真实 IPv4 地址后、打开目标传输前执行调用方的路由限制;同样适用于 ICMP。回调必须支持并发调用,只能进一步限制访问,不能扩大控制器授权范围。库本身不决定系统路由。 diff --git a/client/client.go b/client/client.go index 29fc1f0..840aab0 100644 --- a/client/client.go +++ b/client/client.go @@ -11,6 +11,7 @@ import ( "log/slog" "net" "net/http" + "net/netip" "net/url" "strconv" "strings" @@ -108,6 +109,9 @@ func ValidatePasskey(b []byte) error { } type Options struct { + // CheckTarget may reject a resolved IPv4 destination before transport opens. + // It is called concurrently and cannot grant access outside controller policy. + CheckTarget func(netip.Addr) error Compatibility deployment.Compatibility Gateways []string DNS []string @@ -162,17 +166,18 @@ var ErrDatagramTooLarge = errors.New("UDP datagram exceeds tunnel MTU") var ErrDenied = errors.New("target is not authorized by controller policy") type Client struct { - provider *session.Provider - manager *tunnel.Manager - dialer *l3.Dialer - resolver *resolver.Resolver - ctx context.Context - cancel context.CancelFunc - mu sync.Mutex - closed bool - conns map[*ownedConn]struct{} - transport *http.Transport - events chan Event + checkTarget func(netip.Addr) error + provider *session.Provider + manager *tunnel.Manager + dialer *l3.Dialer + resolver *resolver.Resolver + ctx context.Context + cancel context.CancelFunc + mu sync.Mutex + closed bool + conns map[*ownedConn]struct{} + transport *http.Transport + events chan Event } func New(opts Options) (*Client, error) { @@ -234,7 +239,7 @@ func New(opts Options) (*Client, error) { m.GatewayTrustStore = opts.GatewayTrustStore d := &l3.Dialer{Manager: m, Provider: p, Logger: opts.Logger} ctx, cancel := context.WithCancel(context.Background()) - c := &Client{transport: ownedTransport, provider: p, manager: m, dialer: d, resolver: resolver.NewWithDialerOptions(p, d, opts.DialContext, opts.DisableSystemResolver), ctx: ctx, cancel: cancel, conns: make(map[*ownedConn]struct{}), events: make(chan Event, 16)} + c := &Client{checkTarget: opts.CheckTarget, transport: ownedTransport, provider: p, manager: m, dialer: d, resolver: resolver.NewWithDialerOptions(p, d, opts.DialContext, opts.DisableSystemResolver), ctx: ctx, cancel: cancel, conns: make(map[*ownedConn]struct{}), events: make(chan Event, 16)} p.AddObserver(clientObserver{c}) go p.CheckLoop(ctx, 5*time.Minute) return c, nil @@ -356,6 +361,15 @@ func (c *Client) DialContext(parent context.Context, network, address string) (n if target.AppID == "" { return nil, ErrDenied } + if c.checkTarget != nil { + ip, err := netip.ParseAddr(target.IP) + if err != nil { + return nil, err + } + if err := c.checkTarget(ip.Unmap()); err != nil { + return nil, err + } + } var conn net.Conn if protocol == "tcp" { conn, err = c.dialer.Dial(ctx, target.IP, port, target.AppID, target.Domain) diff --git a/client/packet.go b/client/packet.go index d794a64..8367b7c 100644 --- a/client/packet.go +++ b/client/packet.go @@ -1,6 +1,10 @@ package client -import "context" +import ( + "context" + "errors" + "net/netip" +) // PacketTransport is optional and owns no system interfaces. ExchangePacket // returns a real response or an error; it never synthesizes Echo success. @@ -13,6 +17,15 @@ func (c *Client) ExchangePacket(parent context.Context, packet []byte) ([]byte, if c.isClosed() { return nil, ErrClosed } + if c.checkTarget != nil { + if len(packet) < 20 || packet[0]>>4 != 4 { + return nil, errors.New("invalid IPv4 packet") + } + ip := netip.AddrFrom4([4]byte(packet[16:20])) + if err := c.checkTarget(ip); err != nil { + return nil, err + } + } ctx, done := c.operation(parent) defer done() return c.dialer.ExchangePacket(ctx, packet) diff --git a/client/target_test.go b/client/target_test.go new file mode 100644 index 0000000..99aebb8 --- /dev/null +++ b/client/target_test.go @@ -0,0 +1,52 @@ +package client + +import ( + "context" + "errors" + "github.com/ShanghaitechGeekPie/geektrust/deployment" + "github.com/ShanghaitechGeekPie/geektrust/internal/config" + "net" + "net/http" + "net/netip" + "testing" +) + +func TestTargetFilterRejectsBeforeGatewayDial(t *testing.T) { + rejected := errors.New("route excludes destination") + var seen []netip.Addr + c, err := New(Options{ + Compatibility: deployment.Compatibility{FallbackAppID: "app"}, + ControllerURL: config.DefaultBaseURL, DeviceID: "0123456789ABCDEF0123456789ABCDEF", + Gateways: []string{"gateway.example:441"}, Transport: compatibilityTransport{}, + SessionStore: compatibilityStore(`{"sid":"synthetic","device_id":"0123456789ABCDEF0123456789ABCDEF","client_type":"browser","cookies":[{"name":"sid","value":"synthetic"}]}`), + Authenticator: AuthenticatorFunc(func(context.Context, *http.Client) (string, error) { return "", errors.New("unexpected login") }), + CheckTarget: func(ip netip.Addr) error { seen = append(seen, ip); return rejected }, + DialContext: func(context.Context, string, string) (net.Conn, error) { + t.Error("excluded target opened transport") + return nil, errors.New("unexpected dial") + }, + }) + if err != nil { + t.Fatal(err) + } + defer c.Close() + for _, network := range []string{"tcp", "udp"} { + if _, err := c.DialContext(context.Background(), network, "192.0.2.1:443"); !errors.Is(err, rejected) { + t.Fatalf("%s target filter: %v", network, err) + } + } + packet := make([]byte, 28) + packet[0] = 0x45 + copy(packet[16:20], []byte{192, 0, 2, 1}) + if _, err := c.ExchangePacket(context.Background(), packet); !errors.Is(err, rejected) { + t.Fatalf("ICMP target filter: %v", err) + } + if len(seen) != 3 { + t.Fatalf("checked %d targets", len(seen)) + } + for _, ip := range seen { + if ip != netip.MustParseAddr("192.0.2.1") { + t.Fatal("wrong resolved destination") + } + } +} From 4bdc9746a8693c69cf88251a0b9454df97bf13bc Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Tue, 6 Oct 2026 01:20:50 +0800 Subject: [PATCH 03/28] refactor: unify runtime and versioned client contracts --- .github/workflows/ci.yml | 9 +- .github/workflows/release.yml | 33 +- README.md | 73 +-- auth/auth.go | 71 ++- auth/passkey.go | 77 +++ client/README.md | 44 +- client/client.go | 592 +++--------------- client/consumer_test.go | 31 + client/packet.go | 32 - cmd/geektrust/config_cmd.go | 73 +++ cmd/geektrust/init_cmd.go | 71 +-- .../init_permissions_windows_test.go | 164 ----- cmd/geektrust/library.go | 127 ++-- cmd/geektrust/main.go | 171 ++--- cmd/geektrust/main_test.go | 126 +--- config.example.toml | 124 ++-- deployment/profile.go | 101 ++- internal/config/compatibility_test.go | 46 +- internal/config/config.go | 79 ++- internal/config/example_regression_test.go | 4 +- internal/config/init.go | 57 +- internal/config/init_test.go | 2 +- internal/config/v2.go | 312 +++++++++ internal/config/v2_test.go | 62 ++ internal/deployment/profile.go | 56 ++ internal/deployment/shanghaitech.go | 11 + internal/idsauth/ecnu_test.go | 3 + internal/idsauth/keystore.go | 31 +- internal/inbound/http.go | 2 +- internal/inbound/server.go | 12 + internal/inbound/socks5.go | 2 +- internal/l3/auth.go | 4 +- internal/l3/auth_test.go | 4 +- internal/l3/fallback_stage_test.go | 54 ++ internal/privatefile/permissions.go | 34 +- internal/privatefile/permissions_unix.go | 16 +- internal/privatefile/permissions_windows.go | 202 +----- .../privatefile/permissions_windows_test.go | 97 --- internal/resolver/resolver.go | 56 +- {client => internal/runtime}/client_test.go | 24 +- internal/runtime/command.go | 70 +++ .../runtime}/compatibility_test.go | 64 +- internal/runtime/contract_test.go | 202 ++++++ internal/runtime/devices.go | 76 +++ internal/runtime/dns.go | 32 + internal/runtime/legacy_test.go | 141 +++++ internal/runtime/options.go | 109 ++++ internal/runtime/packet.go | 28 + internal/runtime/runtime.go | 510 +++++++++++++++ internal/runtime/status.go | 450 +++++++++++++ {client => internal/runtime}/target_test.go | 10 +- internal/sdpc/cancellation_test.go | 33 + internal/sdpc/client.go | 9 +- internal/sdpc/login.go | 15 +- internal/sdpc/resource.go | 13 +- internal/sdpc/resource_test.go | 28 + internal/session/authentication_test.go | 4 +- .../session/cancellation_regression_test.go | 10 +- internal/session/challenge.go | 59 ++ internal/session/challenge_test.go | 46 ++ internal/session/events.go | 3 + internal/session/events_test.go | 47 +- internal/session/interaction.go | 56 ++ internal/session/live_test.go | 3 + internal/session/provider.go | 175 +++--- internal/session/provider_test.go | 132 ++-- internal/session/routing.go | 7 +- internal/session/store.go | 171 ++--- internal/settings/compatibility.go | 73 +++ internal/settings/session.go | 17 + internal/storage/files.go | 95 +++ internal/storage/files_test.go | 39 ++ internal/storage/lock_unix.go | 39 ++ internal/storage/lock_windows.go | 38 ++ internal/storage/permissions_windows_test.go | 30 + internal/storage/sync_unix.go | 14 + internal/storage/sync_windows.go | 3 + internal/tunnel/line.go | 10 - internal/tunnel/line_test.go | 18 +- internal/tunnel/reconnect.go | 14 +- internal/tunnel/reset.go | 16 + internal/tunnel/tcp.go | 15 +- internal/tunnel/tcp_test.go | 8 +- internal/tunnel/tunnel.go | 9 +- internal/webui/broker.go | 38 +- internal/webui/broker_test.go | 42 +- internal/webui/hub.go | 8 +- internal/webui/server.go | 12 +- scripts/package-release-uv.sh | 11 +- scripts/package-release.sh | 9 +- scripts/release-targets.sh | 3 + web/src/api.ts | 45 +- web/src/components/SmsDialog.tsx | 8 +- web/src/components/TrustDevices.tsx | 20 +- web/src/types.ts | 1 + 95 files changed, 4024 insertions(+), 2203 deletions(-) create mode 100644 auth/passkey.go create mode 100644 client/consumer_test.go delete mode 100644 client/packet.go create mode 100644 cmd/geektrust/config_cmd.go delete mode 100644 cmd/geektrust/init_permissions_windows_test.go create mode 100644 internal/config/v2.go create mode 100644 internal/config/v2_test.go create mode 100644 internal/deployment/profile.go create mode 100644 internal/deployment/shanghaitech.go create mode 100644 internal/l3/fallback_stage_test.go delete mode 100644 internal/privatefile/permissions_windows_test.go rename {client => internal/runtime}/client_test.go (87%) create mode 100644 internal/runtime/command.go rename {client => internal/runtime}/compatibility_test.go (58%) create mode 100644 internal/runtime/contract_test.go create mode 100644 internal/runtime/devices.go create mode 100644 internal/runtime/dns.go create mode 100644 internal/runtime/legacy_test.go create mode 100644 internal/runtime/options.go create mode 100644 internal/runtime/packet.go create mode 100644 internal/runtime/runtime.go create mode 100644 internal/runtime/status.go rename {client => internal/runtime}/target_test.go (85%) create mode 100644 internal/sdpc/cancellation_test.go create mode 100644 internal/session/challenge.go create mode 100644 internal/session/challenge_test.go create mode 100644 internal/session/interaction.go create mode 100644 internal/settings/compatibility.go create mode 100644 internal/settings/session.go create mode 100644 internal/storage/files.go create mode 100644 internal/storage/files_test.go create mode 100644 internal/storage/lock_unix.go create mode 100644 internal/storage/lock_windows.go create mode 100644 internal/storage/permissions_windows_test.go create mode 100644 internal/storage/sync_unix.go create mode 100644 internal/storage/sync_windows.go create mode 100644 internal/tunnel/reset.go create mode 100644 scripts/release-targets.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d4c5a12..e7a1882 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,10 +18,17 @@ jobs: with: go-version-file: go.mod cache: true + - uses: actions/setup-node@v6 + with: + node-version: 20 + cache: npm + cache-dependency-path: web/package-lock.json + - name: Build panel + run: npm --prefix web ci && npm --prefix web run build - name: Unit and integration tests run: go test ./... - name: Race detector - run: go test -race ./client ./internal/idsauth ./internal/session ./internal/tunnel ./internal/l3 + run: go test -race ./client ./internal/runtime ./internal/idsauth ./internal/session ./internal/tunnel ./internal/l3 ./internal/resolver ./internal/webui ./internal/storage - name: Static analysis run: go vet ./... - name: Build packages diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f564b79..1c78eee 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,7 +1,6 @@ name: Release on: - pull_request: push: tags: - "v*" @@ -39,7 +38,7 @@ jobs: cache-dependency-path: web/package-lock.json - name: Check release scripts - run: bash -n scripts/package-release.sh scripts/package-release-uv.sh + run: bash -n scripts/package-release.sh scripts/package-release-uv.sh scripts/release-targets.sh - name: Build release packages env: @@ -53,6 +52,13 @@ jobs: - name: Verify release checksums run: cd dist && sha256sum --check SHA256SUMS + - name: Save verified packages + uses: actions/upload-artifact@v4 + with: + name: verified-release + path: dist/* + if-no-files-found: error + release: if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') @@ -63,27 +69,14 @@ jobs: timeout-minutes: 30 steps: - - name: Check out repository - uses: actions/checkout@v6 + - uses: actions/checkout@v6 with: persist-credentials: false - - - name: Set up Go - uses: actions/setup-go@v6 + - name: Download verified packages + uses: actions/download-artifact@v4 with: - go-version-file: go.mod - cache-dependency-path: go.sum - - - name: Set up Node.js - uses: actions/setup-node@v6 - with: - node-version: 20 - cache: npm - cache-dependency-path: web/package-lock.json - - - name: Build release packages - run: bash scripts/package-release.sh "$GITHUB_REF_NAME" dist - + name: verified-release + path: dist - name: Publish GitHub Release env: GH_TOKEN: ${{ github.token }} diff --git a/README.md b/README.md index b0d2511..3bf6193 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ brew install uv 1. 用系统安全随机源生成 128 位 `device_id`。 2. keystore 不存在时,通过 `uvx` 在隔离环境中运行 [shanghaitech-ids-passkey](https://github.com/vvbbnn00/shanghaitech-ids-passkey),打开浏览器完成绑定并生成 keystore。不会向全局环境安装任何 Python 包。 -3. 写入 `client_type = "client"` 的配置,启用本地 SOCKS5、HTTP 代理和 Web 面板。 +3. 写入 `auth.mode = "client"` 的版本 2 配置,启用本地 SOCKS5、HTTP 代理和 Web 面板。 配置文件已存在时,init 会拒绝覆盖。确实需要重建时再加 `--force`。 @@ -89,69 +89,31 @@ brew install uv ## 配置 -推荐用 `geektrust init` 生成配置。生成结果如下(另含一行注释): +`geektrust init` 生成版本 2 配置,保留设备 ID,并使用已有 Passkey。上科大的最小手工配置为: ```toml -keystore = "./ids-passkey.keystore" -device_id = "" -base_url = "https://vpn.shanghaitech.edu.cn" -platform = "Mac" -client_type = "client" -state_file = "./state.enc" -gateways = [] -dns = [] -log_level = "info" - -[inbound.socks5] -enabled = true -listen = "127.0.0.1:1080" - -[inbound.http] -enabled = true -listen = "127.0.0.1:8080" +config_version = 2 -[web] -enabled = true -listen = "127.0.0.1:8081" +[auth.passkey] +keystore = "./ids-passkey.keystore" ``` -手工编写配置可参考 [`config.example.toml`](config.example.toml)。 - -主要配置项: +相对路径以配置文件目录为准。设备身份和加密会话放在平台用户持久目录;上科大必需的网关证书域名由程序提供,证书验证继续开启。普通用户无需填写应用 ID、网关 IP 或协议回退开关。 -- `device_id`:设备的稳定身份。修改后服务器会把它视为新设备,需要重新验证和绑定。 -- `client_type`:推荐 `client`。手写配置省略该项时默认为 `browser`。 -- `keystore`:passkey 私钥文件。不要泄露,也不要提交到版本库。 -- `state_file`:加密的会话状态。密钥保存在同目录的 `.key`,两个文件都只允许当前用户读写。 -- `gateways`:留空时使用服务端下发的线路。 -- `dns`:通常留空,仅在需要覆盖服务端下发的隧道 DNS 时设置。 +配置按 `controller`、`auth`、`proxy`、`web`、`dns`、`storage`、`logging` 分组。监听地址省略时采用默认值,空字符串表示禁用。`auth.mode` 支持 `auto`、`client`、`browser`;browser 模式不能绑定授信终端。 -SOCKS5 和 HTTP 代理没有身份认证,只应监听 `127.0.0.1`。如果改成 `0.0.0.0`,同一网络中的其他设备也能使用你的 VPN 会话。 +旧格式继续可读,不自动重写。检查和迁移命令: -### 部署兼容选项 - -所有控制器默认采用严格模式,不再根据学校域名启用兼容行为。 -在配置文件中添加 `[compatibility]`,只开启目标部署需要的选项: - -```toml -[compatibility] -fallback_app_id = "" -fallback_gateways = [] -gateway_server_name = "" -missing_gateway_group_fallback = false -tcp_to_l3_fallback = false +```sh +./geektrust -config config.toml config check +./geektrust -config config.toml config show +./geektrust -config config.toml config migrate +./geektrust -config config.toml config migrate --write ``` -应用 ID 和网关地址仅用于缺失数据时的兜底;已有资源规则和非空网关组优先。 -TCP→L3 回退不覆盖认证拒绝、连接不允许、不可达或取消。 -TLS 域名覆盖仍验证证书;选项拼写错误会拒绝加载配置。 -修改后重新启动客户端;关闭选项后,缓存会话不会恢复旧的兜底网关。 -旧的顶层 `app_id` 已移除,请明确填写 `compatibility.fallback_app_id`。 -上海科大的可选值和进程元数据覆盖示例见 [config.example.toml](config.example.toml)。 - -### browser 兼容模式 +`migrate` 默认只预览,`--write` 保留 `.v1.bak` 备份。旧网关覆盖和新网关筛选含义不同,不能自动转换;复杂的显式兼容设置需要人工选择。设备 ID、凭据、签名计数器和原加密缓存不会被迁移命令删除或重置。 -只有在控制器不支持 client 模式时,才把 `client_type` 设为 `browser`。browser 模式不能绑定授信终端,会话彻底失效后可能再次要求短信。 +完整设置见 [config.example.toml](config.example.toml)。SOCKS5 和 HTTP 代理没有身份认证,默认监听回环地址;配置为非回环地址后,同一网络中的其他设备也能使用你的 VPN 会话。 ## Web 面板 @@ -159,7 +121,6 @@ TLS 域名覆盖仍验证证书;选项拼写错误会拒绝加载配置。 ```toml [web] -enabled = true listen = "127.0.0.1:8081" ``` @@ -175,7 +136,7 @@ listen = "127.0.0.1:8081" - `listen` 必须是回环地址,且不能使用 80 端口,否则配置加载失败。需要远程访问时用 SSH 转发:`ssh -L 8081:127.0.0.1:8081 user@host`。 - 面板启动失败(如端口被占用或与代理端口冲突)只会记录警告并跳过面板,不影响 VPN 和代理。 -- `enabled = false` 时不启动面板,短信只能在终端输入。 +- 版本 2 使用 `listen = ""` 禁用面板;旧格式继续读取 `enabled = false`。短信只能在终端输入。 ## 常用命令 @@ -224,7 +185,7 @@ curl -x http://127.0.0.1:8080 https://library.shanghaitech.edu.cn/qbsjk/list.htm 路由规则来自服务端下发的应用表,支持精确域名、域名后缀、精确 IP、CIDR、IP 区间和端口范围;范围越小的规则优先级越高。 -域名先用公共 DNS 和系统 DNS 解析。没有可用 IPv4 结果时,再通过 VPN 查询服务端下发的校内 DNS,以解析只在校内可见的域名。`dns` 配置可覆盖这些隧道 DNS。 +域名先用公共 DNS 和系统 DNS 解析。没有可用 IPv4 结果时,再通过 VPN 查询服务端下发的校内 DNS,以解析只在校内可见的域名。版本 2 的 `dns.servers` 可覆盖这些隧道 DNS;`dns.strategy = "controller"` 只走控制器 DNS。 DNS 查询先用 UDP,失败或回复被截断时改用 TCP;持续失败的服务器会暂时跳过并改用备用服务器,恢复后自动重新使用。具体超时和冷却规则见 [`docs/TECHNICAL.md`](docs/TECHNICAL.md) §12.5。 diff --git a/auth/auth.go b/auth/auth.go index 3338492..609d883 100644 --- a/auth/auth.go +++ b/auth/auth.go @@ -1,5 +1,3 @@ -// Package auth defines the authentication boundary shared by embedders and the -// controller. It contains no terminal, storage, or school-specific behavior. package auth import ( @@ -9,35 +7,62 @@ import ( "time" ) +type IdentityInfo struct { + Issuer string + Subject string + Kind string +} + +type IdentityProvider interface { + Info(context.Context) (IdentityInfo, error) + Authenticate(context.Context, *http.Client, IdentityRequest) error +} + +type IdentityRequest struct { + AllowInteraction bool +} + +type CredentialStore interface { + Load(context.Context) ([]byte, error) + Save(context.Context, []byte) error +} + +type Method string + +const SMS Method = "sms" + +var ErrInteractionRequired = errors.New("authentication interaction required") var ErrUnsupported = errors.New("unsupported authentication method") -var ErrRequired = errors.New("authentication input required") +var ErrChallengeClosed = errors.New("authentication challenge closed") +var ErrInvalidCredential = errors.New("invalid credential") +var ErrCredentialStore = errors.New("credential store failure") -type UnsupportedError struct{ Method string } +type ChallengeFailure struct { + Code int + Message string +} -func (e *UnsupportedError) Error() string { return ErrUnsupported.Error() } -func (e *UnsupportedError) Unwrap() error { return ErrUnsupported } +type ChallengeInfo struct { + ID uint64 + Method Method + Deadline time.Time + ServerExpiresAt time.Time + LastFailure *ChallengeFailure +} type Challenge struct { - Method string - ExpiresAt time.Time + Info ChallengeInfo + Resend func(context.Context) (ChallengeInfo, error) } -type RequiredError struct{ Challenge Challenge } +type Handler func(context.Context, Challenge) (string, error) -func (e *RequiredError) Error() string { return ErrRequired.Error() } -func (e *RequiredError) Unwrap() error { return ErrRequired } +type UnsupportedError struct{ Method string } -// Handler waits for user input using ctx. The caller owns how the prompt is -// displayed; the SDK never includes the submitted answer in an event or log. -type Handler func(context.Context, Challenge) (string, error) +func (e *UnsupportedError) Error() string { return ErrUnsupported.Error() } +func (e *UnsupportedError) Unwrap() error { return ErrUnsupported } -type ControllerRequest struct { - URL, DeviceID, Platform, ClientType, LoginDomain string - // CSRFToken comes from the initial controller authConfig response. - CSRFToken string -} +type RequiredError struct{ Challenge Challenge } -// ControllerLogin replaces the built-in identity-to-CAS authentication chain. -// On success it leaves the authenticated controller cookies in http.Client.Jar. -// The SDK checks onlineInfo and fetches policy before accepting the session. -type ControllerLogin func(context.Context, *http.Client, ControllerRequest) error +func (e *RequiredError) Error() string { return ErrInteractionRequired.Error() } +func (e *RequiredError) Unwrap() error { return ErrInteractionRequired } diff --git a/auth/passkey.go b/auth/passkey.go new file mode 100644 index 0000000..0c9d366 --- /dev/null +++ b/auth/passkey.go @@ -0,0 +1,77 @@ +package auth + +import ( + "context" + "errors" + "github.com/ShanghaitechGeekPie/geektrust/internal/idsauth" + "net/http" +) + +type Passkey struct { + store CredentialStore + gate chan struct{} +} + +func NewPasskey(s CredentialStore) (*Passkey, error) { + if s == nil { + return nil, ErrCredentialStore + } + return &Passkey{store: s, gate: make(chan struct{}, 1)}, nil +} +func (p *Passkey) Info(ctx context.Context) (IdentityInfo, error) { + b, e := p.store.Load(ctx) + if e != nil { + return IdentityInfo{}, storeError(e) + } + return InspectPasskey(b) +} +func InspectPasskey(b []byte) (IdentityInfo, error) { + k, e := idsauth.ParseKeystore(b, nil) + if e != nil { + return IdentityInfo{}, ErrInvalidCredential + } + return IdentityInfo{Issuer: k.BaseURL(), Subject: k.Username(), Kind: k.Kind()}, nil +} +func (p *Passkey) Authenticate(ctx context.Context, h *http.Client, _ IdentityRequest) error { + select { + case p.gate <- struct{}{}: + defer func() { <-p.gate }() + case <-ctx.Done(): + return ctx.Err() + } + if locker, ok := p.store.(interface { + Lock(context.Context) (func(), error) + }); ok { + unlock, e := locker.Lock(ctx) + if e != nil { + return storeError(e) + } + defer unlock() + } + if e := ctx.Err(); e != nil { + return e + } + b, e := p.store.Load(ctx) + if e != nil { + return storeError(e) + } + k, e := idsauth.ParseKeystore(b, func(b []byte) error { + if e := p.store.Save(ctx, b); e != nil { + return storeError(e) + } + return nil + }) + if e != nil { + return ErrInvalidCredential + } + return idsauth.NewClient(k, h).Login(ctx) +} +func storeError(e error) error { + if errors.Is(e, context.Canceled) { + return errors.Join(ErrCredentialStore, context.Canceled) + } + if errors.Is(e, context.DeadlineExceeded) { + return errors.Join(ErrCredentialStore, context.DeadlineExceeded) + } + return ErrCredentialStore +} diff --git a/client/README.md b/client/README.md index f85a840..c2086cd 100644 --- a/client/README.md +++ b/client/README.md @@ -1,39 +1,37 @@ # client -`client` 封装认证、会话、资源解析和 TCP/UDP 连接,供其他 Go 项目直接引用。 -它不启动代理监听器,也不创建 TUN 或修改系统路由、DNS。 +`client` 提供可嵌入的 aTrust 会话、连接、解析和状态接口。CLI、Web 和 SDK 共用一个内部运行核心。SDK 不创建 TUN、代理监听器或文件目录,不修改系统路由、DNS 或 ACL。 ```go -import "github.com/ShanghaitechGeekPie/geektrust/client" +import ( + "github.com/ShanghaitechGeekPie/geektrust/auth" + "github.com/ShanghaitechGeekPie/geektrust/client" +) +identity, err := auth.NewPasskey(credentials) +if err != nil { return err } c, err := client.New(client.Options{ ControllerURL: controllerURL, - DeviceID: deviceID, - Authenticator: &client.PasskeyAuthenticator{Store: credentials}, - SessionStore: sessions, + DeviceID: deviceID, + Auth: client.AuthOptions{Identity: identity, OnChallenge: prompt}, + SessionStore: sessions, }) if err != nil { return err } defer c.Close() - if _, err := c.Connect(ctx); err != nil { return err } conn, err := c.DialContext(ctx, "tcp", address) if err != nil { return err } defer conn.Close() ``` -- `ControllerURL` 必须是 HTTPS origin(不带路径、查询参数)。`DeviceID` 是持久保存的 32 位大写十六进制标识,可用 `NewDeviceID` 生成。 -- `ClientMode` 默认为 false,即 browser 模式;设为 true 后,首次短信验证成功时会尝试绑定授信终端。 -- `BlobStore` 收到的是凭据或会话的明文字节,调用方负责保密、原子写入和持久化。同一 passkey 使用同一认证器串行更新计数器;保存失败不会提交断言。 -- 认证遵循调用方的 context,允许等待短信输入;网络连接和解析设有超时。连接建立后,用 `SetDeadline` 控制读写。`Close` 会取消操作并关闭自有连接。 -- TCP 优先遵循服务端 L3 偏好,否则先尝试流式 TCP;仅显式设置 `Compatibility.TCPToL3Fallback` 后,网关明确不支持流式命令或在建立阶段提前关闭时才可退回 L3,明确的目标拒绝和取消不会触发回退。 -- 所有控制器均默认严格模式,不按域名推断兼容行为。`Options.Compatibility` 使用公开的 `deployment.Compatibility`,与 TOML `[compatibility]` 字段一一对应;可分别配置应用 ID、缺失网关地址、TLS 域名、缺失网关组和 TCP→L3 回退。网关列表只筛选已分配线路,不覆盖非空的网关组。删除或关闭选项后,新客户端立即采用严格行为,缓存会话不会恢复旧的兜底地址。 -- `LoginDomain` 显式选择 CAS 域;默认从控制器发现。`ControllerLogin` 可替换整个控制器登录流程,通过共享 HTTP CookieJar 建立会话,SDK 随后检查在线状态和资源。`ChallengeHandler` 接收带到期时间的短信验证请求;未提供交互处理器返回 `auth.ErrRequired`,未知认证方式返回 `auth.ErrUnsupported`。 -- 默认 TLS 验证 CA。`GatewayTrustStore` 是显式启用的私有证书 TOFU 兜底,正常 CA 验证通过时不强制检查已有 pin;调用方负责持久保存 pin。 -- UDP 保留数据报边界,payload 上限为 1372 字节。`ExchangePacket` 仅支持未分片 IPv4 ICMP Echo;实际可用性取决于控制器授权和网关支持。IPv6 目标未实现。 - -`Info.Implemented` 仅表示库已经实现的协议能力;`Resources` 表示控制器下发的授权范围, -`OpenTransport` 返回已建立线路和实际分配的 IPv4 地址。它们均不保证任意目标可达。 -`Compatibility.ProcessIdentity` 可以覆盖流式 TCP 和 L3 的进程名、平台和路径,并统一重新计算指纹。 -未配置时保留各自已实现的协议元数据;这些值与宿主操作系统无关,不代表平台连接验证结果。 - -`Options.CheckTarget` 可在解析出真实 IPv4 地址后、打开目标传输前执行调用方的路由限制;同样适用于 ICMP。回调必须支持并发调用,只能进一步限制访问,不能扩大控制器授权范围。库本身不决定系统路由。 +`credentials` 实现 `auth.CredentialStore`;`sessions` 实现按 `client.SessionScope` 分开的 `Load`、`Save`、`Delete`。Save 必须原子且持久。SDK 会再次核对缓存归属,拒绝将旧 Cookie 发给另一控制器或身份。设备 ID 由宿主持久保存。 + +`New` 只检查和复制设置。`Connect`、`Authenticate` 可以发起短信交互;后台、数据连接和解析遇到短信要求时返回 `auth.ErrInteractionRequired`。挑战区分本地 `Deadline` 和服务端 `ServerExpiresAt`,提供限生命周期的 `Resend`。不提供完整控制器登录替换钩子。 + +部署默认为 `deployment.Auto`。上科大的已验证 TLS 身份和缺字段补充由内部适配提供;未知控制器采用 `Generic`。`Fallbacks=nil` 使用部署默认,`&deployment.Fallbacks{}` 关闭全部兜底。TLS 设置放在 `Network.GatewayTLS`,正常 CA 验证成功时不强制检查 pin;未知 CA 的兜底需要原子的 `CheckOrEnroll`,并继续验证证书身份和有效期。 + +SDK 默认仅使用控制器 DNS;额外来源由 `DNS.FallbackLookup` 明确提供。CLI 的 `auto` 顺序在命令转换层保留。`Network.AllowedGateways=nil` 不额外限制,显式空列表拒绝全部线路。`CheckTarget` 收到地址、协议、端口和代;`DNSQueryTarget` 区分基础 DNS 查询,只能收紧访问权限。 + +`Status` 返回安全快照;`Subscribe(ctx)` 为每个订阅者提供独立有界队列,慢订阅者不会阻塞连接。`ImplementedCapabilities()` 表示 SDK 实现范围,不代表资源授权或目标连通。`ExchangeICMPEcho` 仅支持未分片 IPv4 Echo,UDP 保留数据报边界,payload 上限为 1372 字节。IPv6 目标未实现。 + +`Close` 取消并关闭自有对象,`Shutdown(ctx)` 等待自有任务,支持超时。宿主提供的 transport、身份和存储对象由宿主管理。旧会话的连接不跨代重放数据,宿主负责重连。 diff --git a/client/client.go b/client/client.go index 840aab0..d4efaa5 100644 --- a/client/client.go +++ b/client/client.go @@ -1,512 +1,126 @@ -// Package client embeds aTrust authentication and transport without starting -// listeners, changing system networking, or depending on a configuration file. +// Package client is the public facade for the shared aTrust runtime. package client import ( "context" - "crypto/tls" - "encoding/json" - "errors" - "io" - "log/slog" + "github.com/ShanghaitechGeekPie/geektrust/internal/runtime" "net" - "net/http" - "net/netip" - "net/url" - "strconv" - "strings" - "sync" - "time" - "unicode" - - "github.com/ShanghaitechGeekPie/geektrust/auth" - "github.com/ShanghaitechGeekPie/geektrust/deployment" - "github.com/ShanghaitechGeekPie/geektrust/internal/config" - "github.com/ShanghaitechGeekPie/geektrust/internal/idsauth" - "github.com/ShanghaitechGeekPie/geektrust/internal/l3" - "github.com/ShanghaitechGeekPie/geektrust/internal/resolver" - "github.com/ShanghaitechGeekPie/geektrust/internal/session" - "github.com/ShanghaitechGeekPie/geektrust/internal/tunnel" ) -// BlobStore is scoped to a single identity/deployment by the embedding application. -// Save must be atomic and durable. Implementations must protect the secret bytes. -type BlobStore interface { - Load(context.Context) ([]byte, error) - Save(context.Context, []byte) error -} - -// GatewayTrustStore persists SHA-256 SPKI pins for private-CA gateways. -// An empty LoadPin result enrolls the first observed public key. -type GatewayTrustStore interface { - LoadPin(context.Context, string) ([]byte, error) - SavePin(context.Context, string, []byte) error -} -type Authenticator interface { - Authenticate(context.Context, *http.Client) (string, error) -} -type AuthenticatorFunc func(context.Context, *http.Client) (string, error) - -func (f AuthenticatorFunc) Authenticate(ctx context.Context, h *http.Client) (string, error) { - return f(ctx, h) -} - -// PasskeyAuthenticator supports ECNU and ShanghaiTech binary keystores. -// Use one instance/store owner per credential to serialize signature counters. -type PasskeyAuthenticator struct { - Store BlobStore - once sync.Once - gate chan struct{} -} - -func (p *PasskeyAuthenticator) Authenticate(ctx context.Context, h *http.Client) (string, error) { - p.once.Do(func() { p.gate = make(chan struct{}, 1) }) - select { - case p.gate <- struct{}{}: - defer func() { <-p.gate }() - case <-ctx.Done(): - return "", ctx.Err() - } - if err := ctx.Err(); err != nil { - return "", err - } - if p.Store == nil { - return "", errors.New("credential store required") - } - b, err := p.Store.Load(ctx) - if err != nil { - return "", errors.New("cannot load credential") - } - k, err := idsauth.ParseKeystore(b, func(b []byte) error { return p.Store.Save(ctx, b) }) - if err != nil { - return "", errors.New("invalid passkey credential") - } - if err = idsauth.NewClient(k, h).Login(ctx); err != nil { - return "", err - } - return k.Username(), nil -} - -type PasskeyInfo struct { - Kind string - Username string - Origin string -} - -// InspectPasskey validates a credential and exposes only non-secret metadata. -func InspectPasskey(b []byte) (PasskeyInfo, error) { - k, err := idsauth.ParseKeystore(b, nil) - if err != nil { - return PasskeyInfo{}, errors.New("invalid passkey credential") - } - return PasskeyInfo{Kind: k.Kind(), Username: k.Username(), Origin: k.BaseURL()}, nil -} - -// ValidatePasskey validates an imported credential without authenticating it. -func ValidatePasskey(b []byte) error { - _, err := InspectPasskey(b) - return err -} - -type Options struct { - // CheckTarget may reject a resolved IPv4 destination before transport opens. - // It is called concurrently and cannot grant access outside controller policy. - CheckTarget func(netip.Addr) error - Compatibility deployment.Compatibility - Gateways []string - DNS []string - ControllerURL string - DeviceID string - Platform string - LoginDomain string - ClientMode bool - Authenticator Authenticator - ControllerLogin auth.ControllerLogin - ChallengeHandler auth.Handler - SessionStore BlobStore - Transport http.RoundTripper - DialContext func(context.Context, string, string) (net.Conn, error) - DisableSystemResolver bool - GatewayTLSConfig *tls.Config - GatewayTrustStore GatewayTrustStore - Logger *slog.Logger -} - -type Capabilities struct{ IPv4TCP, IPv4UDP, IPv4ICMP, IPv6Targets, IPv6Gateway bool } -type Resource struct { - Address, Protocol, ApplicationID, GatewayGroup string - PortMin, PortMax int -} -type Info struct { - Gateways, DNS []string - Resources []Resource - // Implemented describes library support, not negotiated or authorized access. - Implemented Capabilities -} -type TransportInfo struct { - Gateway string - VirtualIPv4 string -} -type EventKind string +type Client struct{ core *runtime.Runtime } + +func New(o Options) (*Client, error) { + r, e := runtime.New(o) + if e != nil { + return nil, runtime.ConfigError(e) + } + return &Client{core: r}, nil +} +func NewDeviceID() (string, error) { return runtime.NewDeviceID() } +func ImplementedCapabilities() Capabilities { return runtime.ImplementedCapabilities() } + +type Options = runtime.Options +type AuthOptions = runtime.AuthOptions +type SessionMode = runtime.SessionMode +type NetworkOptions = runtime.NetworkOptions +type GatewayTLSOptions = runtime.GatewayTLSOptions +type GatewayTrustMode = runtime.GatewayTrustMode +type GatewayIdentity = runtime.GatewayIdentity +type GatewayPinStore = runtime.GatewayPinStore +type DNSOptions = runtime.DNSOptions +type Target = runtime.Target +type TargetPurpose = runtime.TargetPurpose +type SessionScope = runtime.SessionScope +type SessionStore = runtime.SessionStore +type Capabilities = runtime.Capabilities +type Resource = runtime.Resource +type SessionInfo = runtime.SessionInfo +type TransportInfo = runtime.TransportInfo +type Event = runtime.Event +type Status = runtime.Status +type SessionState = runtime.SessionState +type Error = runtime.Error +type ErrorInfo = runtime.ErrorInfo +type ErrorKind = runtime.ErrorKind +type TrustedDevice = runtime.TrustedDevice +type TrustedDeviceList = runtime.TrustedDeviceList const ( - EventAuthenticating EventKind = "authenticating" - EventAuthenticated EventKind = "authenticated" - EventAuthenticationFailed EventKind = "authentication_failed" - EventSessionInvalidated EventKind = "session_invalidated" + BrowserMode = runtime.BrowserMode + DesktopMode = runtime.DesktopMode + VerifyCA = runtime.VerifyCA + VerifyCAOrTOFU = runtime.VerifyCAOrTOFU + ApplicationTarget = runtime.ApplicationTarget + DNSQueryTarget = runtime.DNSQueryTarget + Idle = runtime.Idle + Authenticating = runtime.Authenticating + Ready = runtime.Ready + InteractionRequired = runtime.InteractionRequired + Failed = runtime.Failed + Closed = runtime.Closed + ErrorConfig = runtime.ErrorConfig + ErrorInteractionRequired = runtime.ErrorInteractionRequired + ErrorIdentityChanged = runtime.ErrorIdentityChanged + ErrorAuthenticationRejected = runtime.ErrorAuthenticationRejected + ErrorControllerDenied = runtime.ErrorControllerDenied + ErrorCallerDenied = runtime.ErrorCallerDenied + ErrorTLS = runtime.ErrorTLS + ErrorDNS = runtime.ErrorDNS + ErrorNetwork = runtime.ErrorNetwork + ErrorUnsupported = runtime.ErrorUnsupported + ErrorSessionReplaced = runtime.ErrorSessionReplaced + ErrorDatagramTooLarge = runtime.ErrorDatagramTooLarge + ErrorStorage = runtime.ErrorStorage + ErrorClosed = runtime.ErrorClosed ) -type Event struct { - Kind EventKind - Time time.Time -} - -var ErrClosed = errors.New("aTrust client closed") -var ErrDatagramTooLarge = errors.New("UDP datagram exceeds tunnel MTU") -var ErrDenied = errors.New("target is not authorized by controller policy") - -type Client struct { - checkTarget func(netip.Addr) error - provider *session.Provider - manager *tunnel.Manager - dialer *l3.Dialer - resolver *resolver.Resolver - ctx context.Context - cancel context.CancelFunc - mu sync.Mutex - closed bool - conns map[*ownedConn]struct{} - transport *http.Transport - events chan Event -} - -func New(opts Options) (*Client, error) { - u, err := url.Parse(opts.ControllerURL) - if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") { - return nil, errors.New("controller must be an HTTPS origin") - } - if len(opts.DeviceID) != 32 || strings.Trim(opts.DeviceID, "0123456789ABCDEF") != "" { - return nil, errors.New("persistent 32-character uppercase hexadecimal device ID required") - } - if opts.Authenticator == nil && opts.ControllerLogin == nil { - return nil, errors.New("authenticator required") - } - if opts.Platform == "" { - opts.Platform = "Mac" - } - if len(opts.Platform) > 64 || strings.IndexFunc(opts.Platform, unicode.IsControl) >= 0 { - return nil, errors.New("platform must be at most 64 bytes without control characters") - } - if opts.Logger == nil { - opts.Logger = slog.New(slog.NewTextHandler(io.Discard, nil)) - } - mode := "browser" - if opts.ClientMode { - mode = "client" - } - cfg := &config.Config{BaseURL: strings.TrimRight(opts.ControllerURL, "/"), DeviceID: opts.DeviceID, Platform: opts.Platform, LoginDomain: opts.LoginDomain, ClientType: mode, Compatibility: opts.Compatibility.Clone(), Gateways: append([]string(nil), opts.Gateways...), DNS: append([]string(nil), opts.DNS...)} - if err := cfg.Compatibility.Validate(); err != nil { - return nil, err - } - p := session.NewProvider(cfg, opts.Logger, nil) - if opts.Authenticator != nil { - p.Authenticate = opts.Authenticator.Authenticate - } - p.ControllerLogin = opts.ControllerLogin - p.ChallengeHandler = opts.ChallengeHandler - p.Transport = opts.Transport - var ownedTransport *http.Transport - if p.Transport == nil { - ownedTransport = http.DefaultTransport.(*http.Transport).Clone() - if opts.DialContext != nil { - ownedTransport.DialContext = opts.DialContext - } - p.Transport = ownedTransport - } - p.SetStore(&stateStore{store: opts.SessionStore}) - m := tunnel.NewManager(p, opts.Logger) - m.MaxAttempts = 3 - m.DialContext = opts.DialContext - m.GatewayTLSConfig = opts.GatewayTLSConfig - if name := cfg.GatewayServerName(); name != "" { - if m.GatewayTLSConfig == nil { - m.GatewayTLSConfig = &tls.Config{ServerName: name} - } else if m.GatewayTLSConfig.ServerName == "" { - m.GatewayTLSConfig = m.GatewayTLSConfig.Clone() - m.GatewayTLSConfig.ServerName = name - } - } - m.GatewayTrustStore = opts.GatewayTrustStore - d := &l3.Dialer{Manager: m, Provider: p, Logger: opts.Logger} - ctx, cancel := context.WithCancel(context.Background()) - c := &Client{checkTarget: opts.CheckTarget, transport: ownedTransport, provider: p, manager: m, dialer: d, resolver: resolver.NewWithDialerOptions(p, d, opts.DialContext, opts.DisableSystemResolver), ctx: ctx, cancel: cancel, conns: make(map[*ownedConn]struct{}), events: make(chan Event, 16)} - p.AddObserver(clientObserver{c}) - go p.CheckLoop(ctx, 5*time.Minute) - return c, nil -} - -func NewDeviceID() (string, error) { return config.GenerateDeviceID() } - -// Authenticate forces a fresh login. Concurrent requests share the provider's -// refresh; the embedding application remains responsible for connection retry. -func (c *Client) Authenticate(parent context.Context) (Info, error) { - if c.isClosed() { - return Info{}, ErrClosed - } - ctx, done := c.withLifetime(parent) - defer done() - if _, err := c.provider.ForceLogin(ctx); err != nil { - return Info{}, err - } - return c.Connect(ctx) -} -func (c *Client) withLifetime(parent context.Context) (context.Context, func()) { - ctx, cancel := context.WithCancel(parent) - stop := context.AfterFunc(c.ctx, cancel) - return ctx, func() { stop(); cancel() } -} +var ( + ErrClosed = runtime.ErrClosed + ErrDatagramTooLarge = runtime.ErrDatagramTooLarge + ErrDenied = runtime.ErrDenied +) -func (c *Client) operation(parent context.Context) (context.Context, func()) { - ctx, release := c.withLifetime(parent) - ctx, cancel := context.WithTimeout(ctx, 45*time.Second) - return ctx, func() { cancel(); release() } +func (c *Client) Connect(ctx context.Context) (SessionInfo, error) { + v, e := c.core.Connect(ctx) + return v, runtime.PublicError("connect", e) } - -func (c *Client) Connect(parent context.Context) (Info, error) { - if c.isClosed() { - return Info{}, ErrClosed - } - ctx, done := c.withLifetime(parent) - defer done() - cred, err := c.provider.Credential(ctx) - if err != nil { - return Info{}, err - } - c.mu.Lock() - defer c.mu.Unlock() - if c.closed { - return Info{}, ErrClosed - } - info := Info{Gateways: append([]string(nil), cred.Gateways...), DNS: append([]string(nil), cred.DNS...), Implemented: Capabilities{IPv4TCP: true, IPv4UDP: true, IPv4ICMP: true, IPv6Gateway: true}} - for _, r := range cred.Policy.IPRules { - address := "" - switch { - case r.IP != nil: - address = r.IP.String() - case r.Net != nil: - address = r.Net.String() - case r.IPMin != nil: - address = r.IPMin.String() + "-" + r.IPMax.String() - } - info.Resources = append(info.Resources, Resource{Address: address, Protocol: r.Proto, ApplicationID: r.AppID, GatewayGroup: cred.Policy.AppNodeGroups[r.AppID], PortMin: r.Port.Min, PortMax: r.Port.Max}) - } - for _, r := range cred.Policy.DomainRules { - info.Resources = append(info.Resources, Resource{Address: r.Domain, Protocol: r.Proto, ApplicationID: r.AppID, GatewayGroup: cred.Policy.AppNodeGroups[r.AppID], PortMin: r.Port.Min, PortMax: r.Port.Max}) - } - for _, r := range cred.Policy.SuffixRules { - info.Resources = append(info.Resources, Resource{Address: "*" + r.Suffix, Protocol: r.Proto, ApplicationID: r.AppID, GatewayGroup: cred.Policy.AppNodeGroups[r.AppID], PortMin: r.Port.Min, PortMax: r.Port.Max}) - } - return info, nil +func (c *Client) Authenticate(ctx context.Context) (SessionInfo, error) { + v, e := c.core.Authenticate(ctx) + return v, runtime.PublicError("authenticate", e) } - -// OpenTransport authenticates an L3 gateway without creating a system TUN or -// requesting access to any particular resource. Embedders can call it before -// advertising a connected packet-facing session. -func (c *Client) OpenTransport(parent context.Context) (TransportInfo, error) { - if c.isClosed() { - return TransportInfo{}, ErrClosed - } - ctx, done := c.operation(parent) - defer done() - t, err := c.manager.Tunnel(ctx) - if err != nil { - return TransportInfo{}, err - } - ip := t.VIP().To4() - if ip == nil { - return TransportInfo{}, errors.New("gateway did not assign an IPv4 virtual address") - } - return TransportInfo{Gateway: t.Addr(), VirtualIPv4: ip.String()}, nil +func (c *Client) OpenTransport(ctx context.Context) (TransportInfo, error) { + v, e := c.core.OpenTransport(ctx) + return v, runtime.PublicError("open_transport", e) } - -func (c *Client) DialContext(parent context.Context, network, address string) (net.Conn, error) { - if network != "tcp" && network != "tcp4" && network != "udp" && network != "udp4" { - return nil, errors.New("unsupported target network") - } - protocol := strings.TrimSuffix(network, "4") - host, p, err := net.SplitHostPort(address) - if err != nil { - return nil, errors.New("target must include port") - } - port, err := strconv.Atoi(p) - if err != nil || port < 1 || port > 65535 { - return nil, errors.New("invalid target port") - } - c.mu.Lock() - closed := c.closed - c.mu.Unlock() - if closed { - return nil, ErrClosed - } - ctx, done := c.operation(parent) - defer done() - resolve := c.resolver.Resolve - if protocol == "udp" { - resolve = c.resolver.ResolveUDP - } - target, err := resolve(ctx, host, port) - if err != nil { - return nil, err - } - if target.AppID == "" { - return nil, ErrDenied - } - if c.checkTarget != nil { - ip, err := netip.ParseAddr(target.IP) - if err != nil { - return nil, err - } - if err := c.checkTarget(ip.Unmap()); err != nil { - return nil, err - } - } - var conn net.Conn - if protocol == "tcp" { - conn, err = c.dialer.Dial(ctx, target.IP, port, target.AppID, target.Domain) - } else { - conn, err = c.dialer.DialUDP(ctx, target.IP, port, target.AppID, target.Domain) - } - if err != nil { - return nil, err - } - c.mu.Lock() - defer c.mu.Unlock() - if c.closed { - conn.Close() - return nil, ErrClosed - } - owned := &ownedConn{Conn: conn, owner: c, datagram: protocol == "udp"} - c.conns[owned] = struct{}{} - return owned, nil +func (c *Client) DialContext(ctx context.Context, n, a string) (net.Conn, error) { + v, e := c.core.DialContext(ctx, n, a) + return v, runtime.PublicError("dial", e) } - -func (c *Client) isClosed() bool { - c.mu.Lock() - defer c.mu.Unlock() - return c.closed +func (c *Client) LookupContextHost(ctx context.Context, h string) ([]string, error) { + v, e := c.core.LookupContextHost(ctx, h) + return v, runtime.PublicError("lookup", e) } - -func (c *Client) LookupContextHost(parent context.Context, host string) ([]string, error) { - if c.isClosed() { - return nil, ErrClosed - } - ctx, done := c.operation(parent) - defer done() - return c.resolver.LookupHost(ctx, host) +func (c *Client) ExchangeICMPEcho(ctx context.Context, p []byte) ([]byte, error) { + v, e := c.core.ExchangeICMPEcho(ctx, p) + return v, runtime.PublicError("icmp", e) } -func (c *Client) Events() <-chan Event { return c.events } -func (c *Client) Close() error { - c.mu.Lock() - if c.closed { - c.mu.Unlock() - return nil - } - c.closed = true - c.cancel() - conns := make([]*ownedConn, 0, len(c.conns)) - for conn := range c.conns { - conns = append(conns, conn) - } - close(c.events) - c.mu.Unlock() - for _, conn := range conns { - conn.Close() - } - c.provider.CloseObservers() - c.manager.Close() - if c.transport != nil { - c.transport.CloseIdleConnections() - } - return nil +func (c *Client) ForgetSession(ctx context.Context) error { + return runtime.PublicError("forget_session", c.core.ForgetSession(ctx)) } - -type ownedConn struct { - net.Conn - datagram bool - owner *Client - once sync.Once - err error +func (c *Client) Status() Status { return c.core.Status() } +func (c *Client) Subscribe(ctx context.Context) <-chan Event { return c.core.Subscribe(ctx) } +func (c *Client) Close() error { return c.core.Close() } +func (c *Client) Shutdown(ctx context.Context) error { return c.core.Shutdown(ctx) } +func (c *Client) TrustedDevices(ctx context.Context) (TrustedDeviceList, error) { + v, e := c.core.TrustedDevices(ctx) + return v, runtime.PublicError("trusted_devices", e) } - -func (c *ownedConn) Write(b []byte) (int, error) { - if c.datagram && len(b) > 1372 { - return 0, ErrDatagramTooLarge - } - return c.Conn.Write(b) -} -func (c *ownedConn) Close() error { - c.once.Do(func() { c.err = c.Conn.Close(); c.owner.mu.Lock(); delete(c.owner.conns, c); c.owner.mu.Unlock() }) - return c.err +func (c *Client) TrustCurrentDevice(ctx context.Context) error { + return runtime.PublicError("trust_device", c.core.TrustCurrentDevice(ctx)) } -func (c *ownedConn) CloseWrite() error { - if w, ok := c.Conn.(interface{ CloseWrite() error }); ok { - return w.CloseWrite() - } - return errors.New("half-close unavailable") +func (c *Client) UntrustDevices(ctx context.Context, ids []string) error { + return runtime.PublicError("untrust_devices", c.core.UntrustDevices(ctx, ids)) } - -type stateStore struct{ store BlobStore } - -func (s *stateStore) Load(parent context.Context) (*session.State, error) { - if s.store == nil { - return nil, nil - } - ctx, cancel := context.WithTimeout(parent, 5*time.Second) - defer cancel() - b, err := s.store.Load(ctx) - if err != nil || len(b) == 0 { - return nil, err - } - var st session.State - if json.Unmarshal(b, &st) != nil { - return nil, errors.New("invalid stored session") - } - return &st, nil -} -func (s *stateStore) Save(parent context.Context, st *session.State) error { - if s.store == nil { - return nil - } - b, err := json.Marshal(st) - if err != nil { - return err - } - ctx, cancel := context.WithTimeout(parent, 5*time.Second) - defer cancel() - return s.store.Save(ctx, b) -} - -type clientObserver struct{ client *Client } - -func (o clientObserver) OnSessionEvent(event session.Event) { - kind := map[session.EventKind]EventKind{ - session.EventLoginStart: EventAuthenticating, - session.EventLoginSuccess: EventAuthenticated, - session.EventRestoreOK: EventAuthenticated, - session.EventLoginFailed: EventAuthenticationFailed, - session.EventInvalidated: EventSessionInvalidated, - }[event.Kind] - if kind == "" { - return - } - c := o.client - c.mu.Lock() - defer c.mu.Unlock() - if c.closed { - return - } - select { - case c.events <- Event{Kind: kind, Time: event.Time}: - default: - } +func (c *Client) LogoutDevice(ctx context.Context, id string) error { + return runtime.PublicError("logout_device", c.core.LogoutDevice(ctx, id)) } diff --git a/client/consumer_test.go b/client/consumer_test.go new file mode 100644 index 0000000..357f0f1 --- /dev/null +++ b/client/consumer_test.go @@ -0,0 +1,31 @@ +package client_test + +import ( + "context" + "github.com/ShanghaitechGeekPie/geektrust/auth" + "github.com/ShanghaitechGeekPie/geektrust/client" + "net/http" + "testing" +) + +type identity struct{} + +func (identity) Info(context.Context) (auth.IdentityInfo, error) { + return auth.IdentityInfo{Issuer: "test", Subject: "test", Kind: "test"}, nil +} +func (identity) Authenticate(context.Context, *http.Client, auth.IdentityRequest) error { return nil } +func TestPublicClientConstructionAndClose(t *testing.T) { + c, e := client.New(client.Options{ControllerURL: "https://controller.example", DeviceID: "0123456789ABCDEF0123456789ABCDEF", Auth: client.AuthOptions{Identity: identity{}}}) + if e != nil { + t.Fatal(e) + } + if c.Status().State != client.Idle { + t.Fatal("constructor started authentication") + } + if e = c.Shutdown(context.Background()); e != nil { + t.Fatal(e) + } + if client.ImplementedCapabilities().IPv6Targets { + t.Fatal("unsupported IPv6 targets advertised") + } +} diff --git a/client/packet.go b/client/packet.go deleted file mode 100644 index 8367b7c..0000000 --- a/client/packet.go +++ /dev/null @@ -1,32 +0,0 @@ -package client - -import ( - "context" - "errors" - "net/netip" -) - -// PacketTransport is optional and owns no system interfaces. ExchangePacket -// returns a real response or an error; it never synthesizes Echo success. -// Currently only authorized, unfragmented IPv4 ICMP Echo is supported. -type PacketTransport interface { - ExchangePacket(context.Context, []byte) ([]byte, error) -} - -func (c *Client) ExchangePacket(parent context.Context, packet []byte) ([]byte, error) { - if c.isClosed() { - return nil, ErrClosed - } - if c.checkTarget != nil { - if len(packet) < 20 || packet[0]>>4 != 4 { - return nil, errors.New("invalid IPv4 packet") - } - ip := netip.AddrFrom4([4]byte(packet[16:20])) - if err := c.checkTarget(ip); err != nil { - return nil, err - } - } - ctx, done := c.operation(parent) - defer done() - return c.dialer.ExchangePacket(ctx, packet) -} diff --git a/cmd/geektrust/config_cmd.go b/cmd/geektrust/config_cmd.go new file mode 100644 index 0000000..829458b --- /dev/null +++ b/cmd/geektrust/config_cmd.go @@ -0,0 +1,73 @@ +package main + +import ( + "errors" + "flag" + "fmt" + "github.com/ShanghaitechGeekPie/geektrust/internal/config" + "github.com/ShanghaitechGeekPie/geektrust/internal/storage" + "os" +) + +func cmdConfig(path string, args []string) error { + if len(args) == 0 { + return errors.New("usage: geektrust config check|show|migrate") + } + switch args[0] { + case "check", "show": + if len(args) != 1 { + return errors.New("unexpected configuration arguments") + } + c, e := config.Load(path) + if e != nil { + return e + } + if args[0] == "check" { + if e = c.ValidateListeners(); e != nil { + return e + } + for _, key := range c.UnknownFields { + fmt.Printf("warning: ignored legacy field %s\n", key) + } + fmt.Println("configuration valid") + return nil + } + fmt.Printf("config_version = %d\ncontroller = %q\ndeployment = %q\nauth_mode = %q\ndns_strategy = %q\nkeystore = %q\nstate_file = %q\n", c.Version, c.BaseURL, c.Deployment, c.ClientType, c.DNSStrategy, c.Keystore, c.StateFile) + return nil + case "migrate": + fs := flag.NewFlagSet("config migrate", flag.ContinueOnError) + write := fs.Bool("write", false, "back up and replace configuration after preview") + if e := fs.Parse(args[1:]); e != nil { + return e + } + if fs.NArg() != 0 { + return errors.New("unexpected migration arguments") + } + b, e := config.Migration(path) + if e != nil { + return e + } + if !*write { + fmt.Print(string(b)) + return nil + } + old, e := os.ReadFile(path) + if e != nil { + return e + } + if e = storage.CreateExclusive(path+".v1.bak", old); e != nil { + return fmt.Errorf("create migration backup: %w", e) + } + if e = storage.WriteAtomic(path, b, 0600); e != nil { + return e + } + if _, e = config.Load(path); e != nil { + _ = storage.WriteAtomic(path, old, 0600) + return e + } + fmt.Println("configuration migrated; original retained in " + path + ".v1.bak") + return nil + default: + return errors.New("unknown configuration command") + } +} diff --git a/cmd/geektrust/init_cmd.go b/cmd/geektrust/init_cmd.go index 95a9628..4c74ac5 100644 --- a/cmd/geektrust/init_cmd.go +++ b/cmd/geektrust/init_cmd.go @@ -8,10 +8,9 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "strings" - "golang.org/x/text/unicode/norm" - "github.com/ShanghaitechGeekPie/geektrust/internal/config" "github.com/ShanghaitechGeekPie/geektrust/internal/privatefile" ) @@ -37,9 +36,7 @@ func validateInitPaths(configPath string, cfg *config.Config) (string, error) { if item.path == "" { return "", fmt.Errorf("%s path is required", item.name) } - if containsParentTraversal(item.path) { - return "", fmt.Errorf("%s path must not contain '..'", item.name) - } + var err error lexical[i], err = filepath.Abs(filepath.Clean(item.path)) if err != nil { @@ -65,61 +62,22 @@ func validateInitPaths(configPath string, cfg *config.Config) (string, error) { } } } - for i, item := range paths { - if infos[i] != nil { - if err := validateInitFilePermissions(item.name, lexical[i]); err != nil { - return "", err - } - if err := validateInitFilePermissions(item.name, resolved[i]); err != nil { - return "", err - } - } - if err := validateInitDirectory(item.name, lexical[i]); err != nil { - return "", err - } - if err := validateInitDirectory(item.name, resolved[i]); err != nil { - return "", err - } - } return resolved[0], nil } -func initPathsOverlap(left, right string) bool { - // NFC + EqualFold is deliberately conservative: generated file paths - // must also be distinct on case-insensitive APFS, which treats canonically - // equivalent Unicode filenames as the same entry. - leftParts := strings.Split(filepath.ToSlash(norm.NFC.String(filepath.Clean(left))), "/") - rightParts := strings.Split(filepath.ToSlash(norm.NFC.String(filepath.Clean(right))), "/") - if len(leftParts) > len(rightParts) { - leftParts, rightParts = rightParts, leftParts - } - for i := range leftParts { - if !strings.EqualFold(leftParts[i], rightParts[i]) { - return false - } - } - return true -} - -func containsParentTraversal(path string) bool { - for _, component := range strings.Split(filepath.ToSlash(path), "/") { - if component == ".." { - return true - } - } - return false +func initPathsOverlap(a, b string) bool { + a = filepath.Clean(a) + b = filepath.Clean(b) + if runtime.GOOS == "windows" { + a = strings.ToLower(a) + b = strings.ToLower(b) + } + return a == b || strings.HasPrefix(a, b+string(filepath.Separator)) || strings.HasPrefix(b, a+string(filepath.Separator)) } func validateInitDirectory(name, path string) error { - if err := privatefile.CheckParents(path); err != nil { - return fmt.Errorf("%s %w", name, err) - } - return nil -} - -func validateInitFilePermissions(name, path string) error { - if err := privatefile.CheckFile(path); err != nil { - return fmt.Errorf("%s file %s: %w", name, path, err) + if info, err := os.Stat(filepath.Dir(path)); err == nil && !info.IsDir() { + return fmt.Errorf("%s parent is not a directory", name) } return nil } @@ -241,7 +199,7 @@ func cmdInit(ctx context.Context, configPath string, args []string) error { fs.SetOutput(os.Stderr) keystore := fs.String("keystore", "./ids-passkey.keystore", "passkey keystore path") deviceID := fs.String("device-id", "", "persistent 32-character uppercase hex device ID (generated when omitted)") - stateFile := fs.String("state-file", "./state.enc", "encrypted session state path") + stateFile := fs.String("state-file", "", "encrypted session state path") clientType := fs.String("client-type", "client", "login mode: client (recommended) or browser") bindPasskey := fs.Bool("bind-passkey", false, "run shanghaitech-ids-passkey bind when the keystore is missing") force := fs.Bool("force", false, "replace an existing config file") @@ -284,9 +242,6 @@ func cmdInit(ctx context.Context, configPath string, args []string) error { if !info.Mode().IsRegular() { return fmt.Errorf("keystore %s is not a regular file", prepared.Keystore) } - if err := privatefile.Protect(prepared.Keystore); err != nil { - return fmt.Errorf("secure existing keystore: %w", err) - } keystoreExists = true } else if !errors.Is(err, os.ErrNotExist) { return fmt.Errorf("inspect keystore: %w", err) diff --git a/cmd/geektrust/init_permissions_windows_test.go b/cmd/geektrust/init_permissions_windows_test.go deleted file mode 100644 index 727b938..0000000 --- a/cmd/geektrust/init_permissions_windows_test.go +++ /dev/null @@ -1,164 +0,0 @@ -package main - -import ( - "context" - "fmt" - "os" - "os/exec" - "path/filepath" - "strings" - "testing" - - "golang.org/x/sys/windows" - - "github.com/ShanghaitechGeekPie/geektrust/internal/config" -) - -// Only call this on fixtures created by the test, never user directories. -func setTestWindowsACL(t *testing.T, path, extra string) { - t.Helper() - user, err := windows.GetCurrentProcessToken().GetTokenUser() - if err != nil { - t.Fatal(err) - } - sd, err := windows.SecurityDescriptorFromString(fmt.Sprintf("D:P(A;OICI;FA;;;%s)(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)%s", user.User.Sid.String(), extra)) - if err != nil { - t.Fatal(err) - } - dacl, _, err := sd.DACL() - if err != nil { - t.Fatal(err) - } - pathPtr, err := windows.UTF16PtrFromString(path) - if err != nil { - t.Fatal(err) - } - handle, err := windows.CreateFile(pathPtr, windows.WRITE_DAC|windows.READ_CONTROL, - windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, nil, windows.OPEN_EXISTING, - windows.FILE_FLAG_BACKUP_SEMANTICS|windows.FILE_FLAG_OPEN_REPARSE_POINT, 0) - if err != nil { - t.Fatalf("open test ACL %s: %v", path, err) - } - defer windows.CloseHandle(handle) - if err := windows.SetSecurityInfo(handle, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, nil, nil, dacl, nil); err != nil { - t.Fatalf("set test ACL %s: %v", path, err) - } -} - -func TestWindowsInitACLIntegration(t *testing.T) { - t.Logf("process elevated=%v", windows.GetCurrentProcessToken().IsElevated()) - root := t.TempDir() - t.Logf("test root=%s", root) - setTestWindowsACL(t, root, "") - t.Run("normal private directory", func(t *testing.T) { - path := filepath.Join(root, "normal", "config.toml") - err := cmdInit(context.Background(), path, []string{"--keystore", filepath.Join(root, "key"), "--state-file", filepath.Join(root, "state")}) - if err != nil { - t.Fatal(err) - } - if err := validateInitFilePermissions("config", path); err != nil { - t.Fatal(err) - } - }) - for _, tt := range []struct{ name, ace string }{ - {"world writable", "(A;;FW;;;WD)"}, - {"delete child", "(A;;0x40;;;WD)"}, - {"inherit only read", "(A;OIIO;FR;;;BU)"}, - } { - t.Run(tt.name, func(t *testing.T) { - dir := filepath.Join(root, strings.ReplaceAll(tt.name, " ", "-")) - if err := os.Mkdir(dir, 0700); err != nil { - t.Fatal(err) - } - setTestWindowsACL(t, dir, tt.ace) - path := filepath.Join(dir, "config.toml") - if err := cmdInit(context.Background(), path, []string{"--keystore", filepath.Join(root, "key"), "--state-file", filepath.Join(root, "state")}); err == nil { - t.Fatal("unsafe directory accepted") - } - if _, err := os.Stat(path); !os.IsNotExist(err) { - t.Fatalf("config created before rejecting unsafe ACL: %v", err) - } - }) - } - t.Run("private child under replaceable ancestor", func(t *testing.T) { - parent := filepath.Join(root, "replaceable") - child := filepath.Join(parent, "private") - if err := os.MkdirAll(child, 0700); err != nil { - t.Fatal(err) - } - setTestWindowsACL(t, parent, "(A;;0x40;;;WD)") - setTestWindowsACL(t, child, "") - if err := validateInitDirectory("config", filepath.Join(child, "config.toml")); err == nil { - t.Fatal("replaceable ancestor accepted") - } - }) - t.Run("protected child under sibling creation ancestor", func(t *testing.T) { - parent := filepath.Join(root, "siblings") - child := filepath.Join(parent, "private") - if err := os.MkdirAll(child, 0700); err != nil { - t.Fatal(err) - } - setTestWindowsACL(t, parent, "(A;;0x4;;;AU)(A;OICIIO;FR;;;BU)") - setTestWindowsACL(t, child, "") - if err := validateInitDirectory("config", filepath.Join(child, "config.toml")); err != nil { - t.Fatal(err) - } - }) - t.Run("existing readable credential", func(t *testing.T) { - key := filepath.Join(root, "readable.key") - if err := os.WriteFile(key, []byte("synthetic"), 0600); err != nil { - t.Fatal(err) - } - setTestWindowsACL(t, key, "(A;;FR;;;BU)") - _, err := validateInitPaths(filepath.Join(root, "existing.toml"), &config.Config{Keystore: key, StateFile: filepath.Join(root, "existing.state")}) - if err == nil || !strings.Contains(err.Error(), "keystore file") { - t.Fatalf("unsafe existing credential was not rejected: %v", err) - } - }) - t.Run("junction to readable credential", func(t *testing.T) { - target := filepath.Join(root, "junction-target") - link := filepath.Join(root, "junction-link") - if err := os.Mkdir(target, 0700); err != nil { - t.Fatal(err) - } - output, err := exec.Command("cmd.exe", "/d", "/c", "mklink", "/J", link, target).CombinedOutput() - if err != nil { - t.Fatalf("create test junction: %v: %s", err, output) - } - t.Logf("mklink: %s", output) - linkTarget, linkErr := os.Readlink(link) - t.Logf("junction target=%q error=%v", linkTarget, linkErr) - defer os.Remove(link) - key := filepath.Join(target, "key") - if err := os.WriteFile(key, []byte("synthetic"), 0600); err != nil { - t.Fatal(err) - } - cfg := &config.Config{Keystore: filepath.Join(link, "key"), StateFile: filepath.Join(root, "junction.state")} - if _, err := validateInitPaths(filepath.Join(root, "junction.toml"), cfg); err != nil { - t.Fatalf("private junction target was rejected: %v", err) - } - setTestWindowsACL(t, key, "(A;;FR;;;BU)") - _, err = validateInitPaths(filepath.Join(root, "junction.toml"), cfg) - if err == nil || !strings.Contains(err.Error(), "keystore file") { - t.Fatalf("readable junction target was not rejected: %v", err) - } - setTestWindowsACL(t, key, "") - setTestWindowsACL(t, link, "(A;;SD;;;WD)") - if _, err := validateInitPaths(filepath.Join(root, "junction.toml"), cfg); err == nil { - t.Fatal("junction with unsafe DELETE access was accepted") - } - outer := filepath.Join(root, "outer-junction") - if output, err := exec.Command("cmd.exe", "/d", "/c", "mklink", "/J", outer, link).CombinedOutput(); err != nil { - t.Fatalf("create outer junction: %v: %s", err, output) - } - defer os.Remove(outer) - cfg.Keystore = filepath.Join(outer, "key") - if _, err := validateInitPaths(filepath.Join(root, "junction.toml"), cfg); err == nil { - t.Fatal("unsafe intermediate junction was accepted") - } - setTestWindowsACL(t, link, "") - if _, err := validateInitPaths(filepath.Join(root, "junction.toml"), cfg); err != nil { - t.Fatalf("safe multi-hop junction rejected: %v", err) - } - }) -} diff --git a/cmd/geektrust/library.go b/cmd/geektrust/library.go index d047090..7cab12e 100644 --- a/cmd/geektrust/library.go +++ b/cmd/geektrust/library.go @@ -2,64 +2,93 @@ package main import ( "context" - "encoding/json" + "crypto/tls" + "crypto/x509" "errors" - "log/slog" - "net/http" - "github.com/ShanghaitechGeekPie/geektrust/auth" - "github.com/ShanghaitechGeekPie/geektrust/client" + "github.com/ShanghaitechGeekPie/geektrust/deployment" "github.com/ShanghaitechGeekPie/geektrust/internal/config" - "github.com/ShanghaitechGeekPie/geektrust/internal/idsauth" + "github.com/ShanghaitechGeekPie/geektrust/internal/runtime" "github.com/ShanghaitechGeekPie/geektrust/internal/session" + "github.com/ShanghaitechGeekPie/geektrust/internal/storage" + "log/slog" + "net/netip" + "os" ) -// Command wiring owns paths and terminal interaction; the library sees neither. -func commandClient(cfg *config.Config, logger *slog.Logger) (*client.Client, error) { - return client.New(client.Options{ - Compatibility: cfg.Compatibility, - ControllerURL: cfg.BaseURL, DeviceID: cfg.DeviceID, Platform: cfg.Platform, - LoginDomain: cfg.LoginDomain, ClientMode: cfg.ClientType == "client", - Gateways: cfg.Gateways, DNS: cfg.DNS, - Logger: logger, ChallengeHandler: func(ctx context.Context, challenge auth.Challenge) (string, error) { - if challenge.Method != "auth/sms" { - return "", &auth.UnsupportedError{Method: challenge.Method} - } - return smsPrompt(ctx) - }, - SessionStore: commandSessionStore{session.NewStore(cfg.StateFile)}, - Authenticator: client.AuthenticatorFunc(func(ctx context.Context, h *http.Client) (string, error) { - k, err := idsauth.LoadKeystore(cfg.Keystore) - if err != nil { - return "", errors.New("cannot load credential") - } - if err = idsauth.NewClient(k, h).Login(ctx); err != nil { - return "", err - } - return k.Username(), nil - }), - }) +// Every command owns file paths and input; the same runtime owns all network work. +func commandClient(cfg *config.Config, logger *slog.Logger) (*runtime.Runtime, error) { + if e := cfg.ValidateListeners(); e != nil { + return nil, e + } + if e := cfg.EnsureDeviceID(); e != nil { + return nil, e + } + identity, e := auth.NewPasskey(storage.CredentialFile(cfg.Keystore)) + if e != nil { + return nil, e + } + o := runtime.Options{ControllerURL: cfg.BaseURL, DeviceID: cfg.DeviceID, Logger: logger, Auth: runtime.AuthOptions{Identity: identity, LoginDomain: cfg.LoginDomain, OnChallenge: func(ctx context.Context, c auth.Challenge) (string, error) { + if c.Info.Method != auth.SMS { + return "", auth.ErrUnsupported + } + return smsPrompt(ctx) + }}, Deployment: deployment.Options{Profile: cfg.Deployment, Protocol: deployment.ProtocolOptions{ControllerPlatform: cfg.Platform}, Fallbacks: &deployment.Fallbacks{ApplicationID: cfg.Compatibility.FallbackAppID, Gateways: cfg.Compatibility.FallbackGateways, MissingGatewayGroup: cfg.Compatibility.MissingGatewayGroupFallback, StreamToL3: cfg.Compatibility.TCPToL3Fallback}}, SessionStore: commandSessionStore{session.NewStore(cfg.StateFile)}} + if cfg.Version == 1 && cfg.CompatibilityExplicit { + o.Deployment.Profile = deployment.Generic + } + if cfg.ClientType == "client" { + o.Auth.Mode = runtime.DesktopMode + } + if p := cfg.Compatibility.ProcessIdentity; p != nil { + o.Deployment.Protocol.Process = &deployment.ProcessMetadata{Name: p.Name, Platform: p.Platform, Path: p.Path} + } + if cfg.Compatibility.GatewayServerName != "" { + o.Network.GatewayTLS.Config = &tls.Config{ServerName: cfg.Compatibility.GatewayServerName} + } + if cfg.CAFile != "" { + b, e := os.ReadFile(cfg.CAFile) + if e != nil { + return nil, e + } + pool, e := x509.SystemCertPool() + if e != nil { + pool = x509.NewCertPool() + } + if !pool.AppendCertsFromPEM(b) { + return nil, errors.New("invalid gateway CA file") + } + if o.Network.GatewayTLS.Config == nil { + o.Network.GatewayTLS.Config = &tls.Config{} + } + o.Network.GatewayTLS.Config.RootCAs = pool + } + if cfg.Version == 2 { + o.Network.AllowedGateways = cfg.Gateways + } + for _, s := range cfg.DNS { + a, e := netip.ParseAddr(s) + if e != nil { + return nil, e + } + o.DNS.Servers = append(o.DNS.Servers, a) + } + c, e := runtime.New(o) + if e != nil { + return nil, e + } + c.ConfigureCommand(cfg.SessionOptions(), cfg.DNSStrategy) + return c, nil } type commandSessionStore struct{ store *session.Store } -func (s commandSessionStore) Load(ctx context.Context) ([]byte, error) { - if err := ctx.Err(); err != nil { - return nil, err - } - state, err := s.store.Load(ctx) - if err != nil || state == nil { - return nil, err - } - return json.Marshal(state) +func (s commandSessionStore) Load(ctx context.Context, _ runtime.SessionScope) ([]byte, error) { + return s.store.LoadBytes(ctx) } -func (s commandSessionStore) Save(ctx context.Context, data []byte) error { - if err := ctx.Err(); err != nil { - return err - } - var state session.State - if err := json.Unmarshal(data, &state); err != nil { - return errors.New("invalid session state") - } - return s.store.Save(ctx, &state) +func (s commandSessionStore) Save(ctx context.Context, _ runtime.SessionScope, b []byte) error { + return s.store.SaveBytes(ctx, b) +} +func (s commandSessionStore) Delete(ctx context.Context, _ runtime.SessionScope) error { + return s.store.Delete(ctx) } diff --git a/cmd/geektrust/main.go b/cmd/geektrust/main.go index 8d9b2ed..a80bf97 100644 --- a/cmd/geektrust/main.go +++ b/cmd/geektrust/main.go @@ -17,15 +17,14 @@ import ( "os/signal" "strconv" "strings" + "sync" "syscall" "time" "github.com/ShanghaitechGeekPie/geektrust/internal/config" "github.com/ShanghaitechGeekPie/geektrust/internal/inbound" - "github.com/ShanghaitechGeekPie/geektrust/internal/l3" - "github.com/ShanghaitechGeekPie/geektrust/internal/resolver" + "github.com/ShanghaitechGeekPie/geektrust/internal/runtime" "github.com/ShanghaitechGeekPie/geektrust/internal/session" - "github.com/ShanghaitechGeekPie/geektrust/internal/tunnel" "github.com/ShanghaitechGeekPie/geektrust/internal/webui" ) @@ -73,6 +72,13 @@ func main() { return } + if cmd == "config" { + if e := cmdConfig(configPath, args); e != nil { + fmt.Fprintln(os.Stderr, e) + os.Exit(1) + } + return + } cfg, err := config.Load(configPath) if err != nil { fmt.Fprintln(os.Stderr, "geektrust:", err) @@ -141,6 +147,11 @@ func cmdLogin(ctx context.Context, cfg *config.Config, logger *slog.Logger, args if err != nil { return err } + if cfg.ClientType == "client" { + if e := c.TrustCurrentDevice(ctx); e != nil { + logger.Warn("trust device binding failed", "err", e) + } + } fmt.Printf("gateways: %s\ndns: %s\nauthorized resources: %d\n", strings.Join(info.Gateways, ", "), strings.Join(info.DNS, ", "), len(info.Resources)) return nil } @@ -150,41 +161,43 @@ func cmdLogin(ctx context.Context, cfg *config.Config, logger *slog.Logger, args // first login so SMS verification can be completed in the browser; any panel // failure degrades to the terminal-only path without affecting the VPN. func cmdRun(ctx context.Context, cfg *config.Config, logger *slog.Logger, args []string) error { - if !cfg.WebEnabled() { - return runVPN(ctx, cfg, logger, session.NewProvider(cfg, logger, smsPrompt)) + if len(args) != 0 { + return errors.New("usage: geektrust run") } - if webListenConflict(cfg) { - logger.Warn("web panel listen conflicts with an enabled inbound listener; panel disabled", - "listen", cfg.Web.Listen) - return runVPN(ctx, cfg, logger, session.NewProvider(cfg, logger, smsPrompt)) + if !cfg.Inbound.SOCKS5.Enabled && !cfg.Inbound.HTTP.Enabled { + return errors.New("no proxy listeners enabled") } - listener, err := net.Listen("tcp", cfg.Web.Listen) - if err != nil { - logger.Warn("web panel listen failed; panel disabled", "err", err) - return runVPN(ctx, cfg, logger, session.NewProvider(cfg, logger, smsPrompt)) - } - - hub := webui.NewHub(cfg) - broker := webui.NewBroker(hub.SetSMSPending) - provider := session.NewProvider(cfg, logger, nil) - provider.SetSMSHandler(broker) - provider.AddObserver(hub) - server := webui.NewServer(hub, broker, provider, cfg) - go func() { - // A panel failure must never affect the VPN; surface it in the log - // instead of dying silently. - if err := server.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) { - logger.Warn("web panel server stopped unexpectedly", "err", err) + c, e := commandClient(cfg, logger) + if e != nil { + return e + } + defer c.Close() + if cfg.WebEnabled() && !webListenConflict(cfg) { + ln, e := net.Listen("tcp", cfg.Web.Listen) + if e != nil { + logger.Warn("web panel disabled", "err", e) + } else { + hub := webui.NewHub(cfg) + broker := webui.NewBroker(hub.SetSMSPending) + c.Provider().SetSMSHandler(broker) + c.Provider().ChallengeHandler = nil + c.Provider().AddObserver(hub) + server := webui.NewServer(hub, broker, c, cfg) + server.SetLifetime(ctx) + go func() { + if e := server.Serve(ln); e != nil && !errors.Is(e, http.ErrServerClosed) { + logger.Warn("web panel stopped", "err", e) + } + }() + defer func() { + stop, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _ = server.Shutdown(stop) + }() + logger.Info("web panel", "url", "http://"+cfg.Web.Listen) } - }() - defer func() { - // The run context may already be canceled here; use a fresh one. - shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - _ = server.Shutdown(shutdownCtx) - }() - logger.Info("web panel", "url", "http://"+cfg.Web.Listen) - return runVPN(ctx, cfg, logger, provider) + } + return runVPN(ctx, cfg, logger, c) } // webListenConflict reports whether the panel address collides with an @@ -250,24 +263,21 @@ func listenIP(host string) net.IP { } // runVPN establishes the session and serves the proxy listeners. -func runVPN(ctx context.Context, cfg *config.Config, logger *slog.Logger, provider *session.Provider) error { - cred, err := provider.Credential(ctx) - if err != nil { - return err +func runVPN(ctx context.Context, cfg *config.Config, logger *slog.Logger, c *runtime.Runtime) error { + if _, e := c.Connect(ctx); e != nil { + return e + } + cred, e := c.Provider().Credential(ctx) + if e != nil { + return e } printSummary(cred) - - // Session liveness: periodic onlineInfo, silent re-login on expiry. - go provider.CheckLoop(ctx, 5*time.Minute) - - manager := tunnel.NewManager(provider, logger) - manager.GatewayTLSConfig = &tls.Config{ServerName: cfg.GatewayServerName()} - defer manager.Close() - dialer := &l3.Dialer{Manager: manager, Provider: provider, Logger: logger} - res := resolver.New(provider, dialer) - - srv := inbound.New(cfg.Inbound, res, dialer, logger) - return srv.Run(ctx) + if cfg.ClientType == "client" { + if e := c.TrustCurrentDevice(ctx); e != nil { + logger.Warn("trust device binding failed", "err", e) + } + } + return inbound.New(cfg.Inbound, c, c, logger).Run(ctx) } func printSummary(cred *session.Credential) { @@ -292,33 +302,34 @@ func printSummary(cred *session.Credential) { } // smsPrompt reads the SMS code from stdin whenever the controller demands it. +var terminalInput struct { + once sync.Once + lines chan string +} + func smsPrompt(ctx context.Context) (string, error) { - fmt.Fprintln(os.Stderr, "The controller requires SMS verification; a code was sent to your phone.") - fmt.Fprint(os.Stderr, "Enter the 6-digit code: ") - type result struct { - code string - err error - } - ch := make(chan result, 1) - go func() { - sc := bufio.NewScanner(os.Stdin) - if sc.Scan() { - ch <- result{code: strings.TrimSpace(sc.Text())} - } else { - ch <- result{err: errors.New("no verification code provided")} - } - }() + terminalInput.once.Do(func() { + terminalInput.lines = make(chan string) + go func() { + defer close(terminalInput.lines) + scan := bufio.NewScanner(os.Stdin) + for scan.Scan() { + select { + case terminalInput.lines <- strings.TrimSpace(scan.Text()): + default: + } + } + }() + }) + fmt.Fprintln(os.Stderr, "The controller requires SMS verification; enter the 6-digit code:") select { - case r := <-ch: - if r.err != nil { - return "", r.err - } - if r.code == "" { - return "", errors.New("empty verification code") - } - return r.code, nil case <-ctx.Done(): return "", ctx.Err() + case code, ok := <-terminalInput.lines: + if !ok || code == "" { + return "", errors.New("no verification code provided") + } + return code, nil } } @@ -352,7 +363,7 @@ func cmdDial(ctx context.Context, cfg *config.Config, logger *slog.Logger, args time.Since(start).Round(time.Millisecond)) if port == 443 { - tlsConn := tls.Client(conn, &tls.Config{InsecureSkipVerify: true, ServerName: host}) + tlsConn := tls.Client(conn, &tls.Config{ServerName: host}) if err := tlsConn.HandshakeContext(ctx); err != nil { return fmt.Errorf("tls handshake over tunnel: %w", err) } @@ -416,11 +427,15 @@ func cmdTrustDevice(ctx context.Context, cfg *config.Config, logger *slog.Logger return err } - provider := session.NewProvider(cfg, logger, smsPrompt) - if _, err := provider.Credential(ctx); err != nil { + c, err := commandClient(cfg, logger) + if err != nil { + return err + } + defer c.Close() + if _, err := c.Connect(ctx); err != nil { return fmt.Errorf("trust-device: need an active session: %w", err) } - sc := provider.SDPCClient() + sc := c.ActiveSDPC() if sc == nil { return fmt.Errorf("trust-device: no controller client available") } diff --git a/cmd/geektrust/main_test.go b/cmd/geektrust/main_test.go index 5bf8696..8a62c41 100644 --- a/cmd/geektrust/main_test.go +++ b/cmd/geektrust/main_test.go @@ -125,8 +125,8 @@ func TestCmdInitDefaultsAndFlags(t *testing.T) { if err != nil { t.Fatal(err) } - if runtime.GOOS != "windows" && info.Mode().Perm() != 0o600 { - t.Errorf("existing keystore mode = %04o, want 0600", info.Mode().Perm()) + if runtime.GOOS != "windows" && info.Mode().Perm() != 0o644 { + t.Errorf("existing keystore mode = %04o, want 0644", info.Mode().Perm()) } }) @@ -190,30 +190,12 @@ func TestValidateInitPaths(t *testing.T) { keystore: filepath.Join(dir, "key-3"), stateFile: filepath.Join(dir, "state-3"), }, - { - name: "parent traversal", - configPath: dir + string(os.PathSeparator) + "nested" + string(os.PathSeparator) + ".." + string(os.PathSeparator) + "config-4", - keystore: filepath.Join(dir, "key-4"), - stateFile: filepath.Join(dir, "state-4"), - }, { name: "config is keystore ancestor", configPath: filepath.Join(dir, "config-parent"), keystore: filepath.Join(dir, "config-parent", "keystore"), stateFile: filepath.Join(dir, "state-parent"), }, - { - name: "case-only collision", - configPath: filepath.Join(dir, "Config-5"), - keystore: filepath.Join(dir, "config-5"), - stateFile: filepath.Join(dir, "state-5"), - }, - { - name: "Unicode normalization collision", - configPath: filepath.Join(dir, "caf\u00e9-6"), - keystore: filepath.Join(dir, "cafe\u0301-6"), - stateFile: filepath.Join(dir, "state-6"), - }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -274,110 +256,6 @@ func TestValidateInitPaths(t *testing.T) { } }) - t.Run("symlink through other-writable parent", func(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("Windows file modes do not represent Unix directory permissions") - } - targetDir := filepath.Join(dir, "safe-symlink-target") - unsafeDir := filepath.Join(dir, "unsafe-symlink-parent") - if err := os.Mkdir(targetDir, 0o700); err != nil { - t.Fatal(err) - } - if err := os.Mkdir(unsafeDir, 0o700); err != nil { - t.Fatal(err) - } - if err := os.Chmod(unsafeDir, 0o777); err != nil { - t.Fatal(err) - } - linkDir := filepath.Join(unsafeDir, "link") - if err := os.Symlink(targetDir, linkDir); err != nil { - t.Fatal(err) - } - _, err := validateInitPaths( - filepath.Join(dir, "safe-symlink-config"), - &config.Config{ - Keystore: filepath.Join(dir, "safe-symlink-key"), - StateFile: filepath.Join(linkDir, "state"), - }, - ) - if err == nil { - t.Fatal("symlink through other-writable parent was accepted") - } - }) - - t.Run("other-writable config directory", func(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("Windows file modes do not represent Unix directory permissions") - } - shared := filepath.Join(dir, "shared") - if err := os.Mkdir(shared, 0o700); err != nil { - t.Fatal(err) - } - if err := os.Chmod(shared, 0o777); err != nil { - t.Fatal(err) - } - _, err := validateInitPaths( - filepath.Join(shared, "config.toml"), - &config.Config{ - Keystore: filepath.Join(dir, "shared-key"), - StateFile: filepath.Join(dir, "shared-state"), - }, - ) - if err == nil { - t.Fatal("other-writable config directory was accepted") - } - }) - - t.Run("other-writable keystore directory", func(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("Windows file modes do not represent Unix directory permissions") - } - shared := filepath.Join(dir, "shared-keystore") - if err := os.Mkdir(shared, 0o700); err != nil { - t.Fatal(err) - } - if err := os.Chmod(shared, 0o777); err != nil { - t.Fatal(err) - } - _, err := validateInitPaths( - filepath.Join(dir, "shared-keystore-config"), - &config.Config{ - Keystore: filepath.Join(shared, "keystore"), - StateFile: filepath.Join(dir, "shared-keystore-state"), - }, - ) - if err == nil { - t.Fatal("other-writable keystore directory was accepted") - } - }) - - t.Run("private child under other-writable ancestor", func(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("Windows file modes do not represent Unix directory permissions") - } - shared := filepath.Join(dir, "shared-ancestor") - privateChild := filepath.Join(shared, "private-child") - if err := os.Mkdir(shared, 0o700); err != nil { - t.Fatal(err) - } - if err := os.Chmod(shared, 0o777); err != nil { - t.Fatal(err) - } - if err := os.Mkdir(privateChild, 0o700); err != nil { - t.Fatal(err) - } - _, err := validateInitPaths( - filepath.Join(privateChild, "config.toml"), - &config.Config{ - Keystore: filepath.Join(dir, "ancestor-key"), - StateFile: filepath.Join(dir, "ancestor-state"), - }, - ) - if err == nil { - t.Fatal("other-writable ancestor was accepted") - } - }) - t.Run("sticky writable ancestor", func(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("Windows file modes do not represent Unix directory permissions") diff --git a/config.example.toml b/config.example.toml index 893dac9..340edf5 100644 --- a/config.example.toml +++ b/config.example.toml @@ -1,87 +1,43 @@ -# geekTrust 手工配置模板。推荐改用 `geektrust init`,它会生成唯一的 device_id -# 并写入可直接使用的 client 模式配置。 +# geekTrust 配置版本 2。相对路径相对于本文件。 +# 上科大只需提供已有 Passkey;缺省启用本地代理和 Web 面板。 +config_version = 2 -# ---- 登录 ---- -# passkey 凭据文件(由 `geektrust init --bind-passkey` 或 shanghaitech-ids-passkey 的 bind 命令生成)。 +[auth.passkey] keystore = "./ids-passkey.keystore" -# 32 位大写十六进制,每个安装必须不同。可由 `geektrust init` 生成;首次登录后不要修改。 -device_id = "REPLACE_WITH_32_UPPERCASE_HEX" - -# ---- 控制器 ---- -base_url = "https://vpn.shanghaitech.edu.cn" -platform = "Mac" # 控制器协议参数,大小写敏感,与运行操作系统无关 - -# client 模式会在首次短信验证后尝试绑定授信终端,绑定成功后通常不再要求短信。 -# 省略时默认为 browser。 -client_type = "client" - -# 留空时从控制器发现 CAS 登录域,多登录域时必须明确选择。 -login_domain = "" - -# ---- 网关线路 ---- -# 留空 = 从上游 clientResource 自动获取(nodeGroup 地址); -# 填写则筛选服务端分配的网关(格式 host:port,默认端口 441),不会跨组覆盖。 -gateways = [] -# gateways = ["119.78.254.241:441", "59.78.171.241:441"] - -# ---- DNS ---- -# 可选:覆盖服务端下发的隧道 DNS(只填 IP,端口固定 53)。 -# 域名先用公共 DNS(223.5.5.5、119.29.29.29)和系统 DNS 解析,并忽略 Clash 等代理 -# 返回的 198.18.0.0/15 fake-ip;没有可用 IPv4 时,再经 VPN 查询这些服务器。 -dns = [] -# dns = ["10.15.44.11", "10.13.6.2"] - -# ---- 会话状态 ---- -# 加密的会话文件。密钥自动生成在同目录的 .key,两个文件都只允许当前用户读写。 -state_file = "./state.enc" - -# ---- 日志 ---- -log_level = "info" - -# ---- 部署兼容选项 ---- -# 默认严格模式;不根据控制器域名自动启用。修改后重新启动客户端。 -[compatibility] -# 仅在资源规则没有匹配时提交此 appId;仍由服务端验证授权。 -fallback_app_id = "" -# 仅在当前控制器未下发任何网关时使用;必须写完整 host:port。 -fallback_gateways = [] -# IP 网关使用的 TLS 证书域名;不会关闭证书验证。 -gateway_server_name = "" -# 指定网关组缺少地址时,允许使用已下发的完整网关列表。 -missing_gateway_group_fallback = false -# TCP 流协议不兼容时尝试 L3;明确拒绝、不可达、取消不触发回退。 -tcp_to_l3_fallback = false - -# 上海科大旧部署需要兼容时,可逐项将上述值替换为: -# fallback_app_id = "681165d0-1c77-11ed-8650-cd35a51aa42a" -# fallback_gateways = ["119.78.254.241:441", "59.78.171.241:441"] -# gateway_server_name = "vpn.shanghaitech.edu.cn" -# missing_gateway_group_fallback = true -# tcp_to_l3_fallback = true -# 如需指定 CAS 登录域,在文件顶部设置 login_domain = "Shanghaitech.edu.cn"。 - -# 可选:覆盖发送给网关的进程元数据。字段必须全部填写。 -# 未配置时沿用已实现的协议值:流式 TCP 为 Linux Chrome/SSH,L3 为 macOS aTrust。 -# 这些字段不代表本机进程检测结果,也不改变授权。 -# [compatibility.process_identity] -# name = "my-client" -# platform = "Windows" -# path = "my-client.exe" - -# ---- 代理入口 ---- -# 两个代理都没有认证,只应监听回环地址(127.0.0.1)。监听其他地址会让 -# 同一网络中的其他设备使用你的 VPN 会话。 -[inbound.socks5] -enabled = true -listen = "127.0.0.1:1080" - -[inbound.http] -enabled = true -listen = "127.0.0.1:8080" - -# ---- Web 面板 ---- -# `run` 期间提供本地面板,省略时默认启用。listen 必须是回环地址,且不能使用 80 端口。 -[web] -enabled = true -listen = "127.0.0.1:8081" +# 下列分组可按需启用。省略表示使用默认值。 +# [controller] +# url = "https://vpn.shanghaitech.edu.cn" +# deployment = "auto" # auto / shanghaitech / ecnu / generic +# platform = "Mac" # 控制器协议参数,与本机系统无关 + +# [auth] +# mode = "auto" # auto / client / browser +# login_domain = "" +# device_id = "" # 缺省读取或创建持久身份;升级时保留既有 ID + +# [proxy.socks5] +# listen = "127.0.0.1:1080" # 空字符串禁用 +# [proxy.http] +# listen = "127.0.0.1:8080" +# [web] +# listen = "127.0.0.1:8081" # 只允许回环地址;空字符串禁用 + +# [dns] +# strategy = "auto" # auto 保留 CLI 的既有顺序;controller 只走控制器 DNS +# servers = [] # 空列表使用控制器下发的 DNS + +# [storage] +# directory = "" # 缺省使用平台用户私有持久目录 +# legacy_state = "" # 仅用于保留既有加密会话路径,不删除原缓存和密钥 + +# [logging] +# level = "info" + +# 高级设置只在实际部署需要时填写。证书验证始终开启。 +# [tls.gateway] +# server_name = "" +# ca_file = "" +# [routing] +# gateway_filter = [] # 显式空列表拒绝所有线路;省略不额外筛选 +# fallback_app_id = "" diff --git a/deployment/profile.go b/deployment/profile.go index 0b5aed5..7ffed99 100644 --- a/deployment/profile.go +++ b/deployment/profile.go @@ -1,5 +1,3 @@ -// Package deployment defines explicit protocol compatibility settings shared by -// configuration files and embedded clients. No behavior is selected by hostname. package deployment import ( @@ -10,64 +8,65 @@ import ( "unicode" ) -// Compatibility is opt-in. Its zero value uses controller policy without -// deployment-specific fallbacks. These settings never override a server denial. -type Compatibility struct { - ProcessIdentity *ProcessIdentity `toml:"process_identity" json:"process_identity,omitempty"` - FallbackAppID string `toml:"fallback_app_id" json:"fallback_app_id,omitempty"` - FallbackGateways []string `toml:"fallback_gateways" json:"fallback_gateways,omitempty"` - GatewayServerName string `toml:"gateway_server_name" json:"gateway_server_name,omitempty"` - MissingGatewayGroupFallback bool `toml:"missing_gateway_group_fallback" json:"missing_gateway_group_fallback,omitempty"` - TCPToL3Fallback bool `toml:"tcp_to_l3_fallback" json:"tcp_to_l3_fallback,omitempty"` +type Profile string + +const ( + Auto Profile = "" + Generic Profile = "generic" + ShanghaiTech Profile = "shanghaitech" + ECNU Profile = "ecnu" +) + +type Options struct { + Profile Profile + Protocol ProtocolOptions + Fallbacks *Fallbacks } -// Clone separates an active client's settings from caller-owned configuration. -func (c Compatibility) Clone() Compatibility { - if c.ProcessIdentity != nil { - identity := *c.ProcessIdentity - c.ProcessIdentity = &identity - } - c.FallbackGateways = append([]string(nil), c.FallbackGateways...) - return c +type ProtocolOptions struct { + ControllerPlatform string + Process *ProcessMetadata } -func (c Compatibility) Validate() error { - if c.ProcessIdentity != nil { - if err := c.ProcessIdentity.Validate(); err != nil { - return err - } +type ProcessMetadata struct { + Name string + Platform string + Path string +} + +type Fallbacks struct { + ApplicationID string + Gateways []string + MissingGatewayGroup bool + StreamToL3 bool +} + +func (o Options) Validate() error { + switch o.Profile { + case Auto, Generic, ShanghaiTech, ECNU: + default: + return fmt.Errorf("unknown deployment profile %q", o.Profile) } - if len(c.FallbackAppID) > 256 || strings.IndexFunc(c.FallbackAppID, unicode.IsControl) >= 0 { - return fmt.Errorf("compatibility.fallback_app_id must be at most 256 characters without control characters") + if len(o.Protocol.ControllerPlatform) > 64 || strings.IndexFunc(o.Protocol.ControllerPlatform, unicode.IsControl) >= 0 { + return fmt.Errorf("invalid controller platform") } - if c.GatewayServerName != "" { - name := c.GatewayServerName - if len(name) > 253 || strings.ContainsAny(name, "/\\:@?# \t\r\n") || strings.IndexFunc(name, unicode.IsControl) >= 0 { - return fmt.Errorf("compatibility.gateway_server_name must be a TLS hostname without a port") + if p := o.Protocol.Process; p != nil { + for _, v := range []string{p.Name, p.Platform, p.Path} { + if strings.TrimSpace(v) == "" || len(v) > 4096 || strings.IndexFunc(v, unicode.IsControl) >= 0 { + return fmt.Errorf("invalid process metadata") + } } } - for _, address := range c.FallbackGateways { - host, port, err := net.SplitHostPort(address) - number, portErr := strconv.Atoi(port) - if err != nil || host == "" || portErr != nil || number < 1 || number > 65535 || strings.ContainsAny(host, "/\\@?# \t\r\n") { - return fmt.Errorf("compatibility.fallback_gateways entries must be host:port with port 1-65535") + if f := o.Fallbacks; f != nil { + if len(f.ApplicationID) > 256 || strings.IndexFunc(f.ApplicationID, unicode.IsControl) >= 0 { + return fmt.Errorf("invalid fallback application ID") } - } - return nil -} - -// ProcessIdentity overrides the process metadata sent to the gateway. It is -// protocol metadata, not a claim about a locally running or verified process. -type ProcessIdentity struct { - Name string `toml:"name" json:"name"` - Platform string `toml:"platform" json:"platform"` - Path string `toml:"path" json:"path"` -} - -func (p ProcessIdentity) Validate() error { - for _, value := range []string{p.Name, p.Platform, p.Path} { - if strings.TrimSpace(value) == "" || len(value) > 4096 || strings.IndexFunc(value, unicode.IsControl) >= 0 { - return fmt.Errorf("compatibility.process_identity requires name, platform and path without control characters (max 4096 bytes each)") + for _, a := range f.Gateways { + h, p, e := net.SplitHostPort(a) + n, x := strconv.Atoi(p) + if e != nil || x != nil || h == "" || n < 1 || n > 65535 || strings.ContainsAny(h, "/\\@?# \t\r\n") { + return fmt.Errorf("invalid fallback gateway") + } } } return nil diff --git a/internal/config/compatibility_test.go b/internal/config/compatibility_test.go index 32d81f4..65393d0 100644 --- a/internal/config/compatibility_test.go +++ b/internal/config/compatibility_test.go @@ -31,9 +31,18 @@ tcp_to_l3_fallback = true if err != nil { t.Fatal(err) } - if c.Compatibility.TCPToL3Fallback != enabled || c.Compatibility.MissingGatewayGroupFallback != enabled || (c.Compatibility.FallbackAppID != "") != enabled || (len(c.Compatibility.FallbackGateways) > 0) != enabled || (c.GatewayServerName() != "") != enabled || (c.LoginDomain != "") != enabled { - t.Fatalf("unexpected settings for enabled=%v: %+v", enabled, c.Compatibility) + if enabled { + if c.Compatibility.FallbackAppID != "custom-app" || c.GatewayServerName() != "gateway.example" || c.LoginDomain != "custom-domain" { + t.Fatal("explicit settings lost") + } + } else if controller == DefaultBaseURL { + if c.GatewayServerName() != "vpn.shanghaitech.edu.cn" || c.Compatibility.FallbackAppID == "" { + t.Fatal("ShanghaiTech defaults missing") + } + } else if c.GatewayServerName() != "" || c.Compatibility.FallbackAppID != "" { + t.Fatal("school defaults leaked") } + after, err := os.ReadFile(path) if err != nil || string(after) != body { t.Fatal("loading changed original configuration") @@ -45,11 +54,9 @@ tcp_to_l3_fallback = true func TestCompatibilityConfigRejectsMistakes(t *testing.T) { for _, setting := range []string{ - "[compatibility]\ntcp_to_l3_fallbak = true", "[compatibility]\nfallback_gateways = ['gateway:0']", "[compatibility]\nfallback_gateways = ['gateway']", "[compatibility]\ngateway_server_name = 'https://gateway'", - "app_id = 'removed-setting'", } { path := filepath.Join(t.TempDir(), "config.toml") if err := os.WriteFile(path, []byte("keystore = 'synthetic.keystore'\n"+setting), 0600); err != nil { @@ -61,25 +68,24 @@ func TestCompatibilityConfigRejectsMistakes(t *testing.T) { } } -func TestGeneratedConfigDefaultsToStrictCompatibility(t *testing.T) { - cfg, err := PrepareInitialConfig(InitOptions{}) - if err != nil { - t.Fatal(err) +func TestGeneratedConfigDefaultsToShanghaiTech(t *testing.T) { + cfg, e := PrepareInitialConfig(InitOptions{}) + if e != nil { + t.Fatal(e) } - data := renderInitialConfig(cfg) - if !strings.Contains(string(data), "[compatibility]") { - t.Fatal("missing discoverable settings") + p := filepath.Join(t.TempDir(), "config.toml") + b := renderInitialConfig(cfg) + if !strings.Contains(string(b), "config_version = 2") { + t.Fatal("init did not generate v2") } - path := filepath.Join(t.TempDir(), "config.toml") - if err := os.WriteFile(path, data, 0600); err != nil { - t.Fatal(err) + if e = os.WriteFile(p, b, 0600); e != nil { + t.Fatal(e) } - loaded, err := Load(path) - if err != nil { - t.Fatal(err) + v, e := Load(p) + if e != nil { + t.Fatal(e) } - - if loaded.Compatibility.TCPToL3Fallback || loaded.Compatibility.MissingGatewayGroupFallback || loaded.Compatibility.FallbackAppID != "" || loaded.GatewayServerName() != "" { - t.Fatal("generated config enabled compatibility") + if v.GatewayServerName() != "vpn.shanghaitech.edu.cn" || !v.Compatibility.TCPToL3Fallback { + t.Fatal("minimal ShanghaiTech defaults missing") } } diff --git a/internal/config/config.go b/internal/config/config.go index 3779d72..220164d 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -3,6 +3,8 @@ package config import ( "fmt" + public "github.com/ShanghaitechGeekPie/geektrust/deployment" + defaults "github.com/ShanghaitechGeekPie/geektrust/internal/deployment" "net" "os" "strconv" @@ -11,7 +13,7 @@ import ( "github.com/BurntSushi/toml" - "github.com/ShanghaitechGeekPie/geektrust/deployment" + "github.com/ShanghaitechGeekPie/geektrust/internal/settings" ) // DefaultDeviceID is the legacy shared browser-mode identifier. It remains @@ -27,19 +29,29 @@ const DefaultWebListen = "127.0.0.1:8081" // Config is the top-level configuration. type Config struct { - Compatibility deployment.Compatibility `toml:"compatibility"` - Keystore string `toml:"keystore"` - DeviceID string `toml:"device_id"` - BaseURL string `toml:"base_url"` - Platform string `toml:"platform"` - ClientType string `toml:"client_type"` - LoginDomain string `toml:"login_domain"` - Gateways []string `toml:"gateways"` - DNS []string `toml:"dns"` - StateFile string `toml:"state_file"` - LogLevel string `toml:"log_level"` - Inbound Inbound `toml:"inbound"` - Web WebConfig `toml:"web"` + UnknownFields []string `toml:"-"` + CompatibilityExplicit bool `toml:"-"` + Version int `toml:"-"` + Deployment public.Profile `toml:"-"` + DNSStrategy string `toml:"-"` + Directory string `toml:"-"` + CAFile string `toml:"-"` + SourcePath string `toml:"-"` + AppID string `toml:"app_id"` + + Compatibility settings.Compatibility `toml:"compatibility"` + Keystore string `toml:"keystore"` + DeviceID string `toml:"device_id"` + BaseURL string `toml:"base_url"` + Platform string `toml:"platform"` + ClientType string `toml:"client_type"` + LoginDomain string `toml:"login_domain"` + Gateways []string `toml:"gateways"` + DNS []string `toml:"dns"` + StateFile string `toml:"state_file"` + LogLevel string `toml:"log_level"` + Inbound Inbound `toml:"inbound"` + Web WebConfig `toml:"web"` } // Inbound holds the proxy listener configuration. @@ -74,13 +86,39 @@ func Load(path string) (*Config, error) { if err != nil { return nil, fmt.Errorf("read config: %w", err) } + var header struct { + Version int `toml:"config_version"` + } + if _, err := toml.Decode(string(data), &header); err != nil { + return nil, err + } + if header.Version != 0 { + if header.Version != 2 { + return nil, fmt.Errorf("unsupported config_version %d", header.Version) + } + return loadV2(path, data) + } var cfg Config meta, err := toml.Decode(string(data), &cfg) if err != nil { return nil, fmt.Errorf("parse config %s: %w", path, err) } - if keys := meta.Undecoded(); len(keys) != 0 { - return nil, fmt.Errorf("unknown configuration field %s", keys[0]) + for _, key := range meta.Undecoded() { + cfg.UnknownFields = append(cfg.UnknownFields, key.String()) + } + cfg.CompatibilityExplicit = meta.IsDefined("compatibility") + cfg.Version = 1 + cfg.SourcePath = path + cfg.DNSStrategy = "auto" + cfg.applyDefaults() + if !meta.IsDefined("compatibility") { + cfg.Compatibility = defaults.Resolve(cfg.BaseURL, public.Options{}).Compatibility + } + if cfg.AppID != "" { + if meta.IsDefined("compatibility", "fallback_app_id") && cfg.Compatibility.FallbackAppID != cfg.AppID { + return nil, fmt.Errorf("conflicting app_id and compatibility.fallback_app_id") + } + cfg.Compatibility.FallbackAppID = cfg.AppID } cfg.applyDefaults() if err := cfg.validate(); err != nil { @@ -90,7 +128,7 @@ func Load(path string) (*Config, error) { } func (c *Config) applyDefaults() { - if c.DeviceID == "" { + if c.DeviceID == "" && c.Version != 2 { c.DeviceID = DefaultDeviceID } if c.BaseURL == "" { @@ -122,7 +160,7 @@ func (c *Config) validate() error { if c.Keystore == "" { return fmt.Errorf("keystore path is required") } - if !isUpperHex32(c.DeviceID) { + if !(c.Version == 2 && c.DeviceID == "") && !isUpperHex32(c.DeviceID) { return fmt.Errorf("device_id must be 32 uppercase hex chars, got %q", c.DeviceID) } if !strings.HasPrefix(c.BaseURL, "https://") && !strings.HasPrefix(c.BaseURL, "http://") { @@ -243,3 +281,8 @@ func SplitHostPort(addr string) (host string, port string, err error) { func (c *Config) GatewayServerName() string { return c.Compatibility.GatewayServerName } + +// SessionOptions translates the legacy file DTO to normalized session settings. +func (c *Config) SessionOptions() settings.Session { + return settings.Session{BaseURL: c.BaseURL, DeviceID: c.DeviceID, Platform: c.Platform, ClientType: c.ClientType, LoginDomain: c.LoginDomain, Keystore: c.Keystore, StateFile: c.StateFile, Gateways: append([]string(nil), c.Gateways...), DNS: append([]string(nil), c.DNS...), Compatibility: c.Compatibility.Clone(), GatewayFilter: c.Version == 2 && c.Gateways != nil, LegacyGatewayOverride: c.Version != 2 && len(c.Gateways) > 0, DNSConfigured: len(c.DNS) > 0} +} diff --git a/internal/config/example_regression_test.go b/internal/config/example_regression_test.go index abe4186..51b7a5f 100644 --- a/internal/config/example_regression_test.go +++ b/internal/config/example_regression_test.go @@ -7,13 +7,13 @@ import ( "testing" ) -func TestExampleLogLevelIsTopLevel(t *testing.T) { +func TestExampleLoggingGroupCanBeEnabled(t *testing.T) { b, err := os.ReadFile("../../config.example.toml") if err != nil { t.Fatal(err) } s := strings.ReplaceAll(string(b), "REPLACE_WITH_32_UPPERCASE_HEX", "0123456789ABCDEF0123456789ABCDEF") - s = strings.Replace(s, `log_level = "info"`, `log_level = "debug"`, 1) + s = strings.Replace(s, "# [logging]\n# level = \"info\"", "[logging]\nlevel = \"debug\"", 1) path := filepath.Join(t.TempDir(), "config.toml") if err := os.WriteFile(path, []byte(s), 0600); err != nil { t.Fatal(err) diff --git a/internal/config/init.go b/internal/config/init.go index da13bbc..58d6421 100644 --- a/internal/config/init.go +++ b/internal/config/init.go @@ -45,7 +45,11 @@ func PrepareInitialConfig(opts InitOptions) (*Config, error) { opts.Keystore = "./ids-passkey.keystore" } if opts.StateFile == "" { - opts.StateFile = "./state.enc" + d, e := defaultDirectory() + if e != nil { + return nil, e + } + opts.StateFile = filepath.Join(d, "session.enc") } if opts.ClientType == "" { opts.ClientType = "client" @@ -99,44 +103,21 @@ func Initialize(path string, opts InitOptions) (*Config, error) { } func renderInitialConfig(cfg *Config) []byte { - q := strconv.Quote - return []byte(fmt.Sprintf(`# Generated by geektrust init. Keep device_id stable after the first login. -keystore = %s + key, _ := filepath.Abs(cfg.Keystore) + state, _ := filepath.Abs(cfg.StateFile) + return []byte(fmt.Sprintf(`# Generated by geektrust init. Keep device_id stable. +config_version = 2 + +[auth] +mode = %s device_id = %s -base_url = %s -platform = %s -client_type = %s -state_file = %s -gateways = [] -dns = [] -log_level = %s -login_domain = "" - -# Deployment-specific behavior is opt-in. See config.example.toml. -[compatibility] -fallback_app_id = "" -fallback_gateways = [] -gateway_server_name = "" -missing_gateway_group_fallback = false -tcp_to_l3_fallback = false - -[inbound.socks5] -enabled = true -listen = %s - -[inbound.http] -enabled = true -listen = %s - -[web] -enabled = %t -listen = %s -`, - q(cfg.Keystore), q(cfg.DeviceID), q(cfg.BaseURL), q(cfg.Platform), - q(cfg.ClientType), q(cfg.StateFile), q(cfg.LogLevel), - q(cfg.Inbound.SOCKS5.Listen), q(cfg.Inbound.HTTP.Listen), - cfg.WebEnabled(), q(cfg.Web.Listen), - )) + +[auth.passkey] +keystore = %s + +[storage] +legacy_state = %s +`, strconv.Quote(cfg.ClientType), strconv.Quote(cfg.DeviceID), strconv.Quote(key), strconv.Quote(state))) } func writeConfigFile(path string, data []byte, force bool) error { diff --git a/internal/config/init_test.go b/internal/config/init_test.go index 648dd8e..0f30a9a 100644 --- a/internal/config/init_test.go +++ b/internal/config/init_test.go @@ -58,7 +58,7 @@ func TestInitializeDefaultsAndPreservesExistingConfig(t *testing.T) { if err != nil { t.Fatal(err) } - webBlock := "[web]\nenabled = true\nlisten = \"" + DefaultWebListen + "\"" + webBlock := "config_version = 2" if !strings.Contains(string(raw), webBlock) { t.Errorf("rendered config missing complete [web] block:\n%s", raw) } diff --git a/internal/config/v2.go b/internal/config/v2.go new file mode 100644 index 0000000..2d7215a --- /dev/null +++ b/internal/config/v2.go @@ -0,0 +1,312 @@ +package config + +import ( + "bytes" + "errors" + "fmt" + "github.com/BurntSushi/toml" + public "github.com/ShanghaitechGeekPie/geektrust/deployment" + defaults "github.com/ShanghaitechGeekPie/geektrust/internal/deployment" + "github.com/ShanghaitechGeekPie/geektrust/internal/storage" + "net" + "net/url" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" +) + +// FileV2 owns the CLI serialization contract; SDK types carry no TOML tags. +type FileV2 struct { + Version int `toml:"config_version"` + Controller struct { + URL string `toml:"url"` + Deployment string `toml:"deployment"` + Platform string `toml:"platform"` + } `toml:"controller"` + Auth struct { + Mode string `toml:"mode"` + LoginDomain string `toml:"login_domain"` + DeviceID string `toml:"device_id"` + Passkey struct { + Keystore string `toml:"keystore"` + } `toml:"passkey"` + } `toml:"auth"` + Proxy struct { + SOCKS5 struct { + Listen string `toml:"listen"` + } `toml:"socks5"` + HTTP struct { + Listen string `toml:"listen"` + } `toml:"http"` + } `toml:"proxy"` + Web struct { + Listen string `toml:"listen"` + } `toml:"web"` + DNS struct { + Strategy string `toml:"strategy"` + Servers []string `toml:"servers"` + } `toml:"dns"` + Storage struct { + Directory string `toml:"directory"` + LegacyState string `toml:"legacy_state"` + } `toml:"storage"` + Logging struct { + Level string `toml:"level"` + } `toml:"logging"` + TLS struct { + Gateway struct { + ServerName string `toml:"server_name"` + CAFile string `toml:"ca_file"` + } `toml:"gateway"` + } `toml:"tls"` + Routing struct { + GatewayFilter []string `toml:"gateway_filter"` + FallbackAppID string `toml:"fallback_app_id"` + } `toml:"routing"` +} + +func defaultDirectory() (string, error) { + if runtime.GOOS == "linux" { + if p := os.Getenv("XDG_STATE_HOME"); filepath.IsAbs(p) { + return filepath.Join(p, "geektrust"), nil + } + h, e := os.UserHomeDir() + return filepath.Join(h, ".local", "state", "geektrust"), e + } + if runtime.GOOS == "windows" { + p := os.Getenv("LOCALAPPDATA") + if !filepath.IsAbs(p) { + return "", errors.New("LOCALAPPDATA must be an absolute user data directory") + } + return filepath.Join(p, "geektrust"), nil + } + p, e := os.UserConfigDir() + return filepath.Join(p, "geektrust"), e +} +func loadV2(path string, data []byte) (*Config, error) { + var f FileV2 + meta, e := toml.Decode(string(data), &f) + if e != nil { + return nil, e + } + if k := meta.Undecoded(); len(k) > 0 { + return nil, fmt.Errorf("unknown configuration field %s", k[0]) + } + if f.Controller.URL == "" { + f.Controller.URL = DefaultBaseURL + } + u, e := url.Parse(f.Controller.URL) + if e != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") { + return nil, errors.New("controller.url must be an HTTPS origin") + } + profile := public.Profile(f.Controller.Deployment) + if f.Controller.Deployment == "auto" { + profile = public.Auto + } + if e := (public.Options{Profile: profile}).Validate(); e != nil { + return nil, e + } + v := defaults.Resolve(f.Controller.URL, public.Options{Profile: profile, Protocol: public.ProtocolOptions{ControllerPlatform: f.Controller.Platform}}) + mode := f.Auth.Mode + if mode == "" || mode == "auto" { + mode = "browser" + if v.Profile == public.ShanghaiTech { + mode = "client" + } + } + base, e := filepath.Abs(filepath.Dir(path)) + if e != nil { + return nil, e + } + resolve := func(s string) string { + if s != "" && !filepath.IsAbs(s) { + return filepath.Join(base, s) + } + return s + } + directory := resolve(f.Storage.Directory) + if directory == "" { + directory, e = defaultDirectory() + if e != nil { + return nil, e + } + } + id := f.Auth.DeviceID + if id == "" { + b, e := os.ReadFile(filepath.Join(directory, "device_id")) + if e == nil { + id = strings.TrimSpace(string(b)) + } else if !errors.Is(e, os.ErrNotExist) { + return nil, e + } + } + cfg := &Config{Version: 2, SourcePath: path, Directory: directory, DeviceID: id, Keystore: resolve(f.Auth.Passkey.Keystore), BaseURL: strings.TrimRight(f.Controller.URL, "/"), Platform: v.Platform, Deployment: profile, ClientType: mode, LoginDomain: f.Auth.LoginDomain, Compatibility: v.Compatibility, StateFile: filepath.Join(directory, "session.enc"), DNS: append([]string(nil), f.DNS.Servers...), DNSStrategy: f.DNS.Strategy, LogLevel: f.Logging.Level} + if cfg.DNSStrategy == "" { + cfg.DNSStrategy = "auto" + } + if cfg.DNSStrategy != "auto" && cfg.DNSStrategy != "controller" && cfg.DNSStrategy != "system" { + return nil, errors.New("invalid dns.strategy") + } + if cfg.LoginDomain == "" { + cfg.LoginDomain = v.LoginDomain + } + if f.Storage.LegacyState != "" { + cfg.StateFile = resolve(f.Storage.LegacyState) + } + cfg.Gateways = f.Routing.GatewayFilter + if f.Routing.FallbackAppID != "" { + cfg.Compatibility.FallbackAppID = f.Routing.FallbackAppID + } + if f.TLS.Gateway.ServerName != "" { + cfg.Compatibility.GatewayServerName = f.TLS.Gateway.ServerName + } + cfg.CAFile = resolve(f.TLS.Gateway.CAFile) + socks, http, web := "127.0.0.1:1080", "127.0.0.1:8080", DefaultWebListen + if meta.IsDefined("proxy", "socks5", "listen") { + socks = f.Proxy.SOCKS5.Listen + } + if meta.IsDefined("proxy", "http", "listen") { + http = f.Proxy.HTTP.Listen + } + if meta.IsDefined("web", "listen") { + web = f.Web.Listen + } + cfg.Inbound = Inbound{SOCKS5: Listener{Enabled: socks != "", Listen: socks}, HTTP: Listener{Enabled: http != "", Listen: http}} + enabled := web != "" + cfg.Web = WebConfig{Enabled: &enabled, Listen: web} + cfg.applyDefaults() + if e = cfg.validate(); e != nil { + return nil, e + } + if e = cfg.ValidateListeners(); e != nil { + return nil, e + } + return cfg, nil +} +func (c *Config) ValidateListeners() error { + var addresses []string + for _, l := range []Listener{c.Inbound.SOCKS5, c.Inbound.HTTP} { + if !l.Enabled { + continue + } + h, p, e := net.SplitHostPort(l.Listen) + if e != nil { + return fmt.Errorf("invalid proxy listener: %w", e) + } + n, e := strconv.Atoi(p) + if e != nil || n < 1 || n > 65535 { + return errors.New("invalid proxy port") + } + _ = h + for _, a := range addresses { + if listenerOverlap(a, l.Listen) { + return errors.New("proxy listeners overlap") + } + } + addresses = append(addresses, l.Listen) + } + return nil +} +func listenerOverlap(a, b string) bool { + ah, ap, _ := net.SplitHostPort(a) + bh, bp, _ := net.SplitHostPort(b) + an, _ := strconv.Atoi(ap) + bn, _ := strconv.Atoi(bp) + if an != bn { + return false + } + if ah == bh || ah == "" || bh == "" { + return true + } + if ah == "localhost" { + ah = "127.0.0.1" + } + if bh == "localhost" { + bh = "127.0.0.1" + } + ai, bi := net.ParseIP(ah), net.ParseIP(bh) + return ai != nil && bi != nil && (ai.Equal(bi) || ai.IsUnspecified() || bi.IsUnspecified()) +} + +// EnsureDeviceID is called only when starting a client, never by check/show. +func (c *Config) EnsureDeviceID() error { + if c.DeviceID != "" { + return nil + } + id, e := GenerateDeviceID() + if e != nil { + return e + } + p := filepath.Join(c.Directory, "device_id") + if e = storage.CreateExclusive(p, []byte(id+"\n")); errors.Is(e, os.ErrExist) { + b, e := os.ReadFile(p) + if e != nil { + return e + } + id = strings.TrimSpace(string(b)) + } else if e != nil { + return e + } + if !isUpperHex32(id) { + return errors.New("invalid persisted device ID") + } + c.DeviceID = id + return nil +} + +// Migration writes only a new config. Credentials, device IDs and old encrypted caches are preserved. +func Migration(path string) ([]byte, error) { + c, e := Load(path) + if e != nil { + return nil, e + } + if c.Version == 2 { + return os.ReadFile(path) + } + if c.CompatibilityExplicit && (c.Compatibility.ProcessIdentity != nil || len(c.Compatibility.FallbackGateways) > 0 || c.Compatibility.TCPToL3Fallback || c.Compatibility.MissingGatewayGroupFallback) { + return nil, errors.New("explicit legacy protocol/fallback settings require manual migration; keep the original configuration") + } + if len(c.Gateways) > 0 { + return nil, errors.New("legacy gateways override cannot be converted automatically; select permitted gateway filters explicitly") + } + var f FileV2 + f.Version = 2 + f.Controller.URL = c.BaseURL + if c.Compatibility.GatewayServerName == "" && c.Compatibility.FallbackAppID == "" && !c.Compatibility.TCPToL3Fallback && !c.Compatibility.MissingGatewayGroupFallback { + f.Controller.Deployment = "generic" + } + f.Controller.Platform = c.Platform + f.Auth.Mode = c.ClientType + f.Auth.DeviceID = c.DeviceID + f.Auth.LoginDomain = c.LoginDomain + f.Auth.Passkey.Keystore, e = filepath.Abs(c.Keystore) + if e != nil { + return nil, e + } + f.Storage.LegacyState, e = filepath.Abs(c.StateFile) + if e != nil { + return nil, e + } + f.Proxy.SOCKS5.Listen = c.Inbound.SOCKS5.Listen + if !c.Inbound.SOCKS5.Enabled { + f.Proxy.SOCKS5.Listen = "" + } + f.Proxy.HTTP.Listen = c.Inbound.HTTP.Listen + if !c.Inbound.HTTP.Enabled { + f.Proxy.HTTP.Listen = "" + } + f.Web.Listen = c.Web.Listen + if !c.WebEnabled() { + f.Web.Listen = "" + } + f.DNS.Strategy = "auto" + f.DNS.Servers = c.DNS + f.Logging.Level = c.LogLevel + f.Routing.FallbackAppID = c.AppID + f.TLS.Gateway.ServerName = c.Compatibility.GatewayServerName + var b bytes.Buffer + e = toml.NewEncoder(&b).Encode(f) + return b.Bytes(), e +} diff --git a/internal/config/v2_test.go b/internal/config/v2_test.go new file mode 100644 index 0000000..fb53b6c --- /dev/null +++ b/internal/config/v2_test.go @@ -0,0 +1,62 @@ +package config + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestV2MinimalAndReadOnly(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "config.toml") + data := "config_version = 2\n[controller]\ndeployment='auto'\n[auth.passkey]\nkeystore = './credential'\n[storage]\ndirectory = './private'\n" + if e := os.WriteFile(p, []byte(data), 0600); e != nil { + t.Fatal(e) + } + c, e := Load(p) + if e != nil { + t.Fatal(e) + } + if c.Keystore != filepath.Join(dir, "credential") || c.DeviceID != "" || c.GatewayServerName() != "vpn.shanghaitech.edu.cn" { + t.Fatal("minimal v2 defaults incorrect") + } + if _, e = os.Stat(c.Directory); !os.IsNotExist(e) { + t.Fatal("loading created storage") + } + if e = c.EnsureDeviceID(); e != nil { + t.Fatal(e) + } + id := c.DeviceID + c2, e := Load(p) + if e != nil || c2.DeviceID != id { + t.Fatal("persistent identity changed") + } + b, _ := os.ReadFile(p) + if string(b) != data { + t.Fatal("loader rewrote source") + } +} +func TestV2StrictAndLegacyMigration(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "config.toml") + for _, data := range []string{"config_version = 3", "config_version = 2\nkeystore='old'", "config_version=2\n[auth.passkey]\nkeystore='x'\n[web]\ntypo=true"} { + os.WriteFile(p, []byte(data), 0600) + if _, e := Load(p); e == nil { + t.Fatal("invalid v2 accepted") + } + } + old := "keystore='credential'\ndevice_id='0123456789ABCDEF0123456789ABCDEF'\nclient_type='browser'\napp_id='custom'\nunknown_old_key=true\n" + os.WriteFile(p, []byte(old), 0600) + b, e := Migration(p) + if e != nil { + t.Fatal(e) + } + if !strings.Contains(string(b), "0123456789ABCDEF0123456789ABCDEF") || !strings.Contains(string(b), "browser") || !strings.Contains(string(b), "custom") { + t.Fatal("migration lost existing semantics") + } + os.WriteFile(p, []byte(old+"gateways=['other:441']\n"), 0600) + if _, e = Migration(p); e == nil { + t.Fatal("legacy override silently converted") + } +} diff --git a/internal/deployment/profile.go b/internal/deployment/profile.go new file mode 100644 index 0000000..c64be4f --- /dev/null +++ b/internal/deployment/profile.go @@ -0,0 +1,56 @@ +// Package deployment owns the verified defaults for known controllers. +package deployment + +import ( + public "github.com/ShanghaitechGeekPie/geektrust/deployment" + "github.com/ShanghaitechGeekPie/geektrust/internal/settings" + "net/url" + "strings" +) + +type Resolved struct { + Profile public.Profile + Compatibility settings.Compatibility + Platform, LoginDomain string +} + +func Resolve(origin string, o public.Options) Resolved { + p := o.Profile + if p == public.Auto { + u, _ := url.Parse(origin) + p = public.Generic + if u != nil { + switch strings.ToLower(u.Host) { + case "vpn.shanghaitech.edu.cn", "vpn.shanghaitech.edu.cn:443": + p = public.ShanghaiTech + case "vpn.ecnu.edu.cn", "vpn.ecnu.edu.cn:443": + p = public.ECNU + } + } + } + v := Resolved{Profile: p, Platform: "Mac"} + if p == public.ShanghaiTech { + v = shanghaiTechProfile() + } + if o.Protocol.ControllerPlatform != "" { + v.Platform = o.Protocol.ControllerPlatform + } + if x := o.Protocol.Process; x != nil { + v.Compatibility.ProcessIdentity = &settings.ProcessIdentity{Name: x.Name, Platform: x.Platform, Path: x.Path} + } + if f := o.Fallbacks; f != nil { + v.Compatibility.FallbackAppID = f.ApplicationID + v.Compatibility.FallbackGateways = append([]string(nil), f.Gateways...) + v.Compatibility.MissingGatewayGroupFallback = f.MissingGatewayGroup + v.Compatibility.TCPToL3Fallback = f.StreamToL3 + } + return v +} + +// DomainAddress preserves the known single-school mapping, never a generic protocol assumption. +func DomainAddress(origin, ip string) string { + if Resolve(origin, public.Options{}).Profile == public.ShanghaiTech { + return ip + } + return "" +} diff --git a/internal/deployment/shanghaitech.go b/internal/deployment/shanghaitech.go new file mode 100644 index 0000000..6cc75e4 --- /dev/null +++ b/internal/deployment/shanghaitech.go @@ -0,0 +1,11 @@ +package deployment + +import ( + public "github.com/ShanghaitechGeekPie/geektrust/deployment" + "github.com/ShanghaitechGeekPie/geektrust/internal/settings" +) + +// Preserve the existing deployment's missing-information fallbacks, after server policy. +func shanghaiTechProfile() Resolved { + return Resolved{Profile: public.ShanghaiTech, Platform: "Mac", LoginDomain: "Shanghaitech.edu.cn", Compatibility: settings.Compatibility{GatewayServerName: "vpn.shanghaitech.edu.cn", FallbackAppID: "681165d0-1c77-11ed-8650-cd35a51aa42a", FallbackGateways: []string{"119.78.254.241:441", "59.78.171.241:441"}, MissingGatewayGroupFallback: true, TCPToL3Fallback: true}} +} diff --git a/internal/idsauth/ecnu_test.go b/internal/idsauth/ecnu_test.go index a9dab50..9d903c7 100644 --- a/internal/idsauth/ecnu_test.go +++ b/internal/idsauth/ecnu_test.go @@ -45,6 +45,9 @@ func TestECNUCredentialPersistence(t *testing.T) { // TestECNULiveLogin is opt-in and never logs credentials or server payloads. // The credential counter is durably updated; do not run another signer concurrently. func TestECNULiveLogin(t *testing.T) { + if os.Getenv("GEEKTRUST_LIVE_TESTS") != "1" { + t.Skip("online tests require explicit GEEKTRUST_LIVE_TESTS=1") + } path := os.Getenv("GEEKTRUST_ECNU_KEYSTORE") if path == "" { t.Skip("explicit live credential required") diff --git a/internal/idsauth/keystore.go b/internal/idsauth/keystore.go index 86f9558..7824153 100644 --- a/internal/idsauth/keystore.go +++ b/internal/idsauth/keystore.go @@ -10,9 +10,8 @@ import ( "io" "net/url" "os" - "path/filepath" - "github.com/ShanghaitechGeekPie/geektrust/internal/privatefile" + "github.com/ShanghaitechGeekPie/geektrust/internal/storage" ) // keystoreMagic prefixes every default-format keystore file @@ -244,31 +243,5 @@ func marshalNoEscape(v any) ([]byte, error) { // writeFileAtomic writes data to a temp file in the same directory and renames // it over path, so a crash never leaves a half-written secret file. func writeFileAtomic(path string, data []byte, perm os.FileMode) error { - dir := filepath.Dir(path) - tmp, err := os.CreateTemp(dir, ".keystore-*.tmp") - if err != nil { - return err - } - tmpName := tmp.Name() - defer os.Remove(tmpName) - if err := privatefile.Protect(tmpName); err != nil { - tmp.Close() - return err - } - if _, err := tmp.Write(data); err != nil { - tmp.Close() - return err - } - if err := tmp.Chmod(perm); err != nil { - tmp.Close() - return err - } - if err := tmp.Sync(); err != nil { - tmp.Close() - return err - } - if err := tmp.Close(); err != nil { - return err - } - return os.Rename(tmpName, path) + return storage.WriteAtomic(path, data, perm) } diff --git a/internal/inbound/http.go b/internal/inbound/http.go index 1429334..16f65cd 100644 --- a/internal/inbound/http.go +++ b/internal/inbound/http.go @@ -81,7 +81,7 @@ func (s *Server) handleHTTPConnectTCP(ctx context.Context, client net.Conn, br * writeHTTPStatus(client, http.StatusBadGateway, "host not resolvable") return } - upstream, err := s.dialer.Dial(setupCtx, target.IP, port, target.AppID, target.Domain) + upstream, err := s.dialTarget(setupCtx, target, port, "tcp") if err != nil { s.logger.Warn("http dial failed", "host", host, "err", err) writeHTTPStatus(client, http.StatusBadGateway, "tunnel dial failed") diff --git a/internal/inbound/server.go b/internal/inbound/server.go index a515b2f..a49ae77 100644 --- a/internal/inbound/server.go +++ b/internal/inbound/server.go @@ -269,3 +269,15 @@ drain: } } } + +func (s *Server) dialTarget(ctx context.Context, t resolver.Resolution, p int, n string) (net.Conn, error) { + if d, ok := s.dialer.(interface { + DialResolved(context.Context, resolver.Resolution, int, string) (net.Conn, error) + }); ok { + return d.DialResolved(ctx, t, p, n) + } + if n == "udp" { + return s.dialer.DialUDP(ctx, t.IP, p, t.AppID, t.Domain) + } + return s.dialer.Dial(ctx, t.IP, p, t.AppID, t.Domain) +} diff --git a/internal/inbound/socks5.go b/internal/inbound/socks5.go index d2c1f34..8b95e1a 100644 --- a/internal/inbound/socks5.go +++ b/internal/inbound/socks5.go @@ -115,7 +115,7 @@ func (s *Server) handleSOCKSConnect(ctx context.Context, client net.Conn, destin return } - upstream, err := s.dialer.Dial(setupCtx, target.IP, destination.port, target.AppID, target.Domain) + upstream, err := s.dialTarget(setupCtx, target, destination.port, "tcp") if err != nil { s.logger.Warn("socks5 dial failed", "target", net.JoinHostPort(target.IP, strconv.Itoa(destination.port)), "err", err) _ = writeSOCKSReply(client, socksReplyRefused, socksAddress{}) diff --git a/internal/l3/auth.go b/internal/l3/auth.go index d0908b2..4d064ae 100644 --- a/internal/l3/auth.go +++ b/internal/l3/auth.go @@ -8,7 +8,7 @@ import ( "net" "time" - "github.com/ShanghaitechGeekPie/geektrust/deployment" + "github.com/ShanghaitechGeekPie/geektrust/internal/settings" ) const ( @@ -72,7 +72,7 @@ var procFingerprint = fmt.Sprintf("%X", sha256.Sum256([]byte(procPath))) // buildAuthRequestIP serializes a per-flow auth body. domain is the original // hostname for wildcard-authorized targets (empty otherwise). -func buildAuthRequestIP(sid, appID, deviceID, dstIP string, dstPort int, vip net.IP, srcPort uint16, conntrackHash uint64, domain string, protocol int, identity *deployment.ProcessIdentity) ([]byte, error) { +func buildAuthRequestIP(sid, appID, deviceID, dstIP string, dstPort int, vip net.IP, srcPort uint16, conntrackHash uint64, domain string, protocol int, identity *settings.ProcessIdentity) ([]byte, error) { network, err := protocolName(protocol) if err != nil { return nil, err diff --git a/internal/l3/auth_test.go b/internal/l3/auth_test.go index 2752792..d995b04 100644 --- a/internal/l3/auth_test.go +++ b/internal/l3/auth_test.go @@ -9,7 +9,7 @@ import ( "strings" "testing" - "github.com/ShanghaitechGeekPie/geektrust/deployment" + "github.com/ShanghaitechGeekPie/geektrust/internal/settings" ) func TestBuildAuthRequestIPShape(t *testing.T) { @@ -165,7 +165,7 @@ func TestBuildAuthRequestICMP(t *testing.T) { } func TestConfiguredProcessIdentity(t *testing.T) { - identity := &deployment.ProcessIdentity{Name: "custom-client", Platform: "Windows", Path: "custom-client.exe"} + identity := &settings.ProcessIdentity{Name: "custom-client", Platform: "Windows", Path: "custom-client.exe"} body, err := buildAuthRequestIP("sid", "app", "device", "192.0.2.1", 443, net.IPv4(10, 0, 0, 1), 30000, 1, "", protocolTCP, identity) if err != nil { t.Fatal(err) diff --git a/internal/l3/fallback_stage_test.go b/internal/l3/fallback_stage_test.go new file mode 100644 index 0000000..277e35f --- /dev/null +++ b/internal/l3/fallback_stage_test.go @@ -0,0 +1,54 @@ +package l3 + +import ( + "context" + "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" + "github.com/ShanghaitechGeekPie/geektrust/internal/tunnel" + "io" + "log/slog" + "net" + "sync/atomic" + "testing" + "time" +) + +type fallbackStageProvider struct{ cred *session.Credential } + +func (p fallbackStageProvider) Credential(context.Context) (*session.Credential, error) { + return p.cred, nil +} +func (p fallbackStageProvider) InvalidateIfCurrent(*session.Credential) bool { return false } +func TestTLSClosingDoesNotAttemptL3Fallback(t *testing.T) { + ln, e := net.Listen("tcp", "127.0.0.1:0") + if e != nil { + t.Fatal(e) + } + defer ln.Close() + var calls atomic.Int32 + go func() { + for { + c, e := ln.Accept() + if e != nil { + return + } + calls.Add(1) + c.Close() + } + }() + addr := ln.Addr().String() + p := fallbackStageProvider{&session.Credential{SID: "fixture", AppID: "app", DeviceID: "id", AllowTCPFallback: true, Gateways: []string{addr}, Policy: &sdpc.Resource{Gateways: []string{addr}}}} + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + m := tunnel.NewManager(p, logger) + m.MaxAttempts = 1 + defer m.Close() + d := &Dialer{Manager: m, Provider: p, Logger: logger} + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + if _, e = d.Dial(ctx, "192.0.2.1", 443, "app", ""); e == nil { + t.Fatal("TLS close accepted") + } + if calls.Load() != 1 { + t.Fatalf("TLS failure triggered another protocol attempt: %d", calls.Load()) + } +} diff --git a/internal/privatefile/permissions.go b/internal/privatefile/permissions.go index 08d8208..5df4b7e 100644 --- a/internal/privatefile/permissions.go +++ b/internal/privatefile/permissions.go @@ -1,34 +1,2 @@ -// Package privatefile checks credential paths and protects files containing secrets. +// Package privatefile protects new secret files; it does not audit user directories. package privatefile - -import ( - "errors" - "fmt" - "os" - "path/filepath" -) - -// CheckParents checks the nearest existing directory and every ancestor. -func CheckParents(path string) error { - dir := filepath.Dir(path) - nearest := true - for { - info, err := os.Stat(dir) - if err == nil { - if !info.IsDir() { - return fmt.Errorf("parent %s is not a directory", dir) - } - if err := checkDirectory(dir, info, nearest); err != nil { - return fmt.Errorf("directory ancestor %s: %w", dir, err) - } - nearest = false - } else if !errors.Is(err, os.ErrNotExist) { - return fmt.Errorf("inspect directory: %w", err) - } - parent := filepath.Dir(dir) - if parent == dir { - return nil - } - dir = parent - } -} diff --git a/internal/privatefile/permissions_unix.go b/internal/privatefile/permissions_unix.go index f9087c3..fe8a862 100644 --- a/internal/privatefile/permissions_unix.go +++ b/internal/privatefile/permissions_unix.go @@ -3,23 +3,9 @@ package privatefile import ( - "errors" "os" "path/filepath" ) -func checkDirectory(_ string, info os.FileInfo, _ bool) error { - // A directory entry can be replaced by anyone who can write its parent. - if info.Mode().Perm()&0o022 != 0 && info.Mode()&os.ModeSticky == 0 { - return errors.New("directory is writable by other users") - } - return nil -} - -// CheckFile retains the Unix behavior; Protect applies the private file mode. -func CheckFile(_ string) error { return nil } - -// ResolveExistingPath resolves aliases in an existing path. func ResolveExistingPath(path string) (string, error) { return filepath.EvalSymlinks(path) } - -func Protect(path string) error { return os.Chmod(path, 0o600) } +func Protect(path string) error { return os.Chmod(path, 0600) } diff --git a/internal/privatefile/permissions_windows.go b/internal/privatefile/permissions_windows.go index eb5c4f4..651946d 100644 --- a/internal/privatefile/permissions_windows.go +++ b/internal/privatefile/permissions_windows.go @@ -1,209 +1,11 @@ package privatefile import ( - "fmt" - "os" - "path/filepath" - "runtime" - "sync" - "unsafe" - "golang.org/x/sys/windows" + "path/filepath" ) -type windowsInitObject uint8 - -const ( - windowsInitAncestor windowsInitObject = iota - windowsInitParent - windowsInitFile -) - -var windowsTrustedInstallerSID = sync.OnceValue(func() *windows.SID { - // Resolve the local service identity once; failure does not grant trust. - sid, _, _, _ := windows.LookupSID("", `NT SERVICE\TrustedInstaller`) - return sid -}) - -// Resolve junctions as well as symbolic links using the opened target. Go's -// EvalSymlinks does not traverse junctions with the current winsymlink default. -// Keep the native extended path prefix for subsequent Windows file operations. -func ResolveExistingPath(path string) (string, error) { - pathPtr, err := windows.UTF16PtrFromString(path) - if err != nil { - return "", err - } - handle, err := windows.CreateFile(pathPtr, 0, - windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, - nil, windows.OPEN_EXISTING, windows.FILE_FLAG_BACKUP_SEMANTICS, 0) - if err != nil { - return "", err - } - defer windows.CloseHandle(handle) - buffer := make([]uint16, 512) - for { - // Flags 0 request FILE_NAME_NORMALIZED | VOLUME_NAME_DOS. - n, err := windows.GetFinalPathNameByHandle(handle, &buffer[0], uint32(len(buffer)), 0) - if err != nil { - return "", err - } - if n < uint32(len(buffer)) { - return windows.UTF16ToString(buffer[:n]), nil - } - buffer = make([]uint16, n+1) - } -} - -// Directory write bits returned by os.Stat on Windows are synthesized from -// FILE_ATTRIBUTE_READONLY, not the DACL. Use the actual security descriptor. -func checkDirectory(dir string, _ os.FileInfo, nearest bool) error { - kind := windowsInitAncestor - if nearest { - kind = windowsInitParent - } - return validateWindowsInitPath(dir, kind) -} - -// CheckFile checks ownership and access to an existing credential or config file. -func CheckFile(path string) error { return validateWindowsInitPath(path, windowsInitFile) } - -func validateWindowsInitPath(path string, kind windowsInitObject) error { - return validateWindowsInitPathDepth(path, kind, 0) -} - -func validateWindowsInitPathDepth(path string, kind windowsInitObject, depth int) error { - if depth > 64 { - return fmt.Errorf("too many Windows reparse targets") - } - user, err := windows.GetCurrentProcessToken().GetTokenUser() - if err != nil { - return fmt.Errorf("read current user SID: %w", err) - } - pathPtr, err := windows.UTF16PtrFromString(path) - if err != nil { - return err - } - // Inspect the link/junction itself as well as its resolved target (the - // caller checks both paths), including DELETE access on the link itself. - handle, err := windows.CreateFile(pathPtr, windows.READ_CONTROL, - windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, - nil, windows.OPEN_EXISTING, windows.FILE_FLAG_BACKUP_SEMANTICS|windows.FILE_FLAG_OPEN_REPARSE_POINT, 0) - if err != nil { - return fmt.Errorf("open Windows security descriptor: %w", err) - } - defer windows.CloseHandle(handle) - sd, err := windows.GetSecurityInfo(handle, windows.SE_FILE_OBJECT, - windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION) - if err != nil { - return fmt.Errorf("read Windows ACL: %w", err) - } - // TrustedInstaller owns some system ancestors. Do not trust arbitrary - // service accounts or groups merely because the current user belongs to them. - if err := checkWindowsInitSecurity(sd, user.User.Sid, windowsTrustedInstallerSID(), kind); err != nil { - return err - } - var info windows.ByHandleFileInformation - if err := windows.GetFileInformationByHandle(handle, &info); err != nil { - return fmt.Errorf("inspect Windows reparse attributes: %w", err) - } - if info.FileAttributes&windows.FILE_ATTRIBUTE_REPARSE_POINT == 0 { - return nil - } - // The final normalized path omits intermediate links in A -> B -> C. - // Check each first-hop target and its ancestors too, or someone who can - // replace B could redirect an otherwise protected A and C after validation. - target, err := os.Readlink(path) - if err != nil { - return fmt.Errorf("inspect Windows reparse target: %w", err) - } - if !filepath.IsAbs(target) { - target = filepath.Join(filepath.Dir(path), target) - } - if err := validateWindowsInitPathDepth(target, kind, depth+1); err != nil { - return fmt.Errorf("reparse target %s: %w", target, err) - } - for dir := filepath.Dir(target); ; dir = filepath.Dir(dir) { - if err := validateWindowsInitPathDepth(dir, windowsInitAncestor, depth+1); err != nil { - return fmt.Errorf("reparse target ancestor %s: %w", dir, err) - } - if filepath.Dir(dir) == dir { - return nil - } - } -} - -func checkWindowsInitSecurity(sd *windows.SECURITY_DESCRIPTOR, user, installer *windows.SID, kind windowsInitObject) error { - // ACL and ACE pointers refer into sd's backing allocation. - defer runtime.KeepAlive(sd) - trusted := func(sid *windows.SID) bool { - return sid != nil && (sid.Equals(user) || sid.IsWellKnown(windows.WinLocalSystemSid) || - sid.IsWellKnown(windows.WinBuiltinAdministratorsSid) || (installer != nil && sid.Equals(installer))) - } - owner, _, err := sd.Owner() - if err != nil { - return fmt.Errorf("read Windows owner: %w", err) - } - if !trusted(owner) { - return fmt.Errorf("Windows owner is not the current user, SYSTEM, Administrators or TrustedInstaller") - } - dacl, _, err := sd.DACL() - if err != nil { - return fmt.Errorf("read Windows DACL: %w", err) - } - if dacl == nil { - return fmt.Errorf("Windows DACL is null (unrestricted access)") - } - // Higher ancestors may allow users to create unrelated siblings (e.g. - // C:\). That does not let them replace an existing protected child. - const fileDeleteChild = 0x40 // FILE_DELETE_CHILD (WinNT.h) - const replace = windows.DELETE | windows.WRITE_DAC | windows.WRITE_OWNER | - fileDeleteChild | windows.FILE_WRITE_ATTRIBUTES | windows.FILE_WRITE_EA | - windows.GENERIC_ALL | windows.GENERIC_WRITE - const write = replace | windows.FILE_WRITE_DATA | windows.FILE_APPEND_DATA - const private = write | windows.FILE_READ_DATA | windows.FILE_EXECUTE | windows.GENERIC_READ | windows.GENERIC_EXECUTE - for i := uint32(0); i < uint32(dacl.AceCount); i++ { - var ace *windows.ACCESS_ALLOWED_ACE - if err := windows.GetAce(dacl, i, &ace); err != nil { - return fmt.Errorf("read Windows ACE: %w", err) - } - // Denies can only reduce access. Ignoring them is conservative: a - // broad allow plus deny may be rejected, never silently accepted. - if ace.Header.AceType == windows.ACCESS_DENIED_ACE_TYPE { - continue - } - if ace.Header.AceType != windows.ACCESS_ALLOWED_ACE_TYPE { - return fmt.Errorf("unsupported Windows ACE type %d", ace.Header.AceType) - } - sid := (*windows.SID)(unsafe.Pointer(&ace.SidStart)) - if trusted(sid) { - continue - } - mask := uint32(ace.Mask) - flags := ace.Header.AceFlags - if flags&windows.INHERIT_ONLY_ACE == 0 { - dangerous := uint32(replace) - if kind == windowsInitParent { - dangerous = write - } else if kind == windowsInitFile { - dangerous = private - } - if mask&dangerous != 0 { - return fmt.Errorf("Windows ACL grants unsafe access to %s (mask %#x)", sid.String(), mask) - } - } - // Chmod(0600) does not protect Windows files. Reject inheritable - // grants that would expose newly created files or missing directories. - // CREATOR_OWNER becomes the creating user on those new objects. - if kind == windowsInitParent && flags&(windows.OBJECT_INHERIT_ACE|windows.CONTAINER_INHERIT_ACE) != 0 && - !sid.IsWellKnown(windows.WinCreatorOwnerSid) && mask&private != 0 { - return fmt.Errorf("Windows ACL would inherit unsafe access for %s (mask %#x)", sid.String(), mask) - } - } - return nil -} - -// Protect replaces inherited permissions with access for the current identity -// and LocalSystem. Call before writing any secret bytes into a new file. +func ResolveExistingPath(path string) (string, error) { return filepath.EvalSymlinks(path) } func Protect(path string) error { user, err := windows.GetCurrentProcessToken().GetTokenUser() if err != nil { diff --git a/internal/privatefile/permissions_windows_test.go b/internal/privatefile/permissions_windows_test.go deleted file mode 100644 index 5f5baaf..0000000 --- a/internal/privatefile/permissions_windows_test.go +++ /dev/null @@ -1,97 +0,0 @@ -package privatefile - -import ( - "os" - "path/filepath" - "strings" - "testing" - - "golang.org/x/sys/windows" -) - -func TestProtectedDACL(t *testing.T) { - path := filepath.Join(t.TempDir(), "secret") - if err := os.WriteFile(path, nil, 0o600); err != nil { - t.Fatal(err) - } - if err := Protect(path); err != nil { - t.Fatal(err) - } - sd, err := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION) - if err != nil { - t.Fatal(err) - } - sddl := sd.String() - if !strings.HasPrefix(sddl, "D:P") || strings.Count(sddl, "(A;") != 2 || strings.Contains(sddl, ";ID;") { - t.Fatalf("unexpected file ACL: %s", sddl) - } - if err := os.WriteFile(path, []byte("test"), 0o600); err != nil { - t.Fatal(err) - } -} - -func TestWindowsInitACLPolicy(t *testing.T) { - const userID = "S-1-5-21-1-2-3-1001" - user, err := windows.StringToSid(userID) - if err != nil { - t.Fatal(err) - } - tests := []struct { - name, acl string - kind windowsInitObject - reject bool - }{ - {"private parent", "(A;OICI;FA;;;" + userID + ")(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)", windowsInitParent, false}, - {"private file", "(A;;FA;;;" + userID + ")", windowsInitFile, false}, - {"ancestor sibling creation", "(A;;0x4;;;AU)(A;;FR;;;BU)", windowsInitAncestor, false}, - {"ancestor inherited only modify", "(A;OICIIO;FA;;;AU)", windowsInitAncestor, false}, - {"parent creation by others", "(A;;0x4;;;AU)", windowsInitParent, true}, - {"parent file creation by others", "(A;;0x2;;;WD)", windowsInitParent, true}, - {"parent list only", "(A;;FR;;;BU)", windowsInitParent, false}, - {"ancestor delete children", "(A;;0x40;;;WD)", windowsInitAncestor, true}, - {"ancestor delete self", "(A;;SD;;;WD)", windowsInitAncestor, true}, - {"ancestor change ACL", "(A;;WD;;;AU)", windowsInitAncestor, true}, - {"ancestor change owner", "(A;;WO;;;AU)", windowsInitAncestor, true}, - {"ancestor write attributes", "(A;;0x100;;;WD)", windowsInitAncestor, true}, - {"ancestor generic write", "(A;;GW;;;WD)", windowsInitAncestor, true}, - {"inherited read", "(A;OICI;FR;;;BU)", windowsInitParent, true}, - {"inherit only read", "(A;OIIO;FR;;;WD)", windowsInitParent, true}, - {"inherit only write", "(A;CIIO;FW;;;AU)", windowsInitParent, true}, - {"creator owner inheritance", "(A;OICIIO;GA;;;CO)", windowsInitParent, false}, - {"creator group inheritance", "(A;OICIIO;GA;;;CG)", windowsInitParent, true}, - {"existing file read", "(A;;FR;;;BU)", windowsInitFile, true}, - {"existing file write", "(A;;FW;;;AU)", windowsInitFile, true}, - {"existing file execute", "(A;;FX;;;BU)", windowsInitFile, true}, - {"unrecognized user write", "(A;;FA;;;S-1-5-21-1-2-3-1002)", windowsInitFile, true}, - {"deny cannot cancel broad allow in conservative policy", "(D;;FA;;;WD)(A;;FA;;;WD)", windowsInitFile, true}, - {"deny only", "(D;;FA;;;WD)", windowsInitFile, false}, - {"empty DACL", "", windowsInitFile, false}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - sd, err := windows.SecurityDescriptorFromString("O:" + userID + "D:P" + tt.acl) - if err != nil { - t.Fatal(err) - } - err = checkWindowsInitSecurity(sd, user, nil, tt.kind) - if (err != nil) != tt.reject { - t.Fatalf("reject=%v, error=%v", tt.reject, err) - } - }) - } - for _, sddl := range []string{ - "O:" + userID + "D:NO_ACCESS_CONTROL", - "O:S-1-5-21-1-2-3-1002D:P(A;;FA;;;" + userID + ")", - "O:" + userID + "D:P(XA;;FR;;;WD;(@User.Title == \"Manager\"))", - } { - t.Run(sddl, func(t *testing.T) { - sd, err := windows.SecurityDescriptorFromString(sddl) - if err != nil { - t.Fatal(err) - } - if err := checkWindowsInitSecurity(sd, user, nil, windowsInitFile); err == nil { - t.Fatal("unsafe or unsupported descriptor accepted") - } - }) - } -} diff --git a/internal/resolver/resolver.go b/internal/resolver/resolver.go index 22b616b..b50ac46 100644 --- a/internal/resolver/resolver.go +++ b/internal/resolver/resolver.go @@ -9,6 +9,7 @@ import ( "errors" "fmt" "net" + "net/netip" "strconv" "strings" "time" @@ -36,10 +37,13 @@ var DefaultPublicDNS = []string{"223.5.5.5", "119.29.29.29"} // Resolver resolves targets against the live credential's routing policy. type Resolver struct { - provider session.CredentialProvider - tunnel TunnelDialer - stages []lookupStage // direct public resolvers, then the system resolver - tunnelDNS *dnsPool + provider session.CredentialProvider + tunnel TunnelDialer + stages []lookupStage // direct public resolvers, then the system resolver + tunnelDNS *dnsPool + controllerFirst bool + disableTunnelDNS bool + fallback func(context.Context, string) ([]netip.Addr, error) } // New builds a Resolver. Controller-pushed or configured DNS servers are read @@ -78,8 +82,10 @@ func NewWithDialerOptions(provider session.CredentialProvider, tunnel TunnelDial // Resolution is a resolved dial target. type Resolution struct { - IP string - AppID string + Generation uint64 + Host string + IP string + AppID string // Domain carries the original hostname when the target is authorized // via a wildcard (suffix) rule: the gateway matches "*.com"-style // entries against the auth request's domain field, not the resolved IP. @@ -101,11 +107,17 @@ func (r *Resolver) ResolveUDP(ctx context.Context, host string, port int) (Resol // match → TLD suffix fallback. IP-policy matches carry no domain because the // gateway checks destAddr. Wildcard matches carry the original domain because // the gateway checks that field against its own DNS result. -func (r *Resolver) resolve(ctx context.Context, host string, port int, protocol string) (Resolution, error) { +func (r *Resolver) resolve(ctx context.Context, host string, port int, protocol string) (result Resolution, failure error) { cred, err := r.provider.Credential(ctx) if err != nil { return Resolution{}, err } + defer func() { + if failure == nil { + result.Generation = cred.Generation + result.Host = host + } + }() if isGatewayTarget(cred, host, nil, port) { return Resolution{}, fmt.Errorf("%w: %s", ErrGatewayLoop, net.JoinHostPort(host, strconv.Itoa(port))) } @@ -138,7 +150,7 @@ func (r *Resolver) resolve(ctx context.Context, host string, port int, protocol v4, err := r.lookupIPv4(ctx, host, cred) if err != nil { - return Resolution{}, fmt.Errorf("%w: %s: %v", ErrUnresolvable, host, err) + return Resolution{}, fmt.Errorf("%w: %s: %w", ErrUnresolvable, host, err) } if isGatewayTarget(cred, host, v4, port) { return Resolution{}, fmt.Errorf("%w: %s", ErrGatewayLoop, net.JoinHostPort(host, strconv.Itoa(port))) @@ -170,9 +182,9 @@ func (r *Resolver) lookupIPv4(ctx context.Context, host string, cred *session.Cr return nil, ctx.Err() } } - if r.tunnel != nil && len(cred.DNS) > 0 { + if r.tunnel != nil && !r.disableTunnelDNS && len(cred.DNS) > 0 { scope := r.tunnelDNSScope(cred) - return r.tunnelDNS.lookup(ctx, host, scope, cred.DNS, func(ctx context.Context, network, address string) (net.Conn, error) { + result, lookupErr := r.tunnelDNS.lookup(ctx, host, scope, cred.DNS, func(ctx context.Context, network, address string) (net.Conn, error) { server, _, err := net.SplitHostPort(address) if err != nil { return nil, err @@ -193,6 +205,25 @@ func (r *Resolver) lookupIPv4(ctx context.Context, host string, cred *session.Cr } return r.tunnel.DialUDP(ctx, ip.String(), 53, appID, "") }) + if lookupErr == nil { + return result, nil + } + var dnsErr *net.DNSError + if errors.Is(lookupErr, errNoIPv4Answer) || (errors.As(lookupErr, &dnsErr) && dnsErr.IsNotFound) { + return nil, lookupErr + } + lastErr = lookupErr + } + if r.fallback != nil && ctx.Err() == nil { + answers, err := r.fallback(ctx, host) + if err != nil { + return nil, err + } + for _, ip := range answers { + if ip.Is4() { + return net.IP(ip.AsSlice()), nil + } + } } return nil, lastErr } @@ -285,3 +316,8 @@ func (r *Resolver) LookupHost(ctx context.Context, host string) ([]string, error } return []string{ip.String()}, nil } + +// NewController uses only controller DNS, with an explicit host fallback. +func NewController(p session.CredentialProvider, t TunnelDialer, f func(context.Context, string) ([]netip.Addr, error), disabled bool) *Resolver { + return &Resolver{provider: p, tunnel: t, tunnelDNS: newDNSPool(), controllerFirst: true, disableTunnelDNS: disabled, fallback: f} +} diff --git a/client/client_test.go b/internal/runtime/client_test.go similarity index 87% rename from client/client_test.go rename to internal/runtime/client_test.go index b937a73..d29f8ba 100644 --- a/client/client_test.go +++ b/internal/runtime/client_test.go @@ -1,4 +1,4 @@ -package client +package runtime import ( "context" @@ -40,14 +40,14 @@ func (s *testGatewayPins) SavePin(ctx context.Context, addr string, pin []byte) func TestValidateOptions(t *testing.T) { for _, url := range []string{"http://vpn.example", "https://user:secret@vpn.example", "https://vpn.example/?token=x"} { - if _, err := New(Options{ControllerURL: url}); err == nil { + if _, err := newLegacy(legacyOptions{ControllerURL: url, DeviceID: "0123456789ABCDEF0123456789ABCDEF", Authenticator: AuthenticatorFunc(func(context.Context, *http.Client) (string, error) { return "", nil })}); err == nil { t.Fatal("invalid options accepted") } } } func TestClosedClient(t *testing.T) { id, _ := NewDeviceID() - c, err := New(Options{ControllerURL: "https://vpn.example", DeviceID: id, Authenticator: AuthenticatorFunc(func(context.Context, *http.Client) (string, error) { + c, err := newLegacy(legacyOptions{ControllerURL: "https://vpn.example", DeviceID: id, Authenticator: AuthenticatorFunc(func(context.Context, *http.Client) (string, error) { t.Error("closed client authenticated") return "", nil })}) @@ -71,24 +71,16 @@ func TestClosedClient(t *testing.T) { } } -func TestPasskeyWaitCancellation(t *testing.T) { - p := &PasskeyAuthenticator{} - p.once.Do(func() { p.gate = make(chan struct{}, 1) }) - p.gate <- struct{}{} - ctx, cancel := context.WithCancel(context.Background()) - cancel() - if _, err := p.Authenticate(ctx, nil); err != context.Canceled { - t.Fatalf("got %v", err) - } -} - func TestECNULiveAccess(t *testing.T) { + if os.Getenv("GEEKTRUST_LIVE_TESTS") != "1" { + t.Skip("online tests require explicit GEEKTRUST_LIVE_TESTS=1") + } path := os.Getenv("GEEKTRUST_ECNU_KEYSTORE") if path == "" { t.Skip("explicit live credential required") } id, _ := NewDeviceID() - c, err := New(Options{Logger: slog.New(stageHandler{t}), ControllerURL: "https://vpn.ecnu.edu.cn", DeviceID: id, GatewayTrustStore: &testGatewayPins{}, Authenticator: AuthenticatorFunc(func(ctx context.Context, h *http.Client) (string, error) { + c, err := newLegacy(legacyOptions{Logger: slog.New(stageHandler{t}), ControllerURL: "https://vpn.ecnu.edu.cn", DeviceID: id, GatewayTrustStore: &testGatewayPins{}, Authenticator: AuthenticatorFunc(func(ctx context.Context, h *http.Client) (string, error) { k, err := idsauth.LoadKeystore(path) if err != nil { return "", err @@ -208,7 +200,7 @@ func TestECNULiveAccess(t *testing.T) { } binary.BigEndian.PutUint16(packet[10:12], checksum(packet[:20])) binary.BigEndian.PutUint16(packet[22:24], checksum(packet[20:])) - reply, err := c.ExchangePacket(ctx, packet) + reply, err := c.ExchangeICMPEcho(ctx, packet) if err != nil { t.Fatalf("authorized ICMP exchange: %v", err) } diff --git a/internal/runtime/command.go b/internal/runtime/command.go new file mode 100644 index 0000000..d3ed888 --- /dev/null +++ b/internal/runtime/command.go @@ -0,0 +1,70 @@ +package runtime + +import ( + "context" + "github.com/ShanghaitechGeekPie/geektrust/internal/resolver" + "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" + "github.com/ShanghaitechGeekPie/geektrust/internal/settings" + "net" + "net/netip" + "strconv" +) + +// CLI hooks remain internal; the public facade does not expose protocol clients. +func (c *Runtime) Provider() *session.Provider { return c.provider } +func (c *Runtime) ConfigureCommand(s settings.Session, strategy string) { + if s.LegacyGatewayOverride && len(s.Gateways) > 0 { + c.provider.SetLegacyGateways(s.Gateways) + } + if strategy == "auto" { + c.resolver = resolver.New(c.provider, checkedDNSDialer{c}) + } + if strategy == "system" { + c.resolver = resolver.NewController(c.provider, checkedDNSDialer{c}, func(ctx context.Context, h string) ([]netip.Addr, error) { + v, e := net.DefaultResolver.LookupNetIP(ctx, "ip4", h) + return v, e + }, true) + } +} +func (c *Runtime) Resolve(ctx context.Context, h string, p int) (resolver.Resolution, error) { + v, e := c.resolver.Resolve(session.WithInteraction(ctx, false), h, p) + return v, e +} +func (c *Runtime) ResolveUDP(ctx context.Context, h string, p int) (resolver.Resolution, error) { + v, e := c.resolver.ResolveUDP(session.WithInteraction(ctx, false), h, p) + return v, e +} +func (c *Runtime) Dial(ctx context.Context, ip string, p int, app, domain string) (net.Conn, error) { + host := domain + if host == "" { + host = ip + } + return c.DialContext(ctx, "tcp", net.JoinHostPort(host, strconv.Itoa(p))) +} +func (c *Runtime) DialUDP(ctx context.Context, ip string, p int, app, domain string) (net.Conn, error) { + host := domain + if host == "" { + host = ip + } + return c.DialContext(ctx, "udp", net.JoinHostPort(host, strconv.Itoa(p))) +} +func (c *Runtime) ActiveSDPC() *sdpc.Client { return c.provider.ActiveSDPC() } +func (c *Runtime) TryForceRelogin() (func(context.Context), bool) { + run, ok := c.provider.TryForceRelogin() + if !ok { + return nil, false + } + return func(parent context.Context) { + ctx, done := c.withLifetime(parent) + defer done() + ctx = session.WithInteraction(ctx, true) + if c.prepare(ctx) != nil { + cancelled, cancel := context.WithCancel(ctx) + cancel() + run(cancelled) + return + } + run(ctx) + }, true +} diff --git a/client/compatibility_test.go b/internal/runtime/compatibility_test.go similarity index 58% rename from client/compatibility_test.go rename to internal/runtime/compatibility_test.go index 5382622..2f3ca39 100644 --- a/client/compatibility_test.go +++ b/internal/runtime/compatibility_test.go @@ -1,19 +1,17 @@ -package client +package runtime import ( "context" "crypto/tls" "errors" - "github.com/ShanghaitechGeekPie/geektrust/auth" "io" "net/http" - "net/url" "strings" "testing" "time" - "github.com/ShanghaitechGeekPie/geektrust/deployment" "github.com/ShanghaitechGeekPie/geektrust/internal/config" + "github.com/ShanghaitechGeekPie/geektrust/internal/settings" ) type compatibilityStore string @@ -37,17 +35,19 @@ func (compatibilityTransport) RoundTrip(r *http.Request) (*http.Response, error) func TestExplicitCompatibilityOptions(t *testing.T) { template := &tls.Config{} - options := Options{ - Compatibility: deployment.Compatibility{FallbackAppID: "custom-app", GatewayServerName: "gateway.example"}, + options := legacyOptions{ + Compatibility: settings.Compatibility{FallbackAppID: "custom-app", GatewayServerName: "gateway.example"}, LoginDomain: "custom-domain", ControllerURL: config.DefaultBaseURL, DeviceID: "0123456789ABCDEF0123456789ABCDEF", Gateways: []string{"override:441"}, DNS: []string{"10.0.0.53"}, GatewayTLSConfig: template, Transport: compatibilityTransport{}, - SessionStore: compatibilityStore(`{"sid":"synthetic-session","device_id":"0123456789ABCDEF0123456789ABCDEF","client_type":"browser","cookies":[{"name":"sid","value":"synthetic-session"}]}`), - Authenticator: AuthenticatorFunc(func(context.Context, *http.Client) (string, error) { return "", errors.New("unexpected full login") }), + SessionStore: compatibilityStore(`{"sid":"synthetic-session","device_id":"0123456789ABCDEF0123456789ABCDEF","client_type":"browser","cookies":[{"name":"sid","value":"synthetic-session"}]}`), + Authenticator: AuthenticatorFunc(func(context.Context, *http.Client) (string, error) { + return "", errors.New("unexpected full login") + }), } - c, err := New(options) + c, err := newLegacy(options) if err != nil { t.Fatal(err) } @@ -77,7 +77,7 @@ func TestAuthenticationUsesCallerDeadline(t *testing.T) { defer cancel() want, _ := parent.Deadline() called := false - c, err := New(Options{ControllerURL: config.DefaultBaseURL, DeviceID: "0123456789ABCDEF0123456789ABCDEF", Authenticator: AuthenticatorFunc(func(ctx context.Context, _ *http.Client) (string, error) { + c, err := newLegacy(legacyOptions{ControllerURL: config.DefaultBaseURL, DeviceID: "0123456789ABCDEF0123456789ABCDEF", Authenticator: AuthenticatorFunc(func(ctx context.Context, _ *http.Client) (string, error) { called = true got, ok := ctx.Deadline() if !ok || !got.Equal(want) { @@ -98,50 +98,18 @@ type controllerTransport func(*http.Request) (*http.Response, error) func (f controllerTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } -func TestCustomControllerLogin(t *testing.T) { - calls := 0 - transport := controllerTransport(func(r *http.Request) (*http.Response, error) { - if r.URL.Path == "/passport/v1/public/authConfig" { - return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"code":0,"data":{"security":{"csrfToken":"synthetic"},"authServerInfoList":[{"authType":"auth/cas","loginDomain":"a"},{"authType":"auth/cas","loginDomain":"b"}]}}`))}, nil - } - return (compatibilityTransport{}).RoundTrip(r) - }) - c, err := New(Options{ - ControllerURL: "https://controller.example", DeviceID: "0123456789ABCDEF0123456789ABCDEF", - Transport: transport, Compatibility: deployment.Compatibility{FallbackGateways: []string{"gateway.example:441"}}, - ControllerLogin: func(ctx context.Context, httpClient *http.Client, request auth.ControllerRequest) error { - calls++ - if request.URL != "https://controller.example" || request.LoginDomain != "" || request.CSRFToken != "synthetic" { - t.Fatal("custom authentication received implicit CAS configuration") - } - origin, _ := url.Parse(request.URL) - httpClient.Jar.SetCookies(origin, []*http.Cookie{{Name: "sid", Value: "synthetic"}}) - return nil - }, - }) - if err != nil { - t.Fatal(err) - } - defer c.Close() - info, err := c.Connect(context.Background()) - if err != nil || calls != 1 { - t.Fatalf("custom login calls=%d err=%v", calls, err) - } - if !info.Implemented.IPv4ICMP || info.Implemented.IPv6Targets || len(info.Resources) != 0 { - t.Fatal("implementation and authorization were conflated") - } -} - func TestRestoredSessionUsesCurrentCompatibility(t *testing.T) { state := compatibilityStore(`{"sid":"synthetic","device_id":"0123456789ABCDEF0123456789ABCDEF","client_type":"browser","cookies":[{"name":"sid","value":"synthetic"}],"gateways":["stale.example:441"]}`) for _, enabled := range []bool{true, false} { - options := Options{ControllerURL: config.DefaultBaseURL, DeviceID: "0123456789ABCDEF0123456789ABCDEF", Transport: compatibilityTransport{}, SessionStore: state, - Authenticator: AuthenticatorFunc(func(context.Context, *http.Client) (string, error) { return "", errors.New("synthetic no fresh login") }), + options := legacyOptions{ControllerURL: config.DefaultBaseURL, DeviceID: "0123456789ABCDEF0123456789ABCDEF", Transport: compatibilityTransport{}, SessionStore: state, + Authenticator: AuthenticatorFunc(func(context.Context, *http.Client) (string, error) { + return "", errors.New("synthetic no fresh login") + }), } if enabled { - options.Compatibility = deployment.Compatibility{FallbackAppID: "app", FallbackGateways: []string{"configured.example:441"}, TCPToL3Fallback: true} + options.Compatibility = settings.Compatibility{FallbackAppID: "app", FallbackGateways: []string{"configured.example:441"}, TCPToL3Fallback: true} } - c, err := New(options) + c, err := newLegacy(options) if err != nil { t.Fatal(err) } diff --git a/internal/runtime/contract_test.go b/internal/runtime/contract_test.go new file mode 100644 index 0000000..77dd98e --- /dev/null +++ b/internal/runtime/contract_test.go @@ -0,0 +1,202 @@ +package runtime + +import ( + "context" + "encoding/json" + "errors" + "github.com/ShanghaitechGeekPie/geektrust/auth" + "github.com/ShanghaitechGeekPie/geektrust/deployment" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" + "io" + "net/http" + "net/netip" + "strings" + "sync/atomic" + "testing" + "time" +) + +type contractIdentity struct { + calls atomic.Int32 + subject string +} + +func (i *contractIdentity) Info(context.Context) (auth.IdentityInfo, error) { + i.calls.Add(1) + return auth.IdentityInfo{Issuer: "fixture", Subject: i.subject, Kind: "passkey"}, nil +} +func (i *contractIdentity) Authenticate(context.Context, *http.Client, auth.IdentityRequest) error { + return errors.New("unexpected authentication") +} + +type contractStore struct { + state session.State + loads atomic.Int32 +} + +func (s *contractStore) Load(context.Context, SessionScope) ([]byte, error) { + s.loads.Add(1) + return json.Marshal(s.state) +} +func (s *contractStore) Save(context.Context, SessionScope, []byte) error { return nil } +func (s *contractStore) Delete(context.Context, SessionScope) error { return nil } +func contractOptions(id *contractIdentity, store *contractStore) Options { + return Options{ControllerURL: "https://controller.example", DeviceID: "0123456789ABCDEF0123456789ABCDEF", Auth: AuthOptions{Identity: id}, Deployment: deployment.Options{Profile: deployment.Generic, Fallbacks: &deployment.Fallbacks{ApplicationID: "app", Gateways: []string{"gateway.example:441"}}}, Network: NetworkOptions{ControlTransport: compatibilityTransport{}}, SessionStore: store} +} +func validState() session.State { + return session.State{Version: 1, ControllerURL: "https://controller.example", IdentityIssuer: "fixture", IdentitySubject: "account", IdentityKind: "passkey", DeviceID: "0123456789ABCDEF0123456789ABCDEF", ClientType: "browser", SID: "secret", Cookies: []session.CookieRecord{{Name: "sid", Value: "secret"}}} +} +func TestNewAndScopedRestore(t *testing.T) { + for _, wrong := range []bool{false, true} { + i := &contractIdentity{subject: "account"} + s := &contractStore{state: validState()} + if wrong { + s.state.ControllerURL = "https://other.example" + } + c, e := New(contractOptions(i, s)) + if e != nil { + t.Fatal(e) + } + if i.calls.Load() != 0 || s.loads.Load() != 0 { + t.Fatal("constructor performed I/O") + } + _, e = c.Connect(context.Background()) + if wrong && e == nil { + t.Fatal("foreign cache accepted") + } + if !wrong && e != nil { + t.Fatal(e) + } + c.Close() + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + if e = c.Shutdown(ctx); e != nil { + t.Fatal(e) + } + cancel() + } +} +func TestSubscribersAndIdentityChange(t *testing.T) { + i := &contractIdentity{subject: "account"} + s := &contractStore{state: validState()} + c, e := New(contractOptions(i, s)) + if e != nil { + t.Fatal(e) + } + defer c.Close() + ctx, cancel := context.WithCancel(context.Background()) + a := c.Subscribe(ctx) + b := c.Subscribe(context.Background()) + <-a + <-b + cancel() + if _, ok := <-a; ok { + t.Fatal("canceled subscriber remained open") + } + if _, e = c.Connect(context.Background()); e != nil { + t.Fatal(e) + } + select { + case <-b: + case <-time.After(time.Second): + t.Fatal("second subscriber was canceled") + } + i.subject = "another" + _, e = c.Connect(context.Background()) + var typed *Error + if !errors.As(e, &typed) || typed.Info.Kind != ErrorIdentityChanged { + t.Fatal("changed identity accepted") + } +} +func TestExplicitEmptyGatewayList(t *testing.T) { + i := &contractIdentity{subject: "account"} + s := &contractStore{state: validState()} + o := contractOptions(i, s) + o.Network.AllowedGateways = []string{} + c, e := New(o) + if e != nil { + t.Fatal(e) + } + defer c.Close() + if _, e = c.Connect(context.Background()); e == nil { + t.Fatal("empty allowed list used fallback gateways") + } +} +func TestDNSCallbackPurposeAndSafeErrors(t *testing.T) { + i := &contractIdentity{subject: "account"} + s := &contractStore{state: validState()} + o := contractOptions(i, s) + seen := false + o.CheckTarget = func(_ context.Context, target Target) error { + seen = target.Purpose == DNSQueryTarget && target.IP == netip.MustParseAddr("192.0.2.53") + return errors.New("do not expose ticket=secret") + } + c, e := New(o) + if e != nil { + t.Fatal(e) + } + defer c.Close() + e = (checkedDNSDialer{c}).check(context.Background(), "192.0.2.53", 53, "udp") + if !seen || e == nil { + t.Fatal("DNS target callback omitted") + } + wrapped := safeError("lookup", e) + if strings.Contains(wrapped.Error(), "secret") || strings.Contains(errors.Unwrap(wrapped).Error(), "secret") { + t.Fatal("error chain leaked secrets") + } +} + +type blockingIdentity struct { + entered chan struct{} + release chan struct{} +} + +func (i blockingIdentity) Info(context.Context) (auth.IdentityInfo, error) { + close(i.entered) + <-i.release + return auth.IdentityInfo{Issuer: "fixture", Subject: "account", Kind: "passkey"}, nil +} +func (i blockingIdentity) Authenticate(context.Context, *http.Client, auth.IdentityRequest) error { + return nil +} +func TestShutdownBoundsUncooperativeIdentity(t *testing.T) { + i := blockingIdentity{make(chan struct{}), make(chan struct{})} + o := contractOptions(&contractIdentity{subject: "account"}, &contractStore{state: validState()}) + o.Auth.Identity = i + c, e := New(o) + if e != nil { + t.Fatal(e) + } + done := make(chan error, 1) + go func() { _, e := c.Connect(context.Background()); done <- e }() + <-i.entered + c.Close() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + if e = c.Shutdown(ctx); !errors.Is(e, context.DeadlineExceeded) { + t.Fatal("shutdown did not honor deadline") + } + close(i.release) + if e = <-done; e == nil { + t.Fatal("late identity published a closed session") + } + if e = c.Shutdown(context.Background()); e != nil { + t.Fatal(e) + } +} + +func TestExpiredSessionReauthenticates(t *testing.T) { + i := &contractIdentity{subject: "account"} + s := &contractStore{state: validState()} + o := contractOptions(i, s) + o.Network.ControlTransport = controllerTransport(func(r *http.Request) (*http.Response, error) { + return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"code":0,"data":{"isOnline":false}}`))}, nil + }) + c, e := New(o) + if e != nil { + t.Fatal(e) + } + defer c.Close() + if _, e = c.Connect(context.Background()); e == nil || !strings.Contains(e.Error(), "unexpected authentication") { + t.Fatal("expired cached session blocked fresh authentication") + } +} diff --git a/internal/runtime/devices.go b/internal/runtime/devices.go new file mode 100644 index 0000000..bf245ea --- /dev/null +++ b/internal/runtime/devices.go @@ -0,0 +1,76 @@ +package runtime + +import ( + "context" + "errors" + "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" +) + +func (c *Runtime) controller(ctx context.Context) (*sdpc.Client, error) { + if e := c.prepare(ctx); e != nil { + return nil, e + } + if _, e := c.provider.Credential(ctx); e != nil { + return nil, e + } + sc := c.provider.ActiveSDPC() + if sc == nil { + return nil, errors.New("no active controller session") + } + return sc, nil +} +func (c *Runtime) TrustedDevices(parent context.Context) (TrustedDeviceList, error) { + ctx, done := c.operation(parent) + defer done() + sc, e := c.controller(ctx) + if e != nil { + return TrustedDeviceList{}, e + } + v, e := sc.QueryTrustDevice(ctx) + if e != nil { + return TrustedDeviceList{}, e + } + out := TrustedDeviceList{CurrentDeviceID: v.SelfID, CurrentTrustStatus: v.CurrentTrustStatus, TrustEnabled: v.Config.Enable} + for _, x := range v.Devices { + out.Devices = append(out.Devices, TrustedDevice{ID: x.ID, Name: x.DeviceName, Platform: x.DeviceType, OS: x.OS, OSVersion: x.OSVersion, LastLoginIP: x.LastLoginIP, LastLoginAddress: x.LastLoginAddress, NetworkZones: append([]string(nil), x.NetworkZoneList...), Online: x.OnlineStatus}) + } + return out, nil +} +func (c *Runtime) TrustCurrentDevice(parent context.Context) error { + ctx, done := c.operation(parent) + defer done() + sc, e := c.controller(ctx) + if e != nil { + return e + } + return sc.TrustDevice(ctx) +} +func (c *Runtime) UntrustDevices(parent context.Context, ids []string) error { + ctx, done := c.operation(parent) + defer done() + sc, e := c.controller(ctx) + if e != nil { + return e + } + return sc.UntrustDevice(ctx, ids) +} +func (c *Runtime) LogoutDevice(parent context.Context, id string) error { + ctx, done := c.operation(parent) + defer done() + list, e := c.TrustedDevices(ctx) + if e != nil { + return e + } + sc, e := c.controller(ctx) + if e != nil { + return e + } + if e = sc.LogoutDevice(ctx, id); e != nil { + return e + } + if id == list.CurrentDeviceID { + c.provider.Invalidate() + c.resetConnections() + } + return nil +} diff --git a/internal/runtime/dns.go b/internal/runtime/dns.go new file mode 100644 index 0000000..aa7f654 --- /dev/null +++ b/internal/runtime/dns.go @@ -0,0 +1,32 @@ +package runtime + +import ( + "context" + "net" + "net/netip" +) + +type checkedDNSDialer struct{ c *Runtime } + +func (d checkedDNSDialer) check(ctx context.Context, ip string, port int, network string) error { + if d.c.checkTarget == nil { + return nil + } + a, e := netip.ParseAddr(ip) + if e != nil { + return e + } + return d.c.checkTarget(ctx, Target{Generation: d.c.currentGeneration(), IP: a.Unmap(), Port: uint16(port), Network: network, Purpose: DNSQueryTarget}) +} +func (d checkedDNSDialer) Dial(ctx context.Context, ip string, port int, app, domain string) (net.Conn, error) { + if e := d.check(ctx, ip, port, "tcp"); e != nil { + return nil, e + } + return d.c.dialer.Dial(ctx, ip, port, app, domain) +} +func (d checkedDNSDialer) DialUDP(ctx context.Context, ip string, port int, app, domain string) (net.Conn, error) { + if e := d.check(ctx, ip, port, "udp"); e != nil { + return nil, e + } + return d.c.dialer.DialUDP(ctx, ip, port, app, domain) +} diff --git a/internal/runtime/legacy_test.go b/internal/runtime/legacy_test.go new file mode 100644 index 0000000..ffa1e60 --- /dev/null +++ b/internal/runtime/legacy_test.go @@ -0,0 +1,141 @@ +package runtime + +// These adapters migrate old regression fixtures to the new API; no legacy engine is used. +import ( + "context" + "crypto/tls" + "encoding/json" + "github.com/ShanghaitechGeekPie/geektrust/auth" + "github.com/ShanghaitechGeekPie/geektrust/deployment" + "github.com/ShanghaitechGeekPie/geektrust/internal/settings" + "log/slog" + "net" + "net/http" + "net/netip" +) + +type BlobStore interface { + Load(context.Context) ([]byte, error) + Save(context.Context, []byte) error +} +type AuthenticatorFunc func(context.Context, *http.Client) (string, error) + +func (f AuthenticatorFunc) Authenticate(c context.Context, h *http.Client) (string, error) { + return f(c, h) +} + +type legacyIdentity struct{ f AuthenticatorFunc } + +func (l legacyIdentity) Info(context.Context) (auth.IdentityInfo, error) { + return auth.IdentityInfo{Issuer: "fixture", Subject: "fixture", Kind: "fixture"}, nil +} +func (l legacyIdentity) Authenticate(c context.Context, h *http.Client, _ auth.IdentityRequest) error { + if l.f == nil { + return nil + } + _, e := l.f(c, h) + return e +} + +type legacyOptions struct { + CheckTarget func(netip.Addr) error + Compatibility settings.Compatibility + Gateways, DNS []string + ControllerURL, DeviceID, Platform, LoginDomain string + ClientMode bool + Authenticator AuthenticatorFunc + ChallengeHandler auth.Handler + SessionStore BlobStore + Transport http.RoundTripper + DialContext func(context.Context, string, string) (net.Conn, error) + DisableSystemResolver bool + GatewayTLSConfig *tls.Config + GatewayTrustStore interface { + LoadPin(context.Context, string) ([]byte, error) + SavePin(context.Context, string, []byte) error + } + Logger *slog.Logger +} +type fixtureSession struct{ old BlobStore } + +func (f fixtureSession) Load(ctx context.Context, s SessionScope) ([]byte, error) { + b, e := f.old.Load(ctx) + if e != nil || len(b) == 0 { + return b, e + } + var v map[string]any + if e = json.Unmarshal(b, &v); e != nil { + return nil, e + } + v["version"] = 1 + v["controller_url"] = s.ControllerURL + v["identity_issuer"] = s.IdentityIssuer + v["identity_subject"] = s.IdentitySubject + v["identity_kind"] = s.IdentityKind + v["login_domain"] = s.LoginDomain + return json.Marshal(v) +} +func (f fixtureSession) Save(c context.Context, _ SessionScope, b []byte) error { + return f.old.Save(c, b) +} +func (f fixtureSession) Delete(context.Context, SessionScope) error { return nil } + +type legacyPins struct { + old interface { + LoadPin(context.Context, string) ([]byte, error) + SavePin(context.Context, string, []byte) error + } +} + +func (p legacyPins) CheckOrEnroll(c context.Context, i GatewayIdentity, b [32]byte) (bool, error) { + v, e := p.old.LoadPin(c, i.Address) + if e != nil { + return false, e + } + if len(v) == 0 { + return true, p.old.SavePin(c, i.Address, b[:]) + } + return string(v) == string(b[:]), nil +} +func newLegacy(o legacyOptions) (*Runtime, error) { + opts := Options{ControllerURL: o.ControllerURL, DeviceID: o.DeviceID, Logger: o.Logger, Auth: AuthOptions{Identity: legacyIdentity{o.Authenticator}, LoginDomain: o.LoginDomain, OnChallenge: o.ChallengeHandler}, Deployment: deployment.Options{Profile: deployment.Generic, Protocol: deployment.ProtocolOptions{ControllerPlatform: o.Platform}, Fallbacks: &deployment.Fallbacks{ApplicationID: o.Compatibility.FallbackAppID, Gateways: append([]string(nil), o.Compatibility.FallbackGateways...), MissingGatewayGroup: o.Compatibility.MissingGatewayGroupFallback, StreamToL3: o.Compatibility.TCPToL3Fallback}}, Network: NetworkOptions{ControlTransport: o.Transport, DialContext: o.DialContext, GatewayTLS: GatewayTLSOptions{Config: o.GatewayTLSConfig}}} + if o.ClientMode { + opts.Auth.Mode = DesktopMode + } + if o.SessionStore != nil { + opts.SessionStore = fixtureSession{o.SessionStore} + } + if o.GatewayTrustStore != nil { + opts.Network.GatewayTLS.Mode = VerifyCAOrTOFU + opts.Network.GatewayTLS.PinStore = legacyPins{o.GatewayTrustStore} + } + if o.Compatibility.GatewayServerName != "" { + if opts.Network.GatewayTLS.Config == nil { + opts.Network.GatewayTLS.Config = &tls.Config{} + } else { + opts.Network.GatewayTLS.Config = opts.Network.GatewayTLS.Config.Clone() + } + opts.Network.GatewayTLS.Config.ServerName = o.Compatibility.GatewayServerName + } + if o.CheckTarget != nil { + opts.CheckTarget = func(_ context.Context, t Target) error { return o.CheckTarget(t.IP) } + } + if p := o.Compatibility.ProcessIdentity; p != nil { + opts.Deployment.Protocol.Process = &deployment.ProcessMetadata{Name: p.Name, Platform: p.Platform, Path: p.Path} + } + for _, s := range o.DNS { + a, e := netip.ParseAddr(s) + if e != nil { + return nil, e + } + opts.DNS.Servers = append(opts.DNS.Servers, a) + } + if len(o.Gateways) > 0 { + opts.Deployment.Fallbacks.Gateways = append([]string(nil), o.Gateways...) + } + c, e := New(opts) + if e == nil { + + } + return c, e +} diff --git a/internal/runtime/options.go b/internal/runtime/options.go new file mode 100644 index 0000000..9d9a9a1 --- /dev/null +++ b/internal/runtime/options.go @@ -0,0 +1,109 @@ +package runtime + +import ( + "context" + "crypto/tls" + "log/slog" + "net" + "net/http" + "net/netip" + "time" + + "github.com/ShanghaitechGeekPie/geektrust/auth" + "github.com/ShanghaitechGeekPie/geektrust/deployment" +) + +type Options struct { + ControllerURL string + DeviceID string + Deployment deployment.Options + Auth AuthOptions + SessionStore SessionStore + Network NetworkOptions + DNS DNSOptions + CheckTarget func(context.Context, Target) error + Logger *slog.Logger +} + +type AuthOptions struct { + Identity auth.IdentityProvider + OnChallenge auth.Handler + Mode SessionMode + LoginDomain string +} + +type SessionMode uint8 + +const ( + BrowserMode SessionMode = iota + DesktopMode +) + +type NetworkOptions struct { + DialContext func(context.Context, string, string) (net.Conn, error) + ControlTransport http.RoundTripper + GatewayTLS GatewayTLSOptions + AllowedGateways []string + DialTimeout time.Duration + HTTPTimeout time.Duration +} + +type GatewayTLSOptions struct { + Config *tls.Config + Mode GatewayTrustMode + PinStore GatewayPinStore +} + +type GatewayTrustMode uint8 + +const ( + VerifyCA GatewayTrustMode = iota + VerifyCAOrTOFU +) + +type GatewayIdentity struct { + ControllerURL string + Address string + ServerName string +} + +type GatewayPinStore interface { + CheckOrEnroll(context.Context, GatewayIdentity, [32]byte) (bool, error) +} + +type DNSOptions struct { + Servers []netip.Addr + FallbackLookup func(context.Context, string) ([]netip.Addr, error) +} + +type Target struct { + Generation uint64 + Network string + Host string + IP netip.Addr + Port uint16 + Purpose TargetPurpose +} + +type TargetPurpose uint8 + +const ( + ApplicationTarget TargetPurpose = iota + DNSQueryTarget +) + +type SessionScope struct { + ControllerURL string + IdentityIssuer string + IdentitySubject string + IdentityKind string + DeviceID string + Mode SessionMode + LoginDomain string +} + +type SessionStore interface { + Load(context.Context, SessionScope) ([]byte, error) + Save(context.Context, SessionScope, []byte) error + Delete(context.Context, SessionScope) error +} diff --git a/internal/runtime/packet.go b/internal/runtime/packet.go new file mode 100644 index 0000000..9d3682b --- /dev/null +++ b/internal/runtime/packet.go @@ -0,0 +1,28 @@ +package runtime + +import ( + "context" + "errors" + "net/netip" +) + +func (c *Runtime) ExchangeICMPEcho(parent context.Context, packet []byte) ([]byte, error) { + if c.isClosed() { + return nil, ErrClosed + } + ctx, done := c.operation(parent) + defer done() + if e := c.prepare(ctx); e != nil { + return nil, e + } + if c.checkTarget != nil { + if len(packet) < 20 || packet[0]>>4 != 4 { + return nil, errors.New("invalid IPv4 packet") + } + ip := netip.AddrFrom4([4]byte(packet[16:20])) + if err := c.checkTarget(ctx, Target{Generation: c.currentGeneration(), Network: "icmp", IP: ip}); err != nil { + return nil, err + } + } + return c.dialer.ExchangePacket(ctx, packet) +} diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go new file mode 100644 index 0000000..1d03c8f --- /dev/null +++ b/internal/runtime/runtime.go @@ -0,0 +1,510 @@ +package runtime + +import ( + "context" + "crypto/rand" + "crypto/tls" + "errors" + "fmt" + "io" + "log/slog" + "net" + "net/http" + "net/netip" + + "net/url" + "strconv" + "strings" + "sync" + "time" + + "github.com/ShanghaitechGeekPie/geektrust/auth" + "github.com/ShanghaitechGeekPie/geektrust/deployment" + defaults "github.com/ShanghaitechGeekPie/geektrust/internal/deployment" + "github.com/ShanghaitechGeekPie/geektrust/internal/settings" + + "github.com/ShanghaitechGeekPie/geektrust/internal/l3" + "github.com/ShanghaitechGeekPie/geektrust/internal/resolver" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" + "github.com/ShanghaitechGeekPie/geektrust/internal/tunnel" +) + +type Capabilities struct{ IPv4TCP, IPv4UDP, IPv4ICMPEcho, IPv6Targets, IPv6Gateway bool } +type Resource struct { + Address, Protocol, ApplicationID, GatewayGroup string + PortMin, PortMax int +} +type SessionInfo struct { + Gateways, DNS []string + Resources []Resource + Generation uint64 + Username, DisplayName string +} +type TransportInfo struct { + Generation uint64 + Gateway string + VirtualIPv4 string +} +type Event struct { + Time time.Time + Status Status +} + +var ErrClosed = errors.New("aTrust client closed") +var ErrDatagramTooLarge = errors.New("UDP datagram exceeds tunnel MTU") +var ErrDenied = errors.New("target is not authorized by controller policy") + +type Runtime struct { + ops sync.WaitGroup + shutdownDone chan struct{} + checkTarget func(context.Context, Target) error + provider *session.Provider + manager *tunnel.Manager + dialer *l3.Dialer + resolver *resolver.Resolver + ctx context.Context + cancel context.CancelFunc + mu sync.Mutex + closed bool + conns map[*ownedConn]struct{} + transport *http.Transport + subscribers map[uint64]chan Event + nextSubscriber uint64 + status Status + store SessionStore + generation uint64 + identity auth.IdentityProvider + scope SessionScope + identityMu sync.Mutex + identityReady bool + mode SessionMode + profile deployment.Profile + dialTimeout time.Duration + startOnce sync.Once + tasksDone chan struct{} + forgotten bool +} + +func New(opts Options) (*Runtime, error) { + u, err := url.Parse(opts.ControllerURL) + if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") { + return nil, errors.New("controller must be an HTTPS origin") + } + if len(opts.DeviceID) != 32 || strings.Trim(opts.DeviceID, "0123456789ABCDEF") != "" { + return nil, errors.New("persistent 32-character uppercase hexadecimal device ID required") + } + if opts.Auth.Identity == nil { + return nil, errors.New("identity provider required") + } + if opts.Auth.Mode != BrowserMode && opts.Auth.Mode != DesktopMode { + return nil, errors.New("invalid session mode") + } + if opts.Network.DialTimeout < 0 || opts.Network.HTTPTimeout < 0 { + return nil, errors.New("invalid network timeout") + } + if err := opts.Deployment.Validate(); err != nil { + return nil, err + } + if opts.Network.GatewayTLS.Mode != VerifyCA && opts.Network.GatewayTLS.Mode != VerifyCAOrTOFU { + return nil, errors.New("invalid gateway trust mode") + } + if (opts.Network.GatewayTLS.Mode == VerifyCAOrTOFU) != (opts.Network.GatewayTLS.PinStore != nil) { + return nil, errors.New("gateway pin store requires CA-or-TOFU mode") + } + if t := opts.Network.GatewayTLS.Config; t != nil && t.InsecureSkipVerify { + return nil, errors.New("gateway certificate verification cannot be disabled") + } + if opts.Logger == nil { + opts.Logger = slog.New(slog.NewTextHandler(io.Discard, nil)) + } + resolved := defaults.Resolve(opts.ControllerURL, opts.Deployment) + mode := "browser" + if opts.Auth.Mode == DesktopMode { + mode = "client" + } + u.Host = strings.ToLower(u.Host) + if u.Port() == "443" { + u.Host = u.Hostname() + if strings.Contains(u.Host, ":") { + u.Host = "[" + u.Host + "]" + } + } + u.Path = "" + u.RawPath = "" + cfg := settings.Session{BaseURL: u.String(), DeviceID: opts.DeviceID, Platform: resolved.Platform, LoginDomain: opts.Auth.LoginDomain, ClientType: mode, Compatibility: resolved.Compatibility, StrictStorage: true, GatewayFilter: opts.Network.AllowedGateways != nil} + if cfg.LoginDomain == "" { + cfg.LoginDomain = resolved.LoginDomain + } + for _, address := range opts.Network.AllowedGateways { + host, port, e := net.SplitHostPort(address) + n, x := strconv.Atoi(port) + if e != nil || x != nil || host == "" || n < 1 || n > 65535 { + return nil, errors.New("allowed gateway must be host:port") + } + } + if opts.Network.AllowedGateways != nil { + cfg.Gateways = append([]string{}, opts.Network.AllowedGateways...) + } + cfg.DNSConfigured = opts.DNS.Servers != nil + if opts.DNS.Servers != nil { + cfg.DNS = make([]string, len(opts.DNS.Servers)) + for i, x := range opts.DNS.Servers { + if !x.IsValid() { + return nil, errors.New("invalid DNS address") + } + cfg.DNS[i] = x.String() + } + } + mapDomains := resolved.Profile == deployment.ShanghaiTech + cfg.DomainMapping = &mapDomains + p := session.NewProvider(cfg, opts.Logger, nil) + p.ChallengeHandler = opts.Auth.OnChallenge + p.Transport = opts.Network.ControlTransport + var owned *http.Transport + if p.Transport == nil { + owned = http.DefaultTransport.(*http.Transport).Clone() + if opts.Network.DialContext != nil { + owned.DialContext = opts.Network.DialContext + } + p.Transport = owned + } + p.HTTPTimeout = opts.Network.HTTPTimeout + m := tunnel.NewManager(p, opts.Logger) + m.MaxAttempts = 3 + m.DialContext = opts.Network.DialContext + if t := opts.Network.GatewayTLS.Config; t != nil { + m.GatewayTLSConfig = t.Clone() + if t.RootCAs != nil { + m.GatewayTLSConfig.RootCAs = t.RootCAs.Clone() + } + } + if name := resolved.Compatibility.GatewayServerName; name != "" { + if m.GatewayTLSConfig == nil { + m.GatewayTLSConfig = &tls.Config{ServerName: name} + } else if m.GatewayTLSConfig.ServerName == "" { + m.GatewayTLSConfig.ServerName = name + } + } + if opts.Network.GatewayTLS.PinStore != nil { + m.GatewayTrustStore = pinAdapter{store: opts.Network.GatewayTLS.PinStore, controller: cfg.BaseURL, template: m.GatewayTLSConfig} + } + d := &l3.Dialer{Manager: m, Provider: p, Logger: opts.Logger} + ctx, cancel := context.WithCancel(context.Background()) + c := &Runtime{checkTarget: opts.CheckTarget, provider: p, manager: m, dialer: d, transport: owned, ctx: ctx, cancel: cancel, conns: make(map[*ownedConn]struct{}), store: opts.SessionStore, status: Status{State: Idle}, identity: opts.Auth.Identity, mode: opts.Auth.Mode, profile: resolved.Profile, dialTimeout: opts.Network.DialTimeout, subscribers: make(map[uint64]chan Event), tasksDone: make(chan struct{}), shutdownDone: make(chan struct{})} + p.Authenticate = func(ctx context.Context, h *http.Client) (string, error) { + if e := c.prepare(ctx); e != nil { + return "", e + } + if e := opts.Auth.Identity.Authenticate(ctx, h, auth.IdentityRequest{AllowInteraction: session.InteractionAllowed(ctx)}); e != nil { + return "", e + } + return "", c.prepare(ctx) + } + c.resolver = resolver.NewController(p, checkedDNSDialer{c}, opts.DNS.FallbackLookup, opts.DNS.Servers != nil && len(opts.DNS.Servers) == 0) + c.scope = SessionScope{ControllerURL: cfg.BaseURL, DeviceID: cfg.DeviceID, Mode: opts.Auth.Mode, LoginDomain: cfg.LoginDomain} + p.SetStore(&stateStore{store: opts.SessionStore, client: c}) + return c, nil +} +func NewDeviceID() (string, error) { + var b [16]byte + if _, e := rand.Read(b[:]); e != nil { + return "", e + } + return fmt.Sprintf("%X", b), nil +} + +// Authenticate forces a fresh login. Concurrent requests share the provider's +// refresh; the embedding application remains responsible for connection retry. +func (c *Runtime) Authenticate(parent context.Context) (SessionInfo, error) { + if c.isClosed() { + return SessionInfo{}, ErrClosed + } + ctx, done := c.withLifetime(parent) + defer done() + ctx = session.WithInteraction(ctx, true) + if err := c.prepare(ctx); err != nil { + return SessionInfo{}, err + } + if _, err := c.provider.ForceLogin(ctx); err != nil { + return SessionInfo{}, err + } + return c.Connect(ctx) +} +func (c *Runtime) withLifetime(parent context.Context) (context.Context, func()) { + ctx, cancel := context.WithCancel(parent) + c.mu.Lock() + if c.closed { + c.mu.Unlock() + cancel() + return ctx, func() {} + } + c.ops.Add(1) + c.mu.Unlock() + stop := context.AfterFunc(c.ctx, cancel) + return ctx, func() { stop(); cancel(); c.ops.Done() } +} + +func (c *Runtime) operation(parent context.Context) (context.Context, func()) { + ctx, release := c.withLifetime(parent) + ctx, cancel := context.WithTimeout(ctx, c.operationTimeout()) + return session.WithInteraction(ctx, false), func() { cancel(); release() } +} + +func (c *Runtime) Connect(parent context.Context) (SessionInfo, error) { + if c.isClosed() { + return SessionInfo{}, ErrClosed + } + ctx, done := c.withLifetime(parent) + defer done() + ctx = session.WithInteraction(ctx, true) + if err := c.prepare(ctx); err != nil { + return SessionInfo{}, err + } + cred, err := c.provider.Credential(ctx) + if err != nil { + return SessionInfo{}, err + } + c.mu.Lock() + defer c.mu.Unlock() + if c.closed { + return SessionInfo{}, ErrClosed + } + c.start() + c.generation = cred.Generation + info := SessionInfo{Gateways: append([]string(nil), cred.Gateways...), DNS: append([]string(nil), cred.DNS...), Generation: c.generation, Username: cred.Username, DisplayName: cred.DisplayName} + for _, r := range cred.Policy.IPRules { + address := "" + switch { + case r.IP != nil: + address = r.IP.String() + case r.Net != nil: + address = r.Net.String() + case r.IPMin != nil: + address = r.IPMin.String() + "-" + r.IPMax.String() + } + info.Resources = append(info.Resources, Resource{Address: address, Protocol: r.Proto, ApplicationID: r.AppID, GatewayGroup: cred.Policy.AppNodeGroups[r.AppID], PortMin: r.Port.Min, PortMax: r.Port.Max}) + } + for _, r := range cred.Policy.DomainRules { + info.Resources = append(info.Resources, Resource{Address: r.Domain, Protocol: r.Proto, ApplicationID: r.AppID, GatewayGroup: cred.Policy.AppNodeGroups[r.AppID], PortMin: r.Port.Min, PortMax: r.Port.Max}) + } + for _, r := range cred.Policy.SuffixRules { + info.Resources = append(info.Resources, Resource{Address: "*" + r.Suffix, Protocol: r.Proto, ApplicationID: r.AppID, GatewayGroup: cred.Policy.AppNodeGroups[r.AppID], PortMin: r.Port.Min, PortMax: r.Port.Max}) + } + c.status.State = Ready + c.status.Session = &info + c.status.LastError = nil + c.publishLocked() + return info, nil +} + +// OpenTransport authenticates an L3 gateway without creating a system TUN or +// requesting access to any particular resource. Embedders can call it before +// advertising a connected packet-facing session. +func (c *Runtime) OpenTransport(parent context.Context) (TransportInfo, error) { + if c.isClosed() { + return TransportInfo{}, ErrClosed + } + ctx, done := c.operation(parent) + defer done() + if err := c.prepare(ctx); err != nil { + return TransportInfo{}, err + } + t, err := c.manager.Tunnel(ctx) + if err != nil { + return TransportInfo{}, err + } + ip := t.VIP().To4() + if ip == nil { + return TransportInfo{}, errors.New("gateway did not assign an IPv4 virtual address") + } + return TransportInfo{Generation: c.currentGeneration(), Gateway: t.Addr(), VirtualIPv4: ip.String()}, nil +} + +func (c *Runtime) DialContext(parent context.Context, network, address string) (net.Conn, error) { + if network != "tcp" && network != "tcp4" && network != "udp" && network != "udp4" { + return nil, auth.ErrUnsupported + } + protocol := strings.TrimSuffix(network, "4") + host, p, err := net.SplitHostPort(address) + if err != nil { + return nil, errors.New("target must include port") + } + port, err := strconv.Atoi(p) + if err != nil || port < 1 || port > 65535 { + return nil, errors.New("invalid target port") + } + c.mu.Lock() + closed := c.closed + c.mu.Unlock() + if closed { + return nil, ErrClosed + } + ctx, done := c.operation(parent) + defer done() + if err := c.prepare(ctx); err != nil { + return nil, err + } + resolve := c.resolver.Resolve + if protocol == "udp" { + resolve = c.resolver.ResolveUDP + } + target, err := resolve(ctx, host, port) + if err != nil { + return nil, err + } + return c.dialResolved(ctx, target, port, protocol) +} + +// RoutePlan is an immutable decision under one credential generation. +type RoutePlan struct { + Target resolver.Resolution + Port int + Network string + Gateways []string + GatewayGroup string + Credential *session.Credential +} + +func (c *Runtime) dialResolved(ctx context.Context, target resolver.Resolution, port int, network string) (net.Conn, error) { + cred, e := c.provider.Credential(ctx) + if e != nil { + return nil, e + } + if target.Generation != 0 && target.Generation != cred.Generation { + return nil, &Error{Info: ErrorInfo{Kind: ErrorSessionReplaced, Message: "session replaced during resolution"}} + } + ctx = session.ExpectGeneration(ctx, cred.Generation) + plan := RoutePlan{Target: target, Port: port, Network: network, Credential: cred, Gateways: cred.GatewaysForApp(target.AppID), GatewayGroup: cred.GatewayGroupForApp(target.AppID)} + if target.AppID == "" { + return nil, ErrDenied + } + if len(plan.Gateways) == 0 { + return nil, tunnel.ErrNoLines + } + if c.checkTarget != nil { + ip, e := netip.ParseAddr(target.IP) + if e != nil { + return nil, e + } + if e = c.checkTarget(ctx, Target{Generation: cred.Generation, Network: network, Host: target.Host, IP: ip.Unmap(), Port: uint16(port)}); e != nil { + return nil, &Error{Info: ErrorInfo{Kind: ErrorCallerDenied, Op: "target", Message: "target rejected by caller"}, cause: sanitizedCause{e}} + } + } + var conn net.Conn + if network == "tcp" { + conn, e = c.dialer.Dial(ctx, target.IP, port, target.AppID, target.Domain) + } else { + conn, e = c.dialer.DialUDP(ctx, target.IP, port, target.AppID, target.Domain) + } + if e != nil { + return nil, e + } + if c.provider.Current() != cred { + conn.Close() + return nil, &Error{Info: ErrorInfo{Kind: ErrorSessionReplaced, Message: "session replaced during dial"}} + } + c.mu.Lock() + defer c.mu.Unlock() + if c.closed { + conn.Close() + return nil, ErrClosed + } + owned := &ownedConn{Conn: conn, owner: c, credential: cred, datagram: network == "udp"} + c.conns[owned] = struct{}{} + return owned, nil +} +func (c *Runtime) DialResolved(parent context.Context, t resolver.Resolution, p int, n string) (net.Conn, error) { + ctx, done := c.operation(parent) + defer done() + if e := c.prepare(ctx); e != nil { + return nil, e + } + return c.dialResolved(ctx, t, p, n) +} + +func (c *Runtime) isClosed() bool { + c.mu.Lock() + defer c.mu.Unlock() + return c.closed +} + +func (c *Runtime) LookupContextHost(parent context.Context, host string) ([]string, error) { + if c.isClosed() { + return nil, ErrClosed + } + ctx, done := c.operation(parent) + defer done() + if err := c.prepare(ctx); err != nil { + return nil, err + } + return c.resolver.LookupHost(ctx, host) +} +func (c *Runtime) Close() error { + c.mu.Lock() + if c.closed { + c.mu.Unlock() + return nil + } + c.closed = true + c.status.State = Closed + c.publishLocked() + c.cancel() + conns := make([]*ownedConn, 0, len(c.conns)) + for conn := range c.conns { + conns = append(conns, conn) + } + for id, ch := range c.subscribers { + close(ch) + delete(c.subscribers, id) + } + c.status.State = Closed + c.mu.Unlock() + for _, conn := range conns { + conn.Close() + } + c.startOnce.Do(func() { close(c.tasksDone) }) + c.provider.Close() + c.manager.Close() + if c.transport != nil { + c.transport.CloseIdleConnections() + } + go func() { <-c.tasksDone; c.ops.Wait(); close(c.shutdownDone) }() + return nil +} + +type ownedConn struct { + net.Conn + datagram bool + credential *session.Credential + owner *Runtime + once sync.Once + err error +} + +func (c *ownedConn) Read(b []byte) (int, error) { + if c.owner.provider.Current() != c.credential { + c.Close() + return 0, &Error{Info: ErrorInfo{Kind: ErrorSessionReplaced, Message: "session replaced"}} + } + return c.Conn.Read(b) +} +func (c *ownedConn) Write(b []byte) (int, error) { + if c.owner.provider.Current() != c.credential { + c.Close() + return 0, &Error{Info: ErrorInfo{Kind: ErrorSessionReplaced, Message: "session replaced"}} + } + if c.datagram && len(b) > 1372 { + return 0, ErrDatagramTooLarge + } + return c.Conn.Write(b) +} +func (c *ownedConn) Close() error { + c.once.Do(func() { c.err = c.Conn.Close(); c.owner.mu.Lock(); delete(c.owner.conns, c); c.owner.mu.Unlock() }) + return c.err +} +func (c *ownedConn) CloseWrite() error { + if w, ok := c.Conn.(interface{ CloseWrite() error }); ok { + return w.CloseWrite() + } + return errors.New("half-close unavailable") +} diff --git a/internal/runtime/status.go b/internal/runtime/status.go new file mode 100644 index 0000000..8bf03ab --- /dev/null +++ b/internal/runtime/status.go @@ -0,0 +1,450 @@ +package runtime + +import ( + "context" + "crypto/tls" + "crypto/x509" + "encoding/json" + "errors" + "github.com/ShanghaitechGeekPie/geektrust/auth" + "github.com/ShanghaitechGeekPie/geektrust/deployment" + "github.com/ShanghaitechGeekPie/geektrust/internal/resolver" + "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" + "net" + "sync" + "time" +) + +type SessionState string + +const ( + Idle SessionState = "idle" + Authenticating SessionState = "authenticating" + InteractionRequired SessionState = "interaction_required" + Ready SessionState = "ready" + Failed SessionState = "failed" + Closed SessionState = "closed" +) + +type Status struct { + Revision uint64 + Generation uint64 + State SessionState + Deployment deployment.Profile + Session *SessionInfo + LastError *ErrorInfo +} + +type ErrorKind string + +const ( + ErrorConfig ErrorKind = "config" + ErrorInteractionRequired ErrorKind = "interaction_required" + ErrorIdentityChanged ErrorKind = "identity_changed" + ErrorAuthenticationRejected ErrorKind = "authentication_rejected" + ErrorControllerDenied ErrorKind = "controller_denied" + ErrorCallerDenied ErrorKind = "caller_denied" + ErrorTLS ErrorKind = "tls" + ErrorDNS ErrorKind = "dns" + ErrorNetwork ErrorKind = "network" + ErrorUnsupported ErrorKind = "unsupported" + ErrorSessionReplaced ErrorKind = "session_replaced" + ErrorDatagramTooLarge ErrorKind = "datagram_too_large" + ErrorStorage ErrorKind = "storage" + ErrorClosed ErrorKind = "closed" +) + +type ErrorInfo struct { + Kind ErrorKind + Op string + Code int + Message string +} + +type TrustedDevice struct { + ID, Name, Platform, OS, OSVersion string + LastLoginIP, LastLoginAddress string + NetworkZones []string + Online bool +} + +type TrustedDeviceList struct { + Devices []TrustedDevice + CurrentDeviceID string + CurrentTrustStatus int + TrustEnabled bool +} + +type Error struct { + Info ErrorInfo + cause error +} + +func (e *Error) Error() string { return e.Info.Message } +func (e *Error) Unwrap() error { return e.cause } +func (e *Error) Is(target error) bool { return errors.Is(e.cause, target) } +func safeError(op string, e error) error { + if e == nil { + return nil + } + var existing *Error + if errors.As(e, &existing) { + return e + } + kind := ErrorNetwork + cause := error(sanitizedCause{e}) + msg := "network operation failed" + switch { + case errors.Is(e, context.Canceled): + cause = context.Canceled + msg = "operation canceled" + case errors.Is(e, context.DeadlineExceeded): + cause = context.DeadlineExceeded + msg = "operation deadline exceeded" + case errors.Is(e, auth.ErrInteractionRequired): + kind = ErrorInteractionRequired + cause = auth.ErrInteractionRequired + msg = "authentication interaction required" + case errors.Is(e, auth.ErrCredentialStore): + kind = ErrorStorage + cause = auth.ErrCredentialStore + msg = "credential storage failed" + case errors.Is(e, auth.ErrInvalidCredential): + kind = ErrorConfig + cause = auth.ErrInvalidCredential + msg = "invalid identity credential" + case errors.Is(e, session.ErrIdentityAuthentication): + kind = ErrorAuthenticationRejected + msg = "identity authentication failed" + case errors.Is(e, auth.ErrUnsupported): + kind = ErrorUnsupported + cause = auth.ErrUnsupported + msg = "unsupported operation" + case errors.Is(e, resolver.ErrUnresolvable): + kind = ErrorDNS + msg = "target DNS resolution failed" + case errors.Is(e, session.ErrSessionReplaced): + kind = ErrorSessionReplaced + cause = session.ErrSessionReplaced + msg = "session replaced" + case errors.Is(e, ErrClosed): + kind = ErrorClosed + cause = ErrClosed + msg = ErrClosed.Error() + case errors.Is(e, ErrDenied): + kind = ErrorControllerDenied + cause = ErrDenied + msg = ErrDenied.Error() + case errors.Is(e, ErrDatagramTooLarge): + kind = ErrorDatagramTooLarge + cause = ErrDatagramTooLarge + msg = ErrDatagramTooLarge.Error() + } + var certificate *tls.CertificateVerificationError + var unknown x509.UnknownAuthorityError + var host x509.HostnameError + var invalid x509.CertificateInvalidError + if errors.As(e, &certificate) || errors.As(e, &unknown) || errors.As(e, &host) || errors.As(e, &invalid) { + kind = ErrorTLS + msg = "gateway certificate verification failed" + } + var api *sdpc.APIError + code := 0 + if errors.As(e, &api) { + kind = ErrorControllerDenied + code = int(api.Code) + msg = "controller rejected operation" + } + return &Error{Info: ErrorInfo{Kind: kind, Op: op, Code: code, Message: msg}, cause: cause} +} +func ImplementedCapabilities() Capabilities { + return Capabilities{IPv4TCP: true, IPv4UDP: true, IPv4ICMPEcho: true, IPv6Gateway: true} +} +func (c *Runtime) operationTimeout() time.Duration { + if c.dialTimeout == 0 { + return 45 * time.Second + } + return c.dialTimeout +} +func (c *Runtime) currentGeneration() uint64 { + if v := c.provider.Current(); v != nil { + return v.Generation + } + return 0 +} +func (c *Runtime) prepare(ctx context.Context) error { + if c.isClosed() { + return ErrClosed + } + c.identityMu.Lock() + defer c.identityMu.Unlock() + info, e := c.identity.Info(ctx) + if e != nil { + return e + } + if info.Issuer == "" || info.Subject == "" || info.Kind == "" { + return errors.New("identity metadata required") + } + if c.identityReady { + if c.scope.IdentityIssuer != info.Issuer || c.scope.IdentitySubject != info.Subject || c.scope.IdentityKind != info.Kind { + return &Error{Info: ErrorInfo{Kind: ErrorIdentityChanged, Op: "identity", Message: "identity changed; create a new client"}} + } + return nil + } + if c.isClosed() { + return ErrClosed + } + c.scope.IdentityIssuer = info.Issuer + c.scope.IdentitySubject = info.Subject + c.scope.IdentityKind = info.Kind + c.identityReady = true + c.provider.SetIdentity(info) + c.provider.AddObserver(clientObserver{c}) + return nil +} +func (c *Runtime) start() { + c.startOnce.Do(func() { go func() { defer close(c.tasksDone); c.provider.CheckLoop(c.ctx, 5*time.Minute) }() }) +} +func (c *Runtime) Status() Status { c.mu.Lock(); defer c.mu.Unlock(); return cloneStatus(c.status) } +func cloneStatus(s Status) Status { + if s.Session != nil { + v := *s.Session + v.Gateways = append([]string(nil), v.Gateways...) + v.DNS = append([]string(nil), v.DNS...) + v.Resources = append([]Resource(nil), v.Resources...) + s.Session = &v + } + if s.LastError != nil { + v := *s.LastError + s.LastError = &v + } + return s +} +func (c *Runtime) Subscribe(ctx context.Context) <-chan Event { + ch := make(chan Event, 1) + c.mu.Lock() + if c.closed { + close(ch) + c.mu.Unlock() + return ch + } + c.nextSubscriber++ + id := c.nextSubscriber + c.subscribers[id] = ch + ch <- Event{Time: time.Now(), Status: cloneStatus(c.status)} + c.mu.Unlock() + go func() { + select { + case <-ctx.Done(): + case <-c.ctx.Done(): + } + c.mu.Lock() + if _, ok := c.subscribers[id]; ok { + delete(c.subscribers, id) + close(ch) + } + c.mu.Unlock() + }() + return ch +} +func (c *Runtime) publishLocked() { + c.status.Revision++ + c.status.Generation = c.generation + c.status.Deployment = c.profile + ev := Event{Time: time.Now(), Status: cloneStatus(c.status)} + for _, ch := range c.subscribers { + select { + case ch <- ev: + default: + select { + case <-ch: + default: + } + ch <- ev + } + } +} +func (c *Runtime) Shutdown(ctx context.Context) error { + c.Close() + select { + case <-ctx.Done(): + return ctx.Err() + case <-c.shutdownDone: + return nil + } +} +func (c *Runtime) ForgetSession(parent context.Context) error { + ctx, done := c.operation(parent) + defer done() + if e := c.prepare(ctx); e != nil { + return e + } + c.provider.Invalidate() + c.resetConnections() + c.mu.Lock() + c.forgotten = true + c.mu.Unlock() + store := c.providerStore() + if store == nil { + return nil + } + return store.Delete(ctx, c.scope) +} +func (c *Runtime) providerStore() SessionStore { return c.store } +func (c *Runtime) resetConnections() { + c.mu.Lock() + conns := make([]*ownedConn, 0, len(c.conns)) + for x := range c.conns { + conns = append(conns, x) + } + c.mu.Unlock() + for _, x := range conns { + x.Close() + } + c.manager.Reset() +} + +type clientObserver struct{ client *Runtime } + +func (o clientObserver) OnSessionEvent(e session.Event) { + c := o.client + + c.mu.Lock() + defer c.mu.Unlock() + if c.closed { + return + } + current := c.provider.Current() + if current != nil && (e.Kind == session.EventLoginStart || e.Kind == session.EventLoginFailed || e.Kind == session.EventInvalidated) { + return + } + if e.Session != nil && current != nil && e.Session.Generation != current.Generation { + return + } + if e.Session != nil && c.status.State == Ready && c.status.Session != nil && c.status.Session.Generation == e.Session.Generation { + return + } + switch e.Kind { + case session.EventLoginStart: + c.status.State = Authenticating + case session.EventLoginSuccess, session.EventRestoreOK: + c.status.State = Ready + c.generation = e.Session.Generation + v := SessionInfo{Generation: c.generation} + if e.Session != nil { + v.Username = e.Session.Username + v.DisplayName = e.Session.DisplayName + v.Gateways = append([]string(nil), e.Session.Gateways...) + v.DNS = append([]string(nil), e.Session.DNS...) + } + c.status.Session = &v + c.status.LastError = nil + case session.EventInteractionRequired: + c.status.State = InteractionRequired + c.status.LastError = &ErrorInfo{Kind: ErrorInteractionRequired, Op: "authentication", Message: "authentication interaction required"} + case session.EventLoginFailed: + c.status.State = Failed + c.status.LastError = &ErrorInfo{Kind: ErrorAuthenticationRejected, Op: "authentication", Message: "authentication failed"} + case session.EventInvalidated: + c.status.State = Idle + c.status.Session = nil + default: + return + } + c.publishLocked() +} + +type stateStore struct { + store SessionStore + client *Runtime + mu sync.Mutex +} + +func (s *stateStore) Load(ctx context.Context) (*session.State, error) { + if s.store == nil { + return nil, nil + } + s.client.mu.Lock() + forgot := s.client.forgotten + s.client.mu.Unlock() + if forgot { + return nil, nil + } + b, e := s.store.Load(ctx, s.client.scope) + if e != nil { + return nil, &Error{Info: ErrorInfo{Kind: ErrorStorage, Message: "session storage load failed"}, cause: sanitizedCause{e}} + } + if len(b) == 0 { + return nil, nil + } + var st session.State + if json.Unmarshal(b, &st) != nil { + return nil, &Error{Info: ErrorInfo{Kind: ErrorStorage, Message: "invalid session record"}} + } + if st.Version == 0 { + return nil, nil + } + if st.Version != 1 { + return nil, &Error{Info: ErrorInfo{Kind: ErrorStorage, Message: "invalid session record"}} + } + return &st, nil +} +func (s *stateStore) Save(ctx context.Context, st *session.State) error { + if s.store == nil { + return nil + } + b, e := json.Marshal(st) + if e != nil { + return e + } + if e = s.store.Save(ctx, s.client.scope, b); e != nil { + return &Error{Info: ErrorInfo{Kind: ErrorStorage, Message: "session storage save failed"}, cause: sanitizedCause{e}} + } + s.client.mu.Lock() + s.client.forgotten = false + s.client.mu.Unlock() + return nil +} + +// The tunnel performs CA validation first. Unknown CA enrollment is one atomic store operation. +type pinAdapter struct { + store GatewayPinStore + controller string + template *tls.Config +} + +func (p pinAdapter) LoadPin(ctx context.Context, a string) ([]byte, error) { return nil, nil } +func (p pinAdapter) SavePin(ctx context.Context, a string, b []byte) error { + var pin [32]byte + copy(pin[:], b) + name := "" + if p.template != nil { + name = p.template.ServerName + } + if name == "" { + name, _, _ = net.SplitHostPort(a) + } + ok, e := p.store.CheckOrEnroll(ctx, GatewayIdentity{ControllerURL: p.controller, Address: a, ServerName: name}, pin) + if e != nil { + return &Error{Info: ErrorInfo{Kind: ErrorStorage, Message: "gateway pin storage failed"}} + } + if !ok { + return errors.New("gateway public key changed") + } + return nil +} + +func PublicError(op string, e error) error { return safeError(op, e) } + +type sanitizedCause struct{ original error } + +func (s sanitizedCause) Error() string { return "operation failed" } +func (s sanitizedCause) Is(e error) bool { return errors.Is(s.original, e) } + +func ConfigError(e error) error { + if e == nil { + return nil + } + return &Error{Info: ErrorInfo{Kind: ErrorConfig, Op: "new", Message: e.Error()}} +} diff --git a/client/target_test.go b/internal/runtime/target_test.go similarity index 85% rename from client/target_test.go rename to internal/runtime/target_test.go index 99aebb8..0073643 100644 --- a/client/target_test.go +++ b/internal/runtime/target_test.go @@ -1,10 +1,10 @@ -package client +package runtime import ( "context" "errors" - "github.com/ShanghaitechGeekPie/geektrust/deployment" "github.com/ShanghaitechGeekPie/geektrust/internal/config" + "github.com/ShanghaitechGeekPie/geektrust/internal/settings" "net" "net/http" "net/netip" @@ -14,8 +14,8 @@ import ( func TestTargetFilterRejectsBeforeGatewayDial(t *testing.T) { rejected := errors.New("route excludes destination") var seen []netip.Addr - c, err := New(Options{ - Compatibility: deployment.Compatibility{FallbackAppID: "app"}, + c, err := newLegacy(legacyOptions{ + Compatibility: settings.Compatibility{FallbackAppID: "app"}, ControllerURL: config.DefaultBaseURL, DeviceID: "0123456789ABCDEF0123456789ABCDEF", Gateways: []string{"gateway.example:441"}, Transport: compatibilityTransport{}, SessionStore: compatibilityStore(`{"sid":"synthetic","device_id":"0123456789ABCDEF0123456789ABCDEF","client_type":"browser","cookies":[{"name":"sid","value":"synthetic"}]}`), @@ -38,7 +38,7 @@ func TestTargetFilterRejectsBeforeGatewayDial(t *testing.T) { packet := make([]byte, 28) packet[0] = 0x45 copy(packet[16:20], []byte{192, 0, 2, 1}) - if _, err := c.ExchangePacket(context.Background(), packet); !errors.Is(err, rejected) { + if _, err := c.ExchangeICMPEcho(context.Background(), packet); !errors.Is(err, rejected) { t.Fatalf("ICMP target filter: %v", err) } if len(seen) != 3 { diff --git a/internal/sdpc/cancellation_test.go b/internal/sdpc/cancellation_test.go new file mode 100644 index 0000000..fc6b8f5 --- /dev/null +++ b/internal/sdpc/cancellation_test.go @@ -0,0 +1,33 @@ +package sdpc + +import ( + "context" + "errors" + "net/http" + "net/url" + "strings" + "testing" +) + +type cancellationTransport struct{ cause error } + +func (t cancellationTransport) RoundTrip(*http.Request) (*http.Response, error) { + return nil, &url.Error{Op: "Get", URL: "https://fixture.example/?ticket=secret", Err: t.cause} +} +func TestCASPreservesSafeCancellationCauses(t *testing.T) { + for _, cause := range []error{context.Canceled, context.DeadlineExceeded} { + c := NewClient("https://controller.example", "Mac", "id", &http.Client{Transport: cancellationTransport{cause}}) + c.LoginDomain = "fixture" + _, e := c.CasTicket(context.Background()) + if !errors.Is(e, cause) { + t.Fatal("CAS lost the cancellation cause") + } + if strings.Contains(e.Error(), "secret") { + t.Fatal("CAS exposed a credential-bearing URL") + } + var raw *url.Error + if errors.As(e, &raw) { + t.Fatal("CAS kept the raw URL error in its chain") + } + } +} diff --git a/internal/sdpc/client.go b/internal/sdpc/client.go index 947d909..e685f59 100644 --- a/internal/sdpc/client.go +++ b/internal/sdpc/client.go @@ -78,10 +78,11 @@ func IsSessionExpired(err error) bool { // Client talks to the SDPC controller. The HTTP client must carry a cookie // jar; the session cookies (sid & friends) live there. type Client struct { - BaseURL string - Platform string - DeviceID string - HTTP *http.Client + DomainMapping *bool + BaseURL string + Platform string + DeviceID string + HTTP *http.Client // ClientType selects the login path for reportEnv: ClientTypeBrowser // (default) keeps the session in pure-web mode; ClientTypeDesktop marks diff --git a/internal/sdpc/login.go b/internal/sdpc/login.go index 39fcbd4..bcf2ec6 100644 --- a/internal/sdpc/login.go +++ b/internal/sdpc/login.go @@ -3,6 +3,7 @@ package sdpc import ( "context" "encoding/json" + "errors" "fmt" "net/http" "net/url" @@ -61,8 +62,20 @@ func (c *Client) CasTicket(ctx context.Context) (string, error) { } resp, err := noFollow.Do(req) if err != nil { - return "", fmt.Errorf("cas chain request failed") + cause := ctx.Err() + if cause == nil { + if errors.Is(err, context.Canceled) { + cause = context.Canceled + } else if errors.Is(err, context.DeadlineExceeded) { + cause = context.DeadlineExceeded + } + } + if cause != nil { + return "", fmt.Errorf("cas chain request failed: %w", cause) + } + return "", errors.New("cas chain request failed") } + resp.Body.Close() if shortcutURL == nil { diff --git a/internal/sdpc/resource.go b/internal/sdpc/resource.go index f60353d..f9d763d 100644 --- a/internal/sdpc/resource.go +++ b/internal/sdpc/resource.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/binary" + defaults "github.com/ShanghaitechGeekPie/geektrust/internal/deployment" "net" "net/url" "strconv" @@ -356,7 +357,7 @@ func (c *Client) parseResource(cr *clientResource) *Resource { { for _, d := range domains { res.DomainRules = append(res.DomainRules, DomainRule{ - Domain: normalizeHost(d.host), IP: firstIP, AppID: app.ID, Port: d.port, Proto: d.proto, + Domain: normalizeHost(d.host), IP: c.domainAddress(firstIP), AppID: app.ID, Port: d.port, Proto: d.proto, }) } } @@ -465,3 +466,13 @@ func isDottedIPv4(s string) bool { ip := net.ParseIP(s) return ip != nil && ip.To4() != nil } + +func (c *Client) domainAddress(ip string) string { + if c.DomainMapping != nil { + if !*c.DomainMapping { + return "" + } + return ip + } + return defaults.DomainAddress(c.BaseURL, ip) +} diff --git a/internal/sdpc/resource_test.go b/internal/sdpc/resource_test.go index 2736928..263f0f5 100644 --- a/internal/sdpc/resource_test.go +++ b/internal/sdpc/resource_test.go @@ -313,3 +313,31 @@ func TestAPIErrorSessionExpired(t *testing.T) { } } } + +func TestExplicitGenericLeavesDomainAddressUninferred(t *testing.T) { + var envelope struct { + Data json.RawMessage `json:"data"` + } + if e := json.Unmarshal([]byte(sampleResource), &envelope); e != nil { + t.Fatal(e) + } + var raw clientResource + if e := json.Unmarshal(envelope.Data, &raw); e != nil { + t.Fatal(e) + } + c := NewClient("https://vpn.shanghaitech.edu.cn", "Mac", "id", nil) + disabled := false + c.DomainMapping = &disabled + v := c.parseResource(&raw) + rule, ok := v.MatchDomainProtocol("library.shanghaitech.edu.cn", 443, "tcp") + if !ok || rule.IP != "" { + t.Fatal("generic deployment inherited a school IP mapping") + } + enabled := true + c.DomainMapping = &enabled + v = c.parseResource(&raw) + rule, ok = v.MatchDomainProtocol("library.shanghaitech.edu.cn", 443, "tcp") + if !ok || rule.IP != "10.15.45.163" { + t.Fatal("verified school mapping lost") + } +} diff --git a/internal/session/authentication_test.go b/internal/session/authentication_test.go index 6c1566f..5aa4f1f 100644 --- a/internal/session/authentication_test.go +++ b/internal/session/authentication_test.go @@ -19,7 +19,7 @@ func TestMissingChallengeHandlerReturnsTypedError(t *testing.T) { p := &Provider{} _, err := p.smsFlow(context.Background(), nil) var required *auth.RequiredError - if !errors.Is(err, auth.ErrRequired) || !errors.As(err, &required) || required.Challenge.Method != "auth/sms" { + if !errors.Is(err, auth.ErrInteractionRequired) || !errors.As(err, &required) || required.Challenge.Info.Method != auth.SMS { t.Fatalf("unexpected challenge error: %v", err) } } @@ -37,7 +37,7 @@ func TestCancelledChallengeDoesNotSubmitAnswer(t *testing.T) { defer cancel() p := &Provider{logger: slog.New(slog.NewTextHandler(io.Discard, nil)), ChallengeHandler: func(ctx context.Context, challenge auth.Challenge) (string, error) { deadline, ok := ctx.Deadline() - if !ok || !deadline.Equal(challenge.ExpiresAt) || time.Until(deadline) > time.Minute { + if !ok || !deadline.Equal(challenge.Info.Deadline) || time.Until(deadline) > time.Minute { t.Fatal("challenge missing bounded lifetime") } cancel() diff --git a/internal/session/cancellation_regression_test.go b/internal/session/cancellation_regression_test.go index 0aac2d9..1b722af 100644 --- a/internal/session/cancellation_regression_test.go +++ b/internal/session/cancellation_regression_test.go @@ -44,14 +44,15 @@ func TestRestoreJoinerSurvivesLeaderCancellation(t *testing.T) { secondCtx, stop := context.WithTimeout(context.Background(), 3*time.Second) defer stop() second := make(chan error, 1) + joined := signalJoin(secondCtx) go func() { - cred, err := p.Credential(secondCtx) + cred, err := p.Credential(joined) if err == nil && (cred == nil || cred.SID == "") { err = errors.New("restore returned no credential") } second <- err }() - waitForJoiner(t, p) + waitForJoiner(t, joined) if !deadline { cancel() } @@ -86,8 +87,9 @@ func TestCredentialJoinerDoesNotRetryIndependentTimeout(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() second := make(chan error, 1) - go func() { _, err := p.Credential(ctx); second <- err }() - waitForJoiner(t, p) + joined := signalJoin(ctx) + go func() { _, err := p.Credential(joined); second <- err }() + waitForJoiner(t, joined) close(release) for _, result := range []<-chan error{first, second} { if err := <-result; !errors.Is(err, context.DeadlineExceeded) { diff --git a/internal/session/challenge.go b/internal/session/challenge.go new file mode 100644 index 0000000..fbba479 --- /dev/null +++ b/internal/session/challenge.go @@ -0,0 +1,59 @@ +package session + +import ( + "context" + "errors" + "fmt" + "github.com/ShanghaitechGeekPie/geektrust/auth" + "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" + "sync" + "sync/atomic" + "time" +) + +var challengeSequence atomic.Uint64 + +func (p *Provider) challengeFlow(ctx context.Context, sc *sdpc.Client, deadline time.Time) (string, error) { + info := auth.ChallengeInfo{ID: challengeSequence.Add(1), Method: auth.SMS, Deadline: deadline} + for { + var mu sync.Mutex + active := true + resend := func(parent context.Context) (auth.ChallengeInfo, error) { + mu.Lock() + defer mu.Unlock() + if !active || ctx.Err() != nil { + return auth.ChallengeInfo{}, auth.ErrChallengeClosed + } + call, cancel := context.WithCancel(parent) + stop := context.AfterFunc(ctx, cancel) + defer func() { stop(); cancel() }() + e := sc.SendSMS(call) + if sdpc.IsSessionExpired(e) { + return auth.ChallengeInfo{}, fmt.Errorf("%w: %w", errSMSAuthSessionExpired, e) + } + return info, e + } + code, e := p.ChallengeHandler(ctx, auth.Challenge{Info: info, Resend: resend}) + mu.Lock() + active = false + mu.Unlock() + if ctx.Err() != nil { + return "", ctx.Err() + } + if e != nil { + return "", e + } + ticket, e := sc.CheckSMSCode(ctx, code) + if e == nil { + return ticket, nil + } + if sdpc.IsSessionExpired(e) { + return "", fmt.Errorf("%w: %w", errSMSAuthSessionExpired, e) + } + var api *sdpc.APIError + if !errors.As(e, &api) { + return "", e + } + info.LastFailure = &auth.ChallengeFailure{Code: int(api.Code), Message: "verification rejected"} + } +} diff --git a/internal/session/challenge_test.go b/internal/session/challenge_test.go new file mode 100644 index 0000000..b40c2ed --- /dev/null +++ b/internal/session/challenge_test.go @@ -0,0 +1,46 @@ +package session + +import ( + "context" + "errors" + "github.com/ShanghaitechGeekPie/geektrust/auth" + "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" +) + +func TestChallengeResendLifecycleAndSilentLogin(t *testing.T) { + var sends atomic.Int32 + controller := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Query().Get("action") == "sendsms" { + sends.Add(1) + io.WriteString(w, `{"code":0,"data":{}}`) + } else { + io.WriteString(w, `{"code":0,"data":{"sidTicket":"fixture"}}`) + } + })) + defer controller.Close() + var old func(context.Context) (auth.ChallengeInfo, error) + p := &Provider{logger: slog.New(slog.NewTextHandler(io.Discard, nil)), ChallengeHandler: func(ctx context.Context, c auth.Challenge) (string, error) { + old = c.Resend + if _, e := c.Resend(ctx); e != nil { + t.Fatal(e) + } + return "123456", nil + }} + sc := sdpc.NewClient(controller.URL, "Mac", "id", controller.Client()) + ticket, e := p.smsFlow(context.Background(), sc) + if e != nil || ticket != "fixture" || sends.Load() != 2 { + t.Fatalf("SMS round trip: %v", e) + } + if _, e = old(context.Background()); !errors.Is(e, auth.ErrChallengeClosed) { + t.Fatal("old resend callback remained usable") + } + if _, e = p.smsFlow(WithInteraction(context.Background(), false), sc); !errors.Is(e, auth.ErrInteractionRequired) || sends.Load() != 2 { + t.Fatal("silent operation sent SMS") + } +} diff --git a/internal/session/events.go b/internal/session/events.go index a529f71..e965997 100644 --- a/internal/session/events.go +++ b/internal/session/events.go @@ -21,7 +21,10 @@ const ( // SessionInfo is the credential-redacted session snapshot handed to // observers. It never contains SID, cookies or CSRF tokens. +const EventInteractionRequired EventKind = "interaction_required" + type SessionInfo struct { + Generation uint64 Username string DisplayName string ClientIP string diff --git a/internal/session/events_test.go b/internal/session/events_test.go index b8fbb65..5da1b47 100644 --- a/internal/session/events_test.go +++ b/internal/session/events_test.go @@ -178,6 +178,7 @@ func newRestoreFixture(t *testing.T, handler http.HandlerFunc) *Provider { dir := t.TempDir() statePath := filepath.Join(dir, "state.enc") if err := NewStore(statePath).Save(context.Background(), &State{ + ControllerURL: srv.URL, Username: "u1", SID: "synthetic-sid", DeviceID: testDeviceID, CsrfToken: "synthetic-csrf", @@ -251,11 +252,12 @@ func TestTryForceReloginReservation(t *testing.T) { t.Fatal("idle provider refused relogin") } waiter := make(chan error, 1) + joined := signalJoin(context.Background()) go func() { - _, err := p.Credential(context.Background()) + _, err := p.Credential(joined) waiter <- err }() - waitForJoiner(t, p) + waitForJoiner(t, joined) run(context.Background()) if err := <-waiter; err == nil { @@ -420,25 +422,27 @@ func TestDispatcherDropsOldestAndStampsCount(t *testing.T) { } } -// waitForJoiner polls until one caller has joined the in-flight refresh, -// proving the waiter's Credential took the join branch instead of starting -// its own acquisition or short-circuiting on a cached credential. -func waitForJoiner(t *testing.T, p *Provider) { +// The join branch evaluates Done; this test context signals that point without production counters. +type joinContext struct { + context.Context + once sync.Once + joined chan struct{} +} + +func signalJoin(ctx context.Context) *joinContext { + return &joinContext{Context: ctx, joined: make(chan struct{})} +} +func (c *joinContext) Done() <-chan struct{} { + c.once.Do(func() { close(c.joined) }) + return c.Context.Done() +} +func waitForJoiner(t *testing.T, c *joinContext) { t.Helper() - deadline := time.Now().Add(3 * time.Second) - for time.Now().Before(deadline) { - p.mu.Lock() - var n int - if p.refreshing != nil { - n = p.refreshing.waiters - } - p.mu.Unlock() - if n >= 1 { - return - } - time.Sleep(2 * time.Millisecond) + select { + case <-c.joined: + case <-time.After(3 * time.Second): + t.Fatal("caller did not join the production refresh") } - t.Fatal("no waiter joined the refresh call") } func TestFinishRefreshPublishesLoginSuccess(t *testing.T) { @@ -462,14 +466,15 @@ func TestFinishRefreshPublishesLoginSuccess(t *testing.T) { // A waiter joins the reserved slot and must receive the published result. waiter := make(chan error, 1) + joined := signalJoin(context.Background()) go func() { - got, err := p.Credential(context.Background()) + got, err := p.Credential(joined) if err == nil && got != cred { t.Errorf("waiter got %p, want %p", got, cred) } waiter <- err }() - waitForJoiner(t, p) + waitForJoiner(t, joined) p.finishRefresh(call, cred, session, false, nil) if err := <-waiter; err != nil { diff --git a/internal/session/interaction.go b/internal/session/interaction.go new file mode 100644 index 0000000..54452a0 --- /dev/null +++ b/internal/session/interaction.go @@ -0,0 +1,56 @@ +package session + +import ( + "context" + "errors" + "github.com/ShanghaitechGeekPie/geektrust/auth" + "time" +) + +type interactionKey struct{} + +func WithInteraction(ctx context.Context, allow bool) context.Context { + return context.WithValue(ctx, interactionKey{}, allow) +} +func InteractionAllowed(ctx context.Context) bool { + v, ok := ctx.Value(interactionKey{}).(bool) + return !ok || v +} +func (p *Provider) SetIdentity(i auth.IdentityInfo) { + p.mu.Lock() + p.cfg.IdentityIssuer = i.Issuer + p.cfg.IdentitySubject = i.Subject + p.cfg.IdentityKind = i.Kind + p.mu.Unlock() +} +func (p *Provider) httpTimeout() time.Duration { + if p.HTTPTimeout == 0 { + return 30 * time.Second + } + return p.HTTPTimeout +} + +func (p *Provider) SetLegacyGateways(v []string) { + p.mu.Lock() + p.cfg.Gateways = append([]string(nil), v...) + p.cfg.GatewayFilter = false + p.cfg.LegacyGatewayOverride = true + p.mu.Unlock() +} +func (p *Provider) Current() *Credential { p.mu.Lock(); defer p.mu.Unlock(); return p.cur } + +func (p *Provider) Close() { + p.mu.Lock() + p.closed = true + p.cur = nil + p.mu.Unlock() + p.CloseObservers() +} + +type expectedGenerationKey struct{} + +var ErrSessionReplaced = errors.New("session replaced") + +func ExpectGeneration(ctx context.Context, g uint64) context.Context { + return context.WithValue(ctx, expectedGenerationKey{}, g) +} diff --git a/internal/session/live_test.go b/internal/session/live_test.go index 9871eca..8da2e1e 100644 --- a/internal/session/live_test.go +++ b/internal/session/live_test.go @@ -17,6 +17,9 @@ func (ephemeralStore) Load(context.Context) (*State, error) { return nil, nil } func (ephemeralStore) Save(context.Context, *State) error { return nil } func TestECNULiveSession(t *testing.T) { + if os.Getenv("GEEKTRUST_LIVE_TESTS") != "1" { + t.Skip("online tests require explicit GEEKTRUST_LIVE_TESTS=1") + } path := os.Getenv("GEEKTRUST_ECNU_KEYSTORE") if path == "" { t.Skip("explicit live credential required") diff --git a/internal/session/provider.go b/internal/session/provider.go index 78d7f56..2b066ee 100644 --- a/internal/session/provider.go +++ b/internal/session/provider.go @@ -12,20 +12,25 @@ import ( "time" "github.com/ShanghaitechGeekPie/geektrust/auth" - "github.com/ShanghaitechGeekPie/geektrust/deployment" - "github.com/ShanghaitechGeekPie/geektrust/internal/config" "github.com/ShanghaitechGeekPie/geektrust/internal/idsauth" "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" + "github.com/ShanghaitechGeekPie/geektrust/internal/settings" ) // errSMSAuthSessionExpired marks an expiration discovered after the user has // entered the SMS wait. login catches it and rebuilds the whole IDS/controller // authentication chain instead of publishing a terminal login failure. +var ErrIdentityAuthentication = errors.New("identity authentication rejected") + +var ErrStateStorage = errors.New("session storage failure") + var errSMSAuthSessionExpired = errors.New("SMS authentication session expired") // Credential is everything the tunnel and resolver need from a live session. type Credential struct { - ProcessIdentity *deployment.ProcessIdentity + Generation uint64 + LegacyGatewayOverride bool + ProcessIdentity *settings.ProcessIdentity // AppID is the legacy fallback; matched resource rules always take priority. AppID string MissingGatewayGroupFallback bool @@ -35,6 +40,7 @@ type Credential struct { SID string DeviceID string Username string + DisplayName string ConnectionID string CsrfToken string Cookies []*http.Cookie @@ -66,20 +72,22 @@ type CredentialProvider interface { // credentials, restoring a persisted session or re-logging in silently // when the controller does not request SMS. type Provider struct { - cfg *config.Config + cfg *settings.Session logger *slog.Logger prompt SMSPrompter smsHandler SMSHandler // set by SetSMSHandler during web wiring store StateStore Authenticate func(context.Context, *http.Client) (string, error) - ControllerLogin auth.ControllerLogin ChallengeHandler auth.Handler Transport http.RoundTripper + HTTPTimeout time.Duration mu sync.Mutex cur *Credential sdpc *sdpc.Client // last client, for liveness checks refreshing *refreshCall + generation uint64 + closed bool forceLogin bool // set by Invalidate; skips restore on the next refresh dispMu sync.Mutex @@ -94,19 +102,18 @@ type Provider struct { // refreshCall is one in-flight restore/login shared by every concurrent // caller: all waiters block on done and then read the same result. type refreshCall struct { - done chan struct{} // closed once cred/err are populated - cred *Credential - err error - waiters int // joined callers (observability for tests; guarded by p.mu) - leader context.Context + done chan struct{} // closed once cred/err are populated + cred *Credential + err error + leader context.Context } // NewProvider builds a credential provider. prompt may be nil; a login that // requires SMS then returns an error. -func NewProvider(cfg *config.Config, logger *slog.Logger, prompt SMSPrompter) *Provider { - normalized := *cfg - normalized.Compatibility = cfg.Compatibility.Clone() - cfg = &normalized +func NewProvider(source interface{ SessionOptions() settings.Session }, logger *slog.Logger, prompt SMSPrompter) *Provider { + normalized := source.SessionOptions() + normalized.Compatibility = normalized.Compatibility.Clone() + cfg := &normalized return &Provider{ cfg: cfg, logger: logger, @@ -209,11 +216,23 @@ func (p *Provider) Credential(ctx context.Context) (*Credential, error) { return nil, err } p.mu.Lock() + if p.closed { + p.mu.Unlock() + return nil, context.Canceled + } if p.cur != nil { + if g, ok := ctx.Value(expectedGenerationKey{}).(uint64); ok && g != p.cur.Generation { + p.mu.Unlock() + return nil, ErrSessionReplaced + } cred := p.cur p.mu.Unlock() return cred, nil } + if _, ok := ctx.Value(expectedGenerationKey{}).(uint64); ok { + p.mu.Unlock() + return nil, ErrSessionReplaced + } call := p.refreshing if call == nil { call = &refreshCall{done: make(chan struct{}), leader: ctx} @@ -224,7 +243,6 @@ func (p *Provider) Credential(ctx context.Context) (*Credential, error) { p.finishRefresh(call, cred, session, restored, err) return cred, err } - call.waiters++ p.mu.Unlock() select { case <-call.done: @@ -250,7 +268,16 @@ func (p *Provider) Credential(ctx context.Context) (*Credential, error) { // never callbacks), then waiters are released. func (p *Provider) finishRefresh(call *refreshCall, cred *Credential, session *SessionInfo, restored bool, err error) { p.mu.Lock() + if p.closed { + err = context.Canceled + } + if call.leader != nil && call.leader.Err() != nil { + err = call.leader.Err() + } if err == nil { + p.generation++ + cred.Generation = p.generation + session.Generation = p.generation p.cur = cred if restored { p.emit(Event{Kind: EventRestoreOK, Session: session, Message: "已恢复会话:" + session.DisplayName}) @@ -258,7 +285,11 @@ func (p *Provider) finishRefresh(call *refreshCall, cred *Credential, session *S p.emit(Event{Kind: EventLoginSuccess, Session: session, Message: "会话已建立:" + session.DisplayName}) } } else { - p.emit(Event{Kind: EventLoginFailed, Message: SanitizeErrorText(err.Error())}) + kind := EventLoginFailed + if errors.Is(err, auth.ErrInteractionRequired) { + kind = EventInteractionRequired + } + p.emit(Event{Kind: kind, Message: SanitizeErrorText(err.Error())}) } p.refreshing = nil p.mu.Unlock() @@ -335,7 +366,7 @@ func (p *Provider) invalidateLocked() { func (p *Provider) TryForceRelogin() (run func(context.Context), ok bool) { p.mu.Lock() defer p.mu.Unlock() - if p.refreshing != nil { + if p.closed || p.refreshing != nil { return nil, false } call := &refreshCall{done: make(chan struct{})} @@ -389,7 +420,7 @@ func (p *Provider) CheckLoop(ctx context.Context, interval time.Duration) { continue } refreshCtx, cancel := context.WithTimeout(ctx, 45*time.Second) - _, refreshErr := p.Credential(refreshCtx) + _, refreshErr := p.Credential(WithInteraction(refreshCtx, false)) cancel() if err := refreshErr; err != nil { p.logger.Error("silent re-login failed", "err", err) @@ -417,6 +448,9 @@ func (p *Provider) acquire(ctx context.Context, force bool) (*Credential, *Sessi if ctx.Err() != nil { return nil, nil, false, ctx.Err() } + if p.cfg.StrictStorage && errors.Is(err, ErrStateStorage) { + return nil, nil, false, err + } p.logger.Warn("restoring persisted session failed; performing full login", "err", err) } else if cred != nil { p.logger.Info("restored persisted session", "restored", true) @@ -435,8 +469,14 @@ func (p *Provider) acquire(ctx context.Context, force bool) (*Credential, *Sessi // routing policy. Returns (nil, nil, nil) when there is nothing to restore. func (p *Provider) restore(ctx context.Context) (*Credential, *SessionInfo, error) { st, err := p.store.Load(ctx) - if err != nil || st == nil { - return nil, nil, err + if err != nil { + return nil, nil, fmt.Errorf("%w: %w", ErrStateStorage, err) + } + if st == nil { + return nil, nil, nil + } + if st.ControllerURL != p.cfg.BaseURL || st.IdentityIssuer != p.cfg.IdentityIssuer || st.IdentitySubject != p.cfg.IdentitySubject || st.IdentityKind != p.cfg.IdentityKind || st.LoginDomain != p.cfg.LoginDomain { + return nil, nil, nil } if st.SID == "" || len(st.Cookies) == 0 { return nil, nil, nil @@ -460,7 +500,7 @@ func (p *Provider) restore(ctx context.Context) (*Credential, *SessionInfo, erro } jar, _ := cookiejar.New(nil) - hc := &http.Client{Jar: jar, Timeout: 30 * time.Second, Transport: p.Transport} + hc := &http.Client{Jar: jar, Timeout: p.httpTimeout(), Transport: p.Transport} sc := p.newSDPC(hc) cookies := make([]*http.Cookie, 0, len(st.Cookies)) for _, rec := range st.Cookies { @@ -473,13 +513,14 @@ func (p *Provider) restore(ctx context.Context) (*Credential, *SessionInfo, erro if err != nil { return nil, nil, fmt.Errorf("onlineInfo: %w", err) } - if !info.IsOnline { - return nil, nil, errors.New("persisted session is offline") + if !info.IsOnline || st.Username != info.Username { + return nil, nil, nil } cred, err := p.finishLogin(ctx, sc, info.Username) if err != nil { return nil, nil, err } + cred.DisplayName = info.DisplayName p.logger.Info("session online", "user", info.Username, "display_name", info.DisplayName) return cred, newSessionInfo(info, cred, p.cfg.ClientType), nil } @@ -491,6 +532,7 @@ func (p *Provider) restore(ctx context.Context) (*Credential, *SessionInfo, erro func (p *Provider) newSDPC(hc *http.Client) *sdpc.Client { sc := sdpc.NewClient(p.cfg.BaseURL, p.cfg.Platform, p.cfg.DeviceID, hc) sc.LoginDomain = p.cfg.LoginDomain + sc.DomainMapping = p.cfg.DomainMapping if p.cfg.ClientType == "client" { sc.ClientType = sdpc.ClientTypeDesktop } @@ -519,32 +561,7 @@ func (p *Provider) login(ctx context.Context) (*Credential, *SessionInfo, error) // (→ SMS when requested) → session exchange → clientResource. func (p *Provider) loginOnce(ctx context.Context) (*Credential, *SessionInfo, error) { jar, _ := cookiejar.New(nil) - hc := &http.Client{Jar: jar, Timeout: 30 * time.Second, Transport: p.Transport} - if p.ControllerLogin != nil { - sc := p.newSDPC(hc) - if _, err := sc.AuthConfig(ctx, false); err != nil { - return nil, nil, err - } - request := auth.ControllerRequest{URL: p.cfg.BaseURL, DeviceID: p.cfg.DeviceID, Platform: p.cfg.Platform, ClientType: sc.ClientType, LoginDomain: sc.LoginDomain, CSRFToken: sc.CSRF()} - if err := p.ControllerLogin(ctx, hc, request); err != nil { - return nil, nil, err - } - if sc.SID() == "" { - return nil, nil, errors.New("controller authentication did not establish a session") - } - info, err := sc.OnlineInfo(ctx) - if err != nil { - return nil, nil, err - } - if !info.IsOnline { - return nil, nil, errors.New("controller authentication reports offline") - } - cred, err := p.finishLogin(ctx, sc, info.Username) - if err != nil { - return nil, nil, err - } - return cred, newSessionInfo(info, cred, p.cfg.ClientType), nil - } + hc := &http.Client{Jar: jar, Timeout: p.httpTimeout(), Transport: p.Transport} authenticate := p.Authenticate if authenticate == nil { authenticate = func(ctx context.Context, hc *http.Client) (string, error) { @@ -559,7 +576,7 @@ func (p *Provider) loginOnce(ctx context.Context) (*Credential, *SessionInfo, er } } if _, err := authenticate(ctx, hc); err != nil { - return nil, nil, fmt.Errorf("identity authentication: %w", err) + return nil, nil, fmt.Errorf("%w: %w", ErrIdentityAuthentication, err) } sc := p.newSDPC(hc) ac, err := sc.AuthConfig(ctx, true) @@ -603,27 +620,18 @@ func (p *Provider) loginOnce(ctx context.Context) (*Credential, *SessionInfo, er } p.logger.Info("session established", "user", info.Username, "display_name", info.DisplayName) - // On the desktop path the session is in client mode: bind this device - // as a trusted terminal so subsequent full logins may skip SMS. The - // browser path cannot bind (server rejects with 75500000). - if needSMS && sc.ClientType == sdpc.ClientTypeDesktop { - if err := sc.TrustDevice(ctx); err != nil { - p.logger.Warn("trust device binding failed; SMS will be required on next full login", "err", err) - } else { - p.logger.Info("device bound as trusted terminal") - } - } cred, err := p.finishLogin(ctx, sc, info.Username) if err != nil { return nil, nil, err } + cred.DisplayName = info.DisplayName return cred, newSessionInfo(info, cred, p.cfg.ClientType), nil } // smsFlow completes controller-requested SMS verification. func (p *Provider) smsFlow(ctx context.Context, sc *sdpc.Client) (string, error) { - if p.smsHandler == nil && p.prompt == nil && p.ChallengeHandler == nil { - return "", &auth.RequiredError{Challenge: auth.Challenge{Method: "auth/sms"}} + if !InteractionAllowed(ctx) || (p.smsHandler == nil && p.prompt == nil && p.ChallengeHandler == nil) { + return "", &auth.RequiredError{Challenge: auth.Challenge{Info: auth.ChallengeInfo{Method: auth.SMS}}} } if err := sc.SendSMS(ctx); err != nil { // 75500401: a code was already sent and is still valid — verify it @@ -641,15 +649,16 @@ func (p *Provider) smsFlow(ctx context.Context, sc *sdpc.Client) (string, error) defer cancel() ctx = challengeCtx expires, _ := challengeCtx.Deadline() - code, promptErr = p.ChallengeHandler(challengeCtx, auth.Challenge{Method: "auth/sms", ExpiresAt: expires}) - if err := challengeCtx.Err(); err != nil { - return "", err - } + return p.challengeFlow(challengeCtx, sc, expires) } else if p.smsHandler != nil { // Keep typed controller errors for the web layer. An expired auth // session also carries the private restart marker consumed by login. - resendFn := func(ctx context.Context) error { - err := sc.SendSMS(ctx) + authenticationCtx := ctx + resendFn := func(parent context.Context) error { + call, cancel := context.WithCancel(parent) + stop := context.AfterFunc(authenticationCtx, cancel) + defer func() { stop(); cancel() }() + err := sc.SendSMS(call) if sdpc.IsSessionExpired(err) { return fmt.Errorf("%w: resend SMS: %w", errSMSAuthSessionExpired, err) } @@ -682,26 +691,42 @@ func (p *Provider) finishLogin(ctx context.Context, sc *sdpc.Client, username st p.logger.Info("resource policy loaded", "domain_rules", len(res.DomainRules), "suffix_rules", len(res.SuffixRules), "ip_rules", len(res.IPRules)) gateways := p.cfg.Gateways - if len(gateways) == 0 { + if !p.cfg.GatewayFilter && !p.cfg.LegacyGatewayOverride { gateways = res.Gateways } - if len(gateways) == 0 { + if len(gateways) == 0 && !p.cfg.GatewayFilter { gateways = append([]string(nil), p.cfg.Compatibility.FallbackGateways...) } if len(gateways) == 0 { return nil, fmt.Errorf("controller supplied no gateway addresses") } + if p.cfg.GatewayFilter { + candidates := res.Gateways + if len(candidates) == 0 { + candidates = p.cfg.Compatibility.FallbackGateways + } + gateways = nil + for _, candidate := range candidates { + for _, allowed := range p.cfg.Gateways { + if candidate == allowed { + gateways = append(gateways, candidate) + break + } + } + } + } dns := p.cfg.DNS - if len(dns) == 0 { + if !p.cfg.DNSConfigured && len(dns) == 0 { dns = res.DNS } cred := &Credential{ + LegacyGatewayOverride: p.cfg.LegacyGatewayOverride, ProcessIdentity: p.cfg.Compatibility.ProcessIdentity, AppID: p.cfg.Compatibility.FallbackAppID, MissingGatewayGroupFallback: p.cfg.Compatibility.MissingGatewayGroupFallback, AllowTCPFallback: p.cfg.Compatibility.TCPToL3Fallback, - GatewayOverride: len(p.cfg.Gateways) != 0, + GatewayOverride: p.cfg.GatewayFilter, SID: sc.SID(), DeviceID: p.cfg.DeviceID, Username: username, @@ -718,6 +743,7 @@ func (p *Provider) finishLogin(ctx context.Context, sc *sdpc.Client, username st records = append(records, CookieRecord{Name: ck.Name, Value: ck.Value}) } if err := p.store.Save(ctx, &State{ + Version: 1, ControllerURL: p.cfg.BaseURL, IdentityIssuer: p.cfg.IdentityIssuer, IdentitySubject: p.cfg.IdentitySubject, IdentityKind: p.cfg.IdentityKind, LoginDomain: p.cfg.LoginDomain, Username: username, SID: cred.SID, DeviceID: cred.DeviceID, CsrfToken: cred.CsrfToken, @@ -725,7 +751,10 @@ func (p *Provider) finishLogin(ctx context.Context, sc *sdpc.Client, username st Gateways: cred.Gateways, ClientType: p.cfg.ClientType, }); err != nil { - // Credentials are live; persistence failure should not abort the login. + if p.cfg.StrictStorage { + return nil, err + } + // Legacy callers retain their persistence behavior. p.logger.Error("failed to persist session state", "err", err) } diff --git a/internal/session/provider_test.go b/internal/session/provider_test.go index 66cf613..c55a253 100644 --- a/internal/session/provider_test.go +++ b/internal/session/provider_test.go @@ -11,13 +11,11 @@ import ( "os" "path/filepath" "runtime" - "sync" "sync/atomic" "testing" - "time" - "github.com/ShanghaitechGeekPie/geektrust/internal/config" "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" + "github.com/ShanghaitechGeekPie/geektrust/internal/settings" ) type smsHandlerFunc func(context.Context, func(context.Context) error) (string, error) @@ -30,68 +28,40 @@ func (f smsHandlerFunc) Prompt(ctx context.Context, resend func(context.Context) // must observe the same in-flight login result (regression: a size-1 result // channel stranded all waiters but one). func TestProviderSingleFlightBroadcast(t *testing.T) { - p := &Provider{store: NewStore(filepath.Join(t.TempDir(), "state.enc"))} - - var logins atomic.Int32 - // Stand in for the real login: slow, and counts invocations. - acquire := func(ctx context.Context) (*Credential, error) { - logins.Add(1) - time.Sleep(50 * time.Millisecond) - return &Credential{SID: "shared"}, nil + p := failingProvider(t) + entered := make(chan struct{}) + release := make(chan struct{}) + sentinel := errors.New("fixture authentication stopped") + var calls atomic.Int32 + p.Authenticate = func(context.Context, *http.Client) (string, error) { + if calls.Add(1) == 1 { + close(entered) + } + <-release + return "", sentinel } - - const waiters = 8 - var wg sync.WaitGroup - results := make([]*Credential, waiters) - errs := make([]error, waiters) - - // Drive the same code shape as Credential: one leader runs acquire, - // the rest wait on the shared call. - p.mu.Lock() - call := &refreshCall{done: make(chan struct{})} - p.refreshing = call - p.mu.Unlock() - - for i := range waiters { - wg.Add(1) - go func(i int) { - defer wg.Done() - if i == 0 { - cred, err := acquire(context.Background()) - p.mu.Lock() - p.cur = cred - p.refreshing = nil - p.mu.Unlock() - call.cred, call.err = cred, err - close(call.done) - results[i], errs[i] = cred, err - return - } - // Waiters join the in-flight call. - p.mu.Lock() - c := p.refreshing - p.mu.Unlock() - if c == nil { - // Leader already finished: cached path. - p.mu.Lock() - results[i] = p.cur - p.mu.Unlock() - return - } - <-c.done - results[i], errs[i] = c.cred, c.err - }(i) + const count = 8 + out := make(chan error, count) + go func() { _, e := p.Credential(context.Background()); out <- e }() + <-entered + var joined []*joinContext + for i := 1; i < count; i++ { + ctx := signalJoin(context.Background()) + joined = append(joined, ctx) + go func() { _, e := p.Credential(ctx); out <- e }() } - wg.Wait() - - if n := logins.Load(); n != 1 { - t.Errorf("login ran %d times, want exactly 1", n) + for _, ctx := range joined { + waitForJoiner(t, ctx) } - for i := range waiters { - if errs[i] != nil || results[i] == nil || results[i].SID != "shared" { - t.Errorf("waiter %d got cred=%v err=%v", i, results[i], errs[i]) + close(release) + for i := 0; i < count; i++ { + if e := <-out; !errors.Is(e, sentinel) { + t.Fatalf("caller lost result: %v", e) } } + if calls.Load() != 1 { + t.Fatal("production authentication repeated") + } } func TestRestoreSkipsDifferentClientType(t *testing.T) { @@ -120,7 +90,7 @@ func TestRestoreSkipsDifferentClientType(t *testing.T) { } p := &Provider{ - cfg: &config.Config{ + cfg: &settings.Session{ BaseURL: "http://127.0.0.1:1", Platform: "Mac", DeviceID: deviceID, @@ -144,33 +114,21 @@ func TestRestoreSkipsDifferentClientType(t *testing.T) { // restore the rejected persisted session (regression: restore ran first and // handed back the very credential the caller declared dead). func TestInvalidateSkipsRestore(t *testing.T) { - dir := t.TempDir() - st := NewStore(filepath.Join(dir, "state.enc")) - if err := st.Save(context.Background(), &State{SID: "old-session", DeviceID: "D", Cookies: []CookieRecord{{Name: "sid", Value: "old-session"}}}); err != nil { - t.Fatal(err) - } - p := &Provider{store: st} - + var probes atomic.Int32 + p := newRestoreFixture(t, func(w http.ResponseWriter, r *http.Request) { probes.Add(1); restoreHandler(w, r) }) + called := false + stop := errors.New("forced login") + p.Authenticate = func(context.Context, *http.Client) (string, error) { called = true; return "", stop } p.Invalidate() - p.mu.Lock() - skip := p.forceLogin - p.mu.Unlock() - if !skip { - t.Fatal("Invalidate must set forceLogin") + if _, e := p.Credential(context.Background()); !errors.Is(e, stop) || !called { + t.Fatal("real login path not used") } - // acquire consumes the flag. - p.mu.Lock() - consumed := p.forceLogin - p.forceLogin = false - p.mu.Unlock() - if !consumed { - t.Fatal("forceLogin flag lost before acquire") + if probes.Load() != 0 { + t.Fatal("invalidated session was restored") } } -// TestStoreKeyPermissionTightening: a pre-existing world-readable key file is -// tightened to 0600 on use (regression: permissive modes were accepted). -func TestStoreKeyPermissionTightening(t *testing.T) { +func TestStoreReadPreservesExistingPermissions(t *testing.T) { dir := t.TempDir() keyPath := filepath.Join(dir, "state.enc.key") key := make([]byte, 32) @@ -188,8 +146,8 @@ func TestStoreKeyPermissionTightening(t *testing.T) { if err != nil { t.Fatal(err) } - if runtime.GOOS != "windows" && info.Mode().Perm() != 0o600 { - t.Errorf("key perm = %o, want 600", info.Mode().Perm()) + if runtime.GOOS != "windows" && info.Mode().Perm() != 0o644 { + t.Errorf("key perm = %o, want 644", info.Mode().Perm()) } // The original key must still decrypt the state (tighten, never replace). got, err := st.Load(context.Background()) @@ -198,9 +156,9 @@ func TestStoreKeyPermissionTightening(t *testing.T) { } } -// TestStoreKeyExclusiveCreate: when the key appears between the missing-check +// TestStoreReusesExistingKey: when the key appears between the missing-check // and creation, the existing key wins (O_EXCL path). -func TestStoreKeyExclusiveCreate(t *testing.T) { +func TestStoreReusesExistingKey(t *testing.T) { dir := t.TempDir() st := NewStore(filepath.Join(dir, "state.enc")) // Simulate the winner: create the key first. diff --git a/internal/session/routing.go b/internal/session/routing.go index 0cbefa7..b221c88 100644 --- a/internal/session/routing.go +++ b/internal/session/routing.go @@ -3,6 +3,9 @@ package session // GatewaysForGroup restricts configured gateways to the assigned group. Missing // groups may use the flattened list only when compatibility explicitly allows it. func (c *Credential) GatewaysForGroup(group string) []string { + if c.LegacyGatewayOverride { + return append([]string(nil), c.Gateways...) + } var assigned []string if c.Policy != nil { if group == "" { @@ -16,7 +19,9 @@ func (c *Credential) GatewaysForGroup(group string) []string { assigned = c.Policy.Gateways } if len(assigned) == 0 { - assigned = c.Gateways + if !c.GatewayOverride { + assigned = c.Gateways + } } } if c.GatewayOverride { diff --git a/internal/session/store.go b/internal/session/store.go index 124581c..06f0e18 100644 --- a/internal/session/store.go +++ b/internal/session/store.go @@ -11,16 +11,22 @@ import ( "encoding/json" "errors" "fmt" - "io" "os" - "path/filepath" "time" - "github.com/ShanghaitechGeekPie/geektrust/internal/privatefile" + "github.com/ShanghaitechGeekPie/geektrust/internal/storage" ) // State is the persisted session (encrypted, 0600). type State struct { + Version int `json:"version"` + ControllerURL string `json:"controller_url"` + IdentityIssuer string `json:"identity_issuer"` + IdentitySubject string `json:"identity_subject"` + IdentityKind string `json:"identity_kind"` + LoginDomain string `json:"login_domain"` + Username string `json:"username"` + SID string `json:"sid"` DeviceID string `json:"device_id"` CsrfToken string `json:"csrf_token"` @@ -56,53 +62,65 @@ func (s *Store) keyPath() string { return s.path + ".key" } // Load reads and decrypts the state. It returns (nil, nil) when no state file // exists yet. func (s *Store) Load(ctx context.Context) (*State, error) { - if err := ctx.Err(); err != nil { - return nil, err - } - sealed, err := os.ReadFile(s.path) - if err != nil { - if errors.Is(err, os.ErrNotExist) { - return nil, nil - } - return nil, fmt.Errorf("read state: %w", err) - } - key, err := s.readKey() - if err != nil { - return nil, fmt.Errorf("state key: %w", err) - } - plain, err := decrypt(key, sealed) - if err != nil { - return nil, fmt.Errorf("decrypt state: %w", err) + b, e := s.LoadBytes(ctx) + if e != nil || len(b) == 0 { + return nil, e } var st State - if err := json.Unmarshal(plain, &st); err != nil { - return nil, fmt.Errorf("decode state: %w", err) + if e = json.Unmarshal(b, &st); e != nil { + return nil, e } return &st, nil } - -// Save encrypts and atomically writes the state. func (s *Store) Save(ctx context.Context, st *State) error { - if err := ctx.Err(); err != nil { - return err + v := *st + v.SavedAt = time.Now() + b, e := json.Marshal(v) + if e != nil { + return e } - st.SavedAt = time.Now() - plain, err := json.Marshal(st) - if err != nil { - return fmt.Errorf("encode state: %w", err) + return s.SaveBytes(ctx, b) +} +func (s *Store) LoadBytes(ctx context.Context) ([]byte, error) { + if e := ctx.Err(); e != nil { + return nil, e } - key, err := s.loadOrCreateKey() - if err != nil { - return fmt.Errorf("state key: %w", err) + sealed, e := os.ReadFile(s.path) + if errors.Is(e, os.ErrNotExist) { + return nil, nil } - sealed, err := encrypt(key, plain) - if err != nil { - return fmt.Errorf("encrypt state: %w", err) + if e != nil { + return nil, e + } + key, e := s.readKey() + if e != nil { + return nil, e + } + return decrypt(key, sealed) +} +func (s *Store) SaveBytes(ctx context.Context, b []byte) error { + if e := ctx.Err(); e != nil { + return e + } + key, e := s.loadOrCreateKey() + if e != nil { + return e + } + sealed, e := encrypt(key, b) + if e != nil { + return e } - if err := writeFileAtomic(s.path, sealed, 0o600); err != nil { - return fmt.Errorf("write state: %w", err) + return storage.WriteAtomic(s.path, sealed, 0600) +} +func (s *Store) Delete(ctx context.Context) error { + if e := ctx.Err(); e != nil { + return e + } + e := os.Remove(s.path) + if errors.Is(e, os.ErrNotExist) { + return nil } - return nil + return e } func (s *Store) readKey() ([]byte, error) { @@ -114,49 +132,25 @@ func (s *Store) readKey() ([]byte, error) { if len(key) != 32 { return nil, fmt.Errorf("%s: expected 32 bytes, got %d", path, len(key)) } - if err := privatefile.Protect(path); err != nil { - return nil, fmt.Errorf("protect state key: %w", err) - } return key, nil } func (s *Store) loadOrCreateKey() ([]byte, error) { - key, err := s.readKey() - if err == nil { + key, e := s.readKey() + if e == nil { return key, nil } - if !errors.Is(err, os.ErrNotExist) { - // A present-but-invalid key file is fatal: we must never overwrite it - // (that would destroy the only copy able to decrypt the state). - return nil, err + if !errors.Is(e, os.ErrNotExist) { + return nil, e } - // Create with O_EXCL: concurrent first-time saves (e.g. two processes) - // can never overwrite each other's key, which would leave the other's - // ciphertext permanently undecryptable. The loser reads the winner's key. key = make([]byte, 32) - if _, err := rand.Read(key); err != nil { - return nil, err - } - f, err := os.OpenFile(s.keyPath(), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) - if err != nil { - if errors.Is(err, os.ErrExist) { - return s.readKey() - } - return nil, err - } - if err := privatefile.Protect(s.keyPath()); err != nil { - f.Close() - os.Remove(s.keyPath()) - return nil, err + if _, e = rand.Read(key); e != nil { + return nil, e } - _, werr := f.Write(key) - cerr := f.Close() - if werr != nil || cerr != nil { - os.Remove(s.keyPath()) // never leave a half-written key behind - if werr != nil { - return nil, werr - } - return nil, cerr + if e = storage.CreateExclusive(s.keyPath(), key); errors.Is(e, os.ErrExist) { + return s.readKey() + } else if e != nil { + return nil, e } return key, nil } @@ -197,36 +191,7 @@ func decrypt(key, sealed []byte) ([]byte, error) { // writeFileAtomic writes via temp file + rename so secrets are never left // half-written. func writeFileAtomic(path string, data []byte, perm os.FileMode) error { - dir := filepath.Dir(path) - if err := os.MkdirAll(dir, 0o700); err != nil { - return err - } - tmp, err := os.CreateTemp(dir, ".state-*.tmp") - if err != nil { - return err - } - tmpName := tmp.Name() - defer os.Remove(tmpName) - if err := privatefile.Protect(tmpName); err != nil { - tmp.Close() - return err - } - if _, err := io.WriteString(tmp, string(data)); err != nil { - tmp.Close() - return err - } - if err := tmp.Chmod(perm); err != nil { - tmp.Close() - return err - } - if err := tmp.Sync(); err != nil { - tmp.Close() - return err - } - if err := tmp.Close(); err != nil { - return err - } - return os.Rename(tmpName, path) + return storage.WriteAtomic(path, data, perm) } // StateStore persists session state; embedding applications can supply protected storage. diff --git a/internal/settings/compatibility.go b/internal/settings/compatibility.go new file mode 100644 index 0000000..704858c --- /dev/null +++ b/internal/settings/compatibility.go @@ -0,0 +1,73 @@ +// LegacyCompatibility is the version-1 file representation. +package settings + +import ( + "fmt" + "net" + "strconv" + "strings" + "unicode" +) + +// Compatibility is opt-in. Its zero value uses controller policy without +// deployment-specific fallbacks. These settings never override a server denial. +type Compatibility struct { + ProcessIdentity *ProcessIdentity `toml:"process_identity" json:"process_identity,omitempty"` + FallbackAppID string `toml:"fallback_app_id" json:"fallback_app_id,omitempty"` + FallbackGateways []string `toml:"fallback_gateways" json:"fallback_gateways,omitempty"` + GatewayServerName string `toml:"gateway_server_name" json:"gateway_server_name,omitempty"` + MissingGatewayGroupFallback bool `toml:"missing_gateway_group_fallback" json:"missing_gateway_group_fallback,omitempty"` + TCPToL3Fallback bool `toml:"tcp_to_l3_fallback" json:"tcp_to_l3_fallback,omitempty"` +} + +// Clone separates an active client's settings from caller-owned configuration. +func (c Compatibility) Clone() Compatibility { + if c.ProcessIdentity != nil { + identity := *c.ProcessIdentity + c.ProcessIdentity = &identity + } + c.FallbackGateways = append([]string(nil), c.FallbackGateways...) + return c +} + +func (c Compatibility) Validate() error { + if c.ProcessIdentity != nil { + if err := c.ProcessIdentity.Validate(); err != nil { + return err + } + } + if len(c.FallbackAppID) > 256 || strings.IndexFunc(c.FallbackAppID, unicode.IsControl) >= 0 { + return fmt.Errorf("compatibility.fallback_app_id must be at most 256 characters without control characters") + } + if c.GatewayServerName != "" { + name := c.GatewayServerName + if len(name) > 253 || strings.ContainsAny(name, "/\\:@?# \t\r\n") || strings.IndexFunc(name, unicode.IsControl) >= 0 { + return fmt.Errorf("compatibility.gateway_server_name must be a TLS hostname without a port") + } + } + for _, address := range c.FallbackGateways { + host, port, err := net.SplitHostPort(address) + number, portErr := strconv.Atoi(port) + if err != nil || host == "" || portErr != nil || number < 1 || number > 65535 || strings.ContainsAny(host, "/\\@?# \t\r\n") { + return fmt.Errorf("compatibility.fallback_gateways entries must be host:port with port 1-65535") + } + } + return nil +} + +// ProcessIdentity overrides the process metadata sent to the gateway. It is +// protocol metadata, not a claim about a locally running or verified process. +type ProcessIdentity struct { + Name string `toml:"name" json:"name"` + Platform string `toml:"platform" json:"platform"` + Path string `toml:"path" json:"path"` +} + +func (p ProcessIdentity) Validate() error { + for _, value := range []string{p.Name, p.Platform, p.Path} { + if strings.TrimSpace(value) == "" || len(value) > 4096 || strings.IndexFunc(value, unicode.IsControl) >= 0 { + return fmt.Errorf("compatibility.process_identity requires name, platform and path without control characters (max 4096 bytes each)") + } + } + return nil +} diff --git a/internal/settings/session.go b/internal/settings/session.go new file mode 100644 index 0000000..7676211 --- /dev/null +++ b/internal/settings/session.go @@ -0,0 +1,17 @@ +// Package settings contains normalized runtime values, independent of file formats. +package settings + +type Session struct { + DomainMapping *bool + BaseURL, DeviceID, Platform, ClientType, LoginDomain string + Keystore, StateFile string + Gateways, DNS []string + Compatibility Compatibility + IdentityIssuer, IdentitySubject, IdentityKind string + LegacyGatewayOverride bool + DNSConfigured bool + StrictStorage bool + GatewayFilter bool +} + +func (s Session) SessionOptions() Session { return s } diff --git a/internal/storage/files.go b/internal/storage/files.go new file mode 100644 index 0000000..88b1ec2 --- /dev/null +++ b/internal/storage/files.go @@ -0,0 +1,95 @@ +// Package storage provides the CLI's small, durable private-file boundary. +package storage + +import ( + "context" + "github.com/ShanghaitechGeekPie/geektrust/internal/privatefile" + "os" + "path/filepath" +) + +func WriteAtomic(path string, data []byte, mode os.FileMode) error { + dir := filepath.Dir(path) + if e := os.MkdirAll(dir, 0700); e != nil { + return e + } + f, e := os.CreateTemp(dir, ".geektrust-*") + if e != nil { + return e + } + name := f.Name() + defer os.Remove(name) + if e = privatefile.Protect(name); e != nil { + f.Close() + return e + } + if _, e = f.Write(data); e != nil { + f.Close() + return e + } + if e = f.Chmod(mode); e != nil { + f.Close() + return e + } + if e = f.Sync(); e != nil { + f.Close() + return e + } + if e = f.Close(); e != nil { + return e + } + if e = os.Rename(name, path); e != nil { + return e + } + return syncDirectory(dir) +} +func CreateExclusive(path string, data []byte) error { + dir := filepath.Dir(path) + if e := os.MkdirAll(dir, 0700); e != nil { + return e + } + f, e := os.CreateTemp(dir, ".geektrust-new-*") + if e != nil { + return e + } + name := f.Name() + defer os.Remove(name) + if e = privatefile.Protect(name); e != nil { + f.Close() + return e + } + if _, e = f.Write(data); e != nil { + f.Close() + return e + } + if e = f.Sync(); e != nil { + f.Close() + return e + } + if e = f.Close(); e != nil { + return e + } + if e = os.Link(name, path); e != nil { + return e + } + return syncDirectory(dir) +} + +type CredentialFile string + +func (p CredentialFile) Load(ctx context.Context) ([]byte, error) { + if e := ctx.Err(); e != nil { + return nil, e + } + return os.ReadFile(string(p)) +} +func (p CredentialFile) Save(ctx context.Context, b []byte) error { + if e := ctx.Err(); e != nil { + return e + } + target, e := filepath.EvalSymlinks(string(p)) + if e != nil { + return e + } + return WriteAtomic(target, b, 0600) +} diff --git a/internal/storage/files_test.go b/internal/storage/files_test.go new file mode 100644 index 0000000..9ace318 --- /dev/null +++ b/internal/storage/files_test.go @@ -0,0 +1,39 @@ +package storage + +import ( + "context" + "os" + "path/filepath" + "sync" + "testing" + "time" +) + +func TestExclusivePublicationAndCredentialLock(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "identity") + var wg sync.WaitGroup + for i := 0; i < 8; i++ { + wg.Add(1) + go func() { defer wg.Done(); _ = CreateExclusive(p, []byte("complete identity")) }() + } + wg.Wait() + b, e := os.ReadFile(p) + if e != nil || string(b) != "complete identity" { + t.Fatal("partially published exclusive file") + } + key := CredentialFile(filepath.Join(dir, "credential")) + if e = WriteAtomic(string(key), []byte("fixture"), 0600); e != nil { + t.Fatal(e) + } + unlock, e := key.Lock(context.Background()) + if e != nil { + t.Fatal(e) + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + if _, e = key.Lock(ctx); e == nil { + t.Fatal("lock did not honor cancellation") + } + unlock() +} diff --git a/internal/storage/lock_unix.go b/internal/storage/lock_unix.go new file mode 100644 index 0000000..02833ee --- /dev/null +++ b/internal/storage/lock_unix.go @@ -0,0 +1,39 @@ +//go:build !windows + +package storage + +import ( + "context" + "errors" + "golang.org/x/sys/unix" + "os" + "path/filepath" + "time" +) + +func (p CredentialFile) Lock(ctx context.Context) (func(), error) { + canonical, e := filepath.EvalSymlinks(string(p)) + if e != nil { + return nil, e + } + f, e := os.OpenFile(canonical+".lock", os.O_CREATE|os.O_RDWR, 0600) + if e != nil { + return nil, e + } + for { + e = unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB) + if e == nil { + return func() { unix.Flock(int(f.Fd()), unix.LOCK_UN); f.Close() }, nil + } + if !errors.Is(e, unix.EWOULDBLOCK) { + f.Close() + return nil, e + } + select { + case <-ctx.Done(): + f.Close() + return nil, ctx.Err() + case <-time.After(20 * time.Millisecond): + } + } +} diff --git a/internal/storage/lock_windows.go b/internal/storage/lock_windows.go new file mode 100644 index 0000000..93aed5b --- /dev/null +++ b/internal/storage/lock_windows.go @@ -0,0 +1,38 @@ +package storage + +import ( + "context" + "errors" + "golang.org/x/sys/windows" + "os" + "path/filepath" + "time" +) + +func (p CredentialFile) Lock(ctx context.Context) (func(), error) { + canonical, e := filepath.EvalSymlinks(string(p)) + if e != nil { + return nil, e + } + f, e := os.OpenFile(canonical+".lock", os.O_CREATE|os.O_RDWR, 0600) + if e != nil { + return nil, e + } + ov := &windows.Overlapped{} + for { + e = windows.LockFileEx(windows.Handle(f.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, ov) + if e == nil { + return func() { windows.UnlockFileEx(windows.Handle(f.Fd()), 0, 1, 0, ov); f.Close() }, nil + } + if !errors.Is(e, windows.ERROR_LOCK_VIOLATION) { + f.Close() + return nil, e + } + select { + case <-ctx.Done(): + f.Close() + return nil, ctx.Err() + case <-time.After(20 * time.Millisecond): + } + } +} diff --git a/internal/storage/permissions_windows_test.go b/internal/storage/permissions_windows_test.go new file mode 100644 index 0000000..e369a8d --- /dev/null +++ b/internal/storage/permissions_windows_test.go @@ -0,0 +1,30 @@ +package storage + +import ( + "golang.org/x/sys/windows" + "os" + "path/filepath" + "testing" +) + +func TestSecretFileHasProtectedDACL(t *testing.T) { + path := filepath.Join(t.TempDir(), "secret") + if e := WriteAtomic(path, []byte("fixture"), 0600); e != nil { + t.Fatal(e) + } + if b, e := os.ReadFile(path); e != nil || string(b) != "fixture" { + t.Fatal("secret write failed") + } + sd, e := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION) + if e != nil { + t.Fatal(e) + } + control, _, e := sd.Control() + if e != nil || control&windows.SE_DACL_PROTECTED == 0 { + t.Fatal("secret inherited a parent DACL") + } + dacl, _, e := sd.DACL() + if e != nil || dacl == nil || dacl.AceCount != 2 { + t.Fatal("expected current-user and LocalSystem access only") + } +} diff --git a/internal/storage/sync_unix.go b/internal/storage/sync_unix.go new file mode 100644 index 0000000..b1af323 --- /dev/null +++ b/internal/storage/sync_unix.go @@ -0,0 +1,14 @@ +//go:build !windows + +package storage + +import "os" + +func syncDirectory(path string) error { + f, e := os.Open(path) + if e != nil { + return e + } + defer f.Close() + return f.Sync() +} diff --git a/internal/storage/sync_windows.go b/internal/storage/sync_windows.go new file mode 100644 index 0000000..e0e2a2e --- /dev/null +++ b/internal/storage/sync_windows.go @@ -0,0 +1,3 @@ +package storage + +func syncDirectory(string) error { return nil } diff --git a/internal/tunnel/line.go b/internal/tunnel/line.go index 188deee..ea3d9bd 100644 --- a/internal/tunnel/line.go +++ b/internal/tunnel/line.go @@ -216,16 +216,6 @@ func closeLineResults(results <-chan lineDialResult, remaining int) { } } -// Best retains the diagnostic line-selection API. Runtime callers should use -// DialTLS so the successful connection is not discarded and opened again. -func (l *Lines) Best(ctx context.Context) (string, error) { - conn, addr, err := l.DialTLS(ctx) - if conn != nil { - conn.Close() - } - return addr, err -} - func probeGatewayTLS(ctx context.Context, addr string) (net.Conn, error) { return probeGatewayTLSWithDialer(ctx, addr, nil, nil, nil) } diff --git a/internal/tunnel/line_test.go b/internal/tunnel/line_test.go index a7a9c47..140894c 100644 --- a/internal/tunnel/line_test.go +++ b/internal/tunnel/line_test.go @@ -41,7 +41,7 @@ func TestBestRequiresGatewayTLS(t *testing.T) { roots := x509.NewCertPool() roots.AddCert(tlsServer.Certificate()) lines.TLSConfig = &tls.Config{RootCAs: roots} - got, err := lines.Best(ctx) + got, err := lines.bestForTest(ctx) if err != nil { t.Fatal(err) } @@ -61,7 +61,7 @@ func TestGatewayTLSRejectsUntrustedCertificateByDefault(t *testing.T) { addr := strings.TrimPrefix(server.URL, "https://") ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() - if _, err := NewLines([]string{addr}).Best(ctx); err == nil { + if _, err := NewLines([]string{addr}).bestForTest(ctx); err == nil { t.Fatal("untrusted gateway certificate was accepted") } } @@ -91,17 +91,17 @@ func TestGatewayTrustOnFirstUsePinsPublicKey(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() newLines := func() *Lines { l := NewLines([]string{addr}); l.GatewayTrustStore = store; return l } - if _, err := newLines().Best(ctx); err != nil { + if _, err := newLines().bestForTest(ctx); err != nil { t.Fatal(err) } if pin, _ := store.LoadPin(ctx, addr); len(pin) != 32 { t.Fatal("gateway public key was not persisted") } - if _, err := newLines().Best(ctx); err != nil { + if _, err := newLines().bestForTest(ctx); err != nil { t.Fatalf("matching gateway pin rejected: %v", err) } store.SavePin(ctx, addr, make([]byte, 32)) - if _, err := newLines().Best(ctx); err == nil || !strings.Contains(err.Error(), "public key changed") { + if _, err := newLines().bestForTest(ctx); err == nil || !strings.Contains(err.Error(), "public key changed") { t.Fatalf("changed gateway key accepted: %v", err) } } @@ -179,3 +179,11 @@ func TestAllLinesTriedIncludesRecentTLSFailures(t *testing.T) { t.Fatal("expired TLS failure must be attempted again") } } + +func (l *Lines) bestForTest(ctx context.Context) (string, error) { + conn, addr, err := l.DialTLS(ctx) + if conn != nil { + conn.Close() + } + return addr, err +} diff --git a/internal/tunnel/reconnect.go b/internal/tunnel/reconnect.go index 4c5bab9..2a12fe8 100644 --- a/internal/tunnel/reconnect.go +++ b/internal/tunnel/reconnect.go @@ -397,7 +397,7 @@ func (m *Manager) ForApp(ctx context.Context, appID string) (*Manager, error) { return nil, errors.New("missing resource policy") } group := c.GatewayGroupForApp(appID) - if group == "" { + if group == "" && sameGatewayAddresses(c.Gateways, c.GatewaysForGroup("")) { return m, nil } m.groupsMu.Lock() @@ -423,3 +423,15 @@ func (m *Manager) ForApp(ctx context.Context, appID string) (*Manager, error) { m.groupsMu.Unlock() return g, nil } + +func sameGatewayAddresses(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} diff --git a/internal/tunnel/reset.go b/internal/tunnel/reset.go new file mode 100644 index 0000000..47f6ef0 --- /dev/null +++ b/internal/tunnel/reset.go @@ -0,0 +1,16 @@ +package tunnel + +func (m *Manager) Reset() { + m.mu.Lock() + if m.cur != nil { + m.cur.Close() + m.cur = nil + } + m.mu.Unlock() + m.groupsMu.Lock() + for key, g := range m.groups { + g.Close() + delete(m.groups, key) + } + m.groupsMu.Unlock() +} diff --git a/internal/tunnel/tcp.go b/internal/tunnel/tcp.go index 485805d..dd72c9a 100644 --- a/internal/tunnel/tcp.go +++ b/internal/tunnel/tcp.go @@ -66,6 +66,11 @@ type tcpAuthRequest struct { // TCPAuthError is an explicit gateway authentication rejection. It is terminal // across both gateway selection and stream-to-L3 compatibility fallback. +type TCPSetupError struct{ Err error } + +func (e *TCPSetupError) Error() string { return "TCP stream setup: " + e.Err.Error() } +func (e *TCPSetupError) Unwrap() error { return e.Err } + type TCPAuthError struct{ Code int64 } func (e *TCPAuthError) Error() string { @@ -123,6 +128,10 @@ func ShouldFallbackToL3(err error) bool { if err == nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { return false } + var setup *TCPSetupError + if !errors.As(err, &setup) { + return false + } var rejected *TCPAuthError if errors.As(err, &rejected) { return false @@ -133,7 +142,7 @@ func ShouldFallbackToL3(err error) bool { } // Only incomplete setup exchanges can indicate an unsupported stream path. // TLS verification, authentication rejection and unknown failures are terminal. - return errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) + return (errors.Is(setup.Err, io.EOF) || errors.Is(setup.Err, io.ErrUnexpectedEOF)) } // DialTCP opens an aTrust TCP proxy connection. TCP uses the server's stream @@ -173,14 +182,14 @@ func (m *Manager) DialTCP(ctx context.Context, ip string, port int, appID, domai m.logger.Debug("direct TCP tunnel established", "addr", addr, "target", net.JoinHostPort(ip, strconv.Itoa(port))) return tunneled, nil } - lastErr = err + lastErr = &TCPSetupError{Err: err} var rejected *TCPAuthError if errors.As(err, &rejected) { return nil, err } var status *TCPStatusError if errors.As(err, &status) && status.Status != 0x01 { - return nil, err + return nil, lastErr } lines.ReportFailure(addr) m.logger.Debug("direct TCP line failed", "addr", addr, "err", err) diff --git a/internal/tunnel/tcp_test.go b/internal/tunnel/tcp_test.go index 4a69b24..21918db 100644 --- a/internal/tunnel/tcp_test.go +++ b/internal/tunnel/tcp_test.go @@ -13,9 +13,9 @@ import ( "syscall" "testing" - "github.com/ShanghaitechGeekPie/geektrust/deployment" "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" "github.com/ShanghaitechGeekPie/geektrust/internal/session" + "github.com/ShanghaitechGeekPie/geektrust/internal/settings" ) func TestBuildTCPRequestCombinesAuthAndDestination(t *testing.T) { @@ -202,12 +202,12 @@ func TestDirectGatewaysUsesAssignedNodeGroup(t *testing.T) { } func TestTCPFallbackBoundaries(t *testing.T) { - for _, err := range []error{nil, errors.Join(&TCPAuthError{Code: 403}, io.EOF), errors.New("unclassified failure"), context.Canceled, context.DeadlineExceeded, &TCPStatusError{Status: 0x01}, &TCPStatusError{Status: 0x02}, &TCPStatusError{Status: 0x03}, &TCPStatusError{Status: 0x04}, &TCPStatusError{Status: 0x05}, &TCPStatusError{Status: 0x06}} { + for _, err := range []error{io.EOF, io.ErrUnexpectedEOF, &TCPStatusError{Status: 0x07}, nil, errors.Join(&TCPAuthError{Code: 403}, io.EOF), errors.New("unclassified failure"), context.Canceled, context.DeadlineExceeded, &TCPStatusError{Status: 0x01}, &TCPStatusError{Status: 0x02}, &TCPStatusError{Status: 0x03}, &TCPStatusError{Status: 0x04}, &TCPStatusError{Status: 0x05}, &TCPStatusError{Status: 0x06}} { if ShouldFallbackToL3(err) { t.Fatalf("unexpected fallback: %v", err) } } - if !ShouldFallbackToL3(&TCPStatusError{Status: 0x07}) || !ShouldFallbackToL3(io.EOF) { + if !ShouldFallbackToL3(&TCPSetupError{Err: &TCPStatusError{Status: 0x07}}) || !ShouldFallbackToL3(&TCPSetupError{Err: io.EOF}) { t.Fatal("legacy protocol/setup fallback removed") } } @@ -226,7 +226,7 @@ func TestTCPAuthenticationDenialNeverFallsBack(t *testing.T) { } func TestTCPConfiguredProcessIdentity(t *testing.T) { - identity := &deployment.ProcessIdentity{Name: "custom-client", Platform: "Windows", Path: "custom-client.exe"} + identity := &settings.ProcessIdentity{Name: "custom-client", Platform: "Windows", Path: "custom-client.exe"} packet, err := buildTCPRequest(&session.Credential{ProcessIdentity: identity}, "192.0.2.1", 22, "app", "") if err != nil { t.Fatal(err) diff --git a/internal/tunnel/tunnel.go b/internal/tunnel/tunnel.go index eda9f2f..76b2d9b 100644 --- a/internal/tunnel/tunnel.go +++ b/internal/tunnel/tunnel.go @@ -157,13 +157,18 @@ func gatewayTLSConfigWithTrust(ctx context.Context, addr string, template *tls.C for _, cert := range cs.PeerCertificates[1:] { intermediates.AddCert(cert) } - if _, err := cs.PeerCertificates[0].Verify(x509.VerifyOptions{DNSName: cfg.ServerName, Roots: cfg.RootCAs, Intermediates: intermediates}); err == nil { + _, verifyErr := cs.PeerCertificates[0].Verify(x509.VerifyOptions{DNSName: cfg.ServerName, Roots: cfg.RootCAs, Intermediates: intermediates}) + if verifyErr == nil { return nil } + var unknown x509.UnknownAuthorityError + if !errors.As(verifyErr, &unknown) { + return verifyErr + } leaf := cs.PeerCertificates[0] // Controllers may advertise gateway IPs whose private-CA certificates // contain DNS names only. The saved key is bound to the advertised IP:port. - if net.ParseIP(cfg.ServerName) == nil { + if cfg.ServerName != "" { if err := leaf.VerifyHostname(cfg.ServerName); err != nil { return fmt.Errorf("gateway certificate identity: %w", err) } diff --git a/internal/webui/broker.go b/internal/webui/broker.go index c4188f5..6b683d6 100644 --- a/internal/webui/broker.go +++ b/internal/webui/broker.go @@ -17,7 +17,7 @@ import ( // pending (or the generation does not match). HTTP maps it to 409. var ErrNoPending = errors.New("no SMS verification pending") -// smsPending is one armed prompt generation. opMu serializes resend network +// smsPending is one armed prompt generation. opGate serializes resend network // I/O against Prompt teardown only; claims never touch it. type smsPending struct { gen uint64 @@ -26,10 +26,7 @@ type smsPending struct { done bool // Broker.mu: Prompt retired this generation expired error // Broker.mu: resend proved the auth session expired resend func(context.Context) error - opMu sync.Mutex - // opWaiters counts resends between the first validation and the opMu - // acquisition (observability for tests; guarded by Broker.mu). - opWaiters int + opGate chan struct{} } type smsPromptResult struct { @@ -71,7 +68,7 @@ func (b *Broker) Prompt(ctx context.Context, resend func(context.Context) error) b.gen++ } result := make(chan smsPromptResult, 1) - p := &smsPending{gen: b.gen, result: result, resend: resend} + p := &smsPending{gen: b.gen, result: result, resend: resend, opGate: make(chan struct{}, 1)} b.pending = p b.mu.Unlock() @@ -105,8 +102,8 @@ func (b *Broker) Prompt(ctx context.Context, resend func(context.Context) error) b.mu.Unlock() b.onPendingChange(false, 0) // Wait for an in-flight resend so CheckSMSCode never overlaps it. - cur.opMu.Lock() - cur.opMu.Unlock() + cur.opGate <- struct{}{} + <-cur.opGate b.mu.Lock() expired := cur.expired b.mu.Unlock() @@ -119,8 +116,8 @@ func (b *Broker) Prompt(ctx context.Context, resend func(context.Context) error) b.pending = nil b.mu.Unlock() b.onPendingChange(false, 0) - cur.opMu.Lock() - cur.opMu.Unlock() + cur.opGate <- struct{}{} + <-cur.opGate b.mu.Lock() expired := cur.expired b.mu.Unlock() @@ -158,8 +155,8 @@ func (b *Broker) claim(code string, gen uint64, web bool) error { } // Resend re-triggers the SMS for the armed generation. Two validations -// (before and after acquiring the generation's opMu) keep it from running -// after a claim or teardown; the network call holds opMu, not Broker.mu. +// (before and after acquiring the generation's opGate) keep it from running +// after a claim or teardown; the network call holds opGate, not Broker.mu. func (b *Broker) Resend(ctx context.Context, gen uint64) error { b.mu.Lock() p := b.pending @@ -169,15 +166,12 @@ func (b *Broker) Resend(ctx context.Context, gen uint64) error { } b.mu.Unlock() - // Between the two validations the resend queues on the generation's opMu. - b.mu.Lock() - p.opWaiters++ - b.mu.Unlock() - p.opMu.Lock() - b.mu.Lock() - p.opWaiters-- - b.mu.Unlock() - defer p.opMu.Unlock() + select { + case p.opGate <- struct{}{}: + case <-ctx.Done(): + return ctx.Err() + } + defer func() { <-p.opGate }() b.mu.Lock() valid := b.pending == p && !p.done && !p.resolved && gen == p.gen resendFn := p.resend @@ -193,7 +187,7 @@ func (b *Broker) Resend(ctx context.Context, gen uint64) error { // The controller discarded the authentication behind this prompt. Retire // the generation and wake the blocked Provider so it can rebuild the full // login chain. Record the expiration even if a code claim already won: - // Prompt waits for opMu and lets this known expiration override that code. + // Prompt waits for opGate and lets this known expiration override that code. b.mu.Lock() p.expired = err deliver := b.pending == p && !p.done && !p.resolved && gen == p.gen diff --git a/internal/webui/broker_test.go b/internal/webui/broker_test.go index ecb6895..9644bb7 100644 --- a/internal/webui/broker_test.go +++ b/internal/webui/broker_test.go @@ -180,7 +180,7 @@ func TestBrokerResend(t *testing.T) { recvPrompt(t, ch) } -// TestBrokerResendSecondValidation forces a resend to arrive at the opMu +// TestBrokerResendSecondValidation forces a resend to arrive at the opGate // gate while another resend holds it, then resolves the generation: the // waiting resend must fail its second validation without invoking the // closure. @@ -200,29 +200,18 @@ func TestBrokerResendSecondValidation(t *testing.T) { resendA := make(chan error, 1) go func() { resendA <- b.Resend(context.Background(), gen) }() - <-entered // A holds the generation's opMu inside its closure + <-entered // A holds the generation's opGate inside its closure - // B queues behind opMu; the claim then resolves the generation. + // B queues behind opGate; the claim then resolves the generation. resendB := make(chan error, 1) + queued := &queuedResendContext{Context: context.Background(), ready: make(chan struct{})} go func() { - resendB <- b.Resend(context.Background(), gen) + resendB <- b.Resend(queued, gen) }() - // Wait until B has passed its first validation and is queued on opMu. - deadline := time.Now().Add(3 * time.Second) - for { - b.mu.Lock() - var waiters int - if b.pending != nil { - waiters = b.pending.opWaiters - } - b.mu.Unlock() - if waiters == 1 { - break - } - if time.Now().After(deadline) { - t.Fatal("resend B did not reach the opMu gate") - } - time.Sleep(2 * time.Millisecond) + select { + case <-queued.ready: + case <-time.After(3 * time.Second): + t.Fatal("resend did not reach its production wait") } if err := b.ClaimWeb("123456", gen); err != nil { t.Fatalf("claim during resend = %v", err) @@ -239,7 +228,7 @@ func TestBrokerResendSecondValidation(t *testing.T) { } } -// TestBrokerResendSerializesTeardown proves the opMu contract: with a +// TestBrokerResendSerializesTeardown proves the opGate contract: with a // resend in flight, Prompt must not return the claimed code until the // resend closure finishes. func TestBrokerResendSerializesTeardown(t *testing.T) { @@ -380,3 +369,14 @@ func TestBrokerExpiredResendOverridesConcurrentClaim(t *testing.T) { t.Fatalf("expired resend lost to concurrent code claim: %+v", result) } } + +type queuedResendContext struct { + context.Context + once sync.Once + ready chan struct{} +} + +func (c *queuedResendContext) Done() <-chan struct{} { + c.once.Do(func() { close(c.ready) }) + return c.Context.Done() +} diff --git a/internal/webui/hub.go b/internal/webui/hub.go index 7c91f4d..670e985 100644 --- a/internal/webui/hub.go +++ b/internal/webui/hub.go @@ -44,6 +44,7 @@ type proxyInfo struct { // snapshot is the /api/status and SSE payload (§6.3). type snapshot struct { + Generation uint64 `json:"generation"` State string `json:"state"` Since time.Time `json:"since"` LastError *string `json:"last_error"` @@ -72,6 +73,7 @@ type Hub struct { sessionActive bool smsPending bool smsGen uint64 + generation uint64 user *userInfo gateways []string @@ -116,6 +118,9 @@ func (h *Hub) OnSessionEvent(ev session.Event) { h.acquiring = true h.lastError = nil case session.EventLoginSuccess, session.EventRestoreOK: + if ev.Session != nil { + h.generation = ev.Session.Generation + } h.acquiring = false h.sessionActive = true h.lastError = nil @@ -128,7 +133,7 @@ func (h *Hub) OnSessionEvent(ev session.Event) { h.gateways = append([]string(nil), ev.Session.Gateways...) h.dns = append([]string(nil), ev.Session.DNS...) } - case session.EventLoginFailed: + case session.EventLoginFailed, session.EventInteractionRequired: h.acquiring = false h.sessionActive = false h.clearSessionLocked() @@ -212,6 +217,7 @@ func (h *Hub) snapshotLocked() snapshot { events := make([]HistoryEvent, len(h.events)) copy(events, h.events) return snapshot{ + Generation: h.generation, State: h.state, Since: h.since, LastError: h.lastError, diff --git a/internal/webui/server.go b/internal/webui/server.go index f1d82d2..a19501b 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -50,11 +50,14 @@ type Server struct { http *http.Server dist fs.FS hasUI bool + lifetime context.Context + cancel context.CancelFunc } // NewServer wires the routes, security middleware and embedded frontend. func NewServer(hub *Hub, broker *Broker, provider ProviderAPI, cfg *config.Config) *Server { - s := &Server{hub: hub, broker: broker, provider: provider, cfg: cfg} + ctx, cancel := context.WithCancel(context.Background()) + s := &Server{hub: hub, broker: broker, provider: provider, cfg: cfg, lifetime: ctx, cancel: cancel} if sub, err := fs.Sub(distFS, "dist"); err == nil { s.dist = sub if f, err := sub.Open("index.html"); err == nil { @@ -97,6 +100,7 @@ func (s *Server) Serve(listener net.Listener) error { // a client that stopped reading mid-response) are hard-closed instead of // leaked past the deadline. func (s *Server) Shutdown(ctx context.Context) error { + s.cancel() err := s.http.Shutdown(ctx) if err != nil { s.http.Close() @@ -250,7 +254,7 @@ func (s *Server) handleRelogin(w http.ResponseWriter, r *http.Request) { return } // The reserved acquisition must run exactly once and outlive the request. - go run(context.Background()) + go run(s.lifetime) writeJSON(w, http.StatusAccepted, map[string]any{}) } @@ -277,7 +281,7 @@ func (s *Server) handleTrustList(w http.ResponseWriter, r *http.Request) { func (s *Server) handleTrustBind(w http.ResponseWriter, r *http.Request) { if s.cfg.ClientType != "client" { - writeError(w, http.StatusConflict, `trust-device bind requires client_type = "client" in config`) + writeError(w, http.StatusConflict, `trust-device bind requires client authentication mode`) return } sc := s.activeSC(w) @@ -376,3 +380,5 @@ func (s *Server) handleStatic(w http.ResponseWriter, r *http.Request) { } http.FileServerFS(s.dist).ServeHTTP(w, r) } + +func (s *Server) SetLifetime(ctx context.Context) { context.AfterFunc(ctx, s.cancel) } diff --git a/scripts/package-release-uv.sh b/scripts/package-release-uv.sh index 35ead01..7c37cd9 100755 --- a/scripts/package-release-uv.sh +++ b/scripts/package-release-uv.sh @@ -44,7 +44,7 @@ downloads="$package_tmp/downloads" mkdir -p "$base_output" "$downloads" # Build the base packages first so Go build flags stay in package-release.sh. -# Keep the target list below in sync with that script. +# Both packagers load the same product target list. bash scripts/package-release.sh "$version" "$base_output" uv_release_url="https://releases.astral.sh/github/uv/releases/download/$uv_version" @@ -82,14 +82,7 @@ curl "${curl_args[@]}" --output "$license_dir/LICENSE-MIT" \ curl "${curl_args[@]}" --output "$license_dir/LICENSE-APACHE" \ "https://raw.githubusercontent.com/astral-sh/uv/$uv_version/LICENSE-APACHE" -targets=( - linux/amd64 - linux/arm64 - darwin/amd64 - darwin/arm64 - windows/amd64 - windows/arm64 -) +source "$repo_root/scripts/release-targets.sh" for target in "${targets[@]}"; do goos=${target%/*} diff --git a/scripts/package-release.sh b/scripts/package-release.sh index 6ba639a..ba23eca 100755 --- a/scripts/package-release.sh +++ b/scripts/package-release.sh @@ -32,14 +32,7 @@ trap 'rm -rf "$package_tmp"' EXIT npm --prefix web ci npm --prefix web run build -targets=( - linux/amd64 - linux/arm64 - darwin/amd64 - darwin/arm64 - windows/amd64 - windows/arm64 -) +source "$repo_root/scripts/release-targets.sh" for target in "${targets[@]}"; do goos=${target%/*} diff --git a/scripts/release-targets.sh b/scripts/release-targets.sh new file mode 100644 index 0000000..3f92a88 --- /dev/null +++ b/scripts/release-targets.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# One product target list shared by plain and uv-bundled packaging. +targets=(linux/amd64 linux/arm64 darwin/amd64 darwin/arm64 windows/amd64 windows/arm64) diff --git a/web/src/api.ts b/web/src/api.ts index da3ebbf..d8aac42 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -17,7 +17,8 @@ export interface PanelStore { let store: PanelStore = { snap: null, connected: false }; const listeners = new Set<() => void>(); let sawStream = false; -let reconnectTimer: number | undefined; +let stream: EventSource | undefined; +let streamEpoch = 0; function publish(next: PanelStore) { store = next; @@ -25,8 +26,8 @@ function publish(next: PanelStore) { } function connect() { - reconnectTimer = undefined; const es = new EventSource("/api/events"); + stream = es; es.onopen = () => { if (!store.connected) publish({ ...store, connected: true }); }; @@ -41,38 +42,44 @@ function connect() { publish({ snap, connected: true }); }; es.onerror = () => { - // Rebuild the stream ourselves: EventSource stops retrying once closed, - // and the UI needs an explicit "disconnected" signal either way. - es.close(); + // EventSource retries the connection itself. if (store.connected) publish({ ...store, connected: false }); - if (reconnectTimer === undefined) { - reconnectTimer = window.setTimeout(connect, 2000); - } }; } -async function seed() { +async function seed(epoch: number) { try { const resp = await fetch("/api/status"); if (!resp.ok) return; const snap = (await resp.json()) as Snapshot; - if (!sawStream) publish({ ...store, snap }); + if (epoch === streamEpoch && !sawStream) publish({ ...store, snap }); } catch { // the SSE loop owns retries } } -connect(); -void seed(); + + +function subscribePanel(cb: () => void) { + listeners.add(cb); + if (listeners.size === 1) { + sawStream = false; + connect(); + void seed(++streamEpoch); + } + return () => { + listeners.delete(cb); + if (listeners.size === 0) { + streamEpoch++; + stream?.close(); + stream = undefined; + store = { ...store, connected: false }; + } + }; +} export function usePanelStore(): PanelStore { - return useSyncExternalStore( - (cb) => { - listeners.add(cb); - return () => listeners.delete(cb); - }, - () => store, - ); + return useSyncExternalStore(subscribePanel, () => store); } // --------------------------------------------------------------------------- diff --git a/web/src/components/SmsDialog.tsx b/web/src/components/SmsDialog.tsx index e28842d..7b207f2 100644 --- a/web/src/components/SmsDialog.tsx +++ b/web/src/components/SmsDialog.tsx @@ -42,12 +42,15 @@ export function SmsDialog({ snap }: { snap: Snapshot }) { setBusy(true); setError(null); setNotice(null); + const requestedGen = gen; try { - await post("/api/sms", { code, gen: snap.sms_gen }); + await post("/api/sms", { code, gen: requestedGen }); + if (currentGen.current !== requestedGen) return; // 202 = 已投递;登录结果经 SSE 推送。验证失败会结束本次登录, // 弹窗随之关闭,状态卡片会显示失败原因。 setNotice("已提交,等待服务端验证…"); } catch (err) { + if (currentGen.current !== requestedGen) return; setBusy(false); setError( errorText(err, "提交失败", { @@ -62,13 +65,14 @@ export function SmsDialog({ snap }: { snap: Snapshot }) { if (busy || cooldown > 0) return; setError(null); setNotice(null); + const requestedGen = gen; try { - const requestedGen = snap.sms_gen; const result = await postJSON<{ restarting?: boolean }>("/api/sms/resend", { gen: requestedGen }); if (currentGen.current !== requestedGen) return; setNotice(result.restarting ? "验证已过期,正在重新登录并发送新验证码…" : "验证码已重新发送"); setCooldown(RESEND_COOLDOWN); } catch (err) { + if (currentGen.current !== requestedGen) return; if (err instanceof ApiError && err.status === 429) { // 上一条验证码仍在有效期内:直接输入它,同时进入冷却防止连点。 setCooldown(RESEND_COOLDOWN); diff --git a/web/src/components/TrustDevices.tsx b/web/src/components/TrustDevices.tsx index 06b26b3..194a692 100644 --- a/web/src/components/TrustDevices.tsx +++ b/web/src/components/TrustDevices.tsx @@ -11,7 +11,7 @@ function deviceLabel(d: TrustDeviceEntry): string { const LIST_ERRORS: Record = { 503: "会话未就绪,请稍后重试", - 409: "browser 模式不能绑定授信终端,请把 client_type 改为 client 并重启 geektrust", + 409: "browser 模式不能绑定授信终端,请将登录模式设为 client 并重启 geektrust", }; export function TrustDevices({ snap, connected }: { snap: Snapshot; connected: boolean }) { @@ -25,6 +25,9 @@ export function TrustDevices({ snap, connected }: { snap: Snapshot; connected: b const [refreshing, setRefreshing] = useState(false); // Refresh results must never outlive the session they were fetched in. const epochRef = useRef(0); + const sessionKey = `${snap.generation ?? 0}:${snap.state}:${snap.since}:${snap.user?.username ?? ""}`; + const sessionRef = useRef(sessionKey); + if (sessionRef.current !== sessionKey) { sessionRef.current = sessionKey; epochRef.current++; } const refresh = useCallback(async () => { const epoch = ++epochRef.current; @@ -50,7 +53,9 @@ export function TrustDevices({ snap, connected }: { snap: Snapshot; connected: b setError(null); setNotice(null); } - }, [snap.state, refresh]); + setPending(null); + setRefreshing(false); + }, [sessionKey, refresh]); // Only binding is refused in browser mode (server.go handleTrustBind); // listing, unbinding and logout work on any session, so the card stays @@ -60,18 +65,21 @@ export function TrustDevices({ snap, connected }: { snap: Snapshot; connected: b const canAct = connected && snap.state === "online" && !busy; const run = async (action: () => Promise, ok: string, label: string) => { + const session = sessionRef.current; setPending(label); setError(null); setNotice(null); try { await action(); + if (session !== sessionRef.current) return; setNotice(ok); setSelected(new Set()); await refresh(); } catch (err) { + if (session !== sessionRef.current) return; setError(errorText(err, "操作失败", LIST_ERRORS)); } finally { - setPending(null); + if (session === sessionRef.current) setPending(null); } }; @@ -100,7 +108,8 @@ export function TrustDevices({ snap, connected }: { snap: Snapshot; connected: b className="secondary" onClick={() => { setRefreshing(true); - void refresh().finally(() => setRefreshing(false)); + const session = sessionRef.current; + void refresh().finally(() => { if (session === sessionRef.current) setRefreshing(false); }); }} disabled={!canAct || refreshing} > @@ -129,8 +138,7 @@ export function TrustDevices({ snap, connected }: { snap: Snapshot; connected: b )} {!isClient && (

- 当前为 browser 模式:可以查看、取消授信和注销设备,但不能绑定当前设备。把配置中的{" "} - client_type 改为 client 并重启 geektrust 后才能绑定。 + 当前为 browser 模式:可以查看、取消授信和注销设备,但不能绑定当前设备。将登录模式设为 client 并重启 geektrust 后才能绑定。

)} {error && } diff --git a/web/src/types.ts b/web/src/types.ts index a3e8880..9e1160f 100644 --- a/web/src/types.ts +++ b/web/src/types.ts @@ -19,6 +19,7 @@ export interface HistoryEvent { // Snapshot mirrors GET /api/status and the SSE payload (docs/WEBUI.md §6.3). export interface Snapshot { + generation?: number; state: PanelState; since: string; last_error: string | null; From b319f63b53eb76df65fd8cf0f020fb66998640f8 Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Tue, 6 Oct 2026 02:20:09 +0800 Subject: [PATCH 04/28] fix(config): clarify session state path override --- config.example.toml | 2 +- docs/TECHNICAL.md | 2 +- internal/config/init.go | 2 +- internal/config/init_test.go | 3 ++ internal/config/v2.go | 19 +++++++--- internal/config/v2_test.go | 67 ++++++++++++++++++++++++++++++++++++ 6 files changed, 87 insertions(+), 8 deletions(-) diff --git a/config.example.toml b/config.example.toml index 340edf5..54d0680 100644 --- a/config.example.toml +++ b/config.example.toml @@ -29,7 +29,7 @@ keystore = "./ids-passkey.keystore" # [storage] # directory = "" # 缺省使用平台用户私有持久目录 -# legacy_state = "" # 仅用于保留既有加密会话路径,不删除原缓存和密钥 +# state_file = "" # 留空使用 directory/session.enc;非空覆盖会话文件读写路径 # [logging] # level = "info" diff --git a/docs/TECHNICAL.md b/docs/TECHNICAL.md index 33081d0..d573269 100644 --- a/docs/TECHNICAL.md +++ b/docs/TECHNICAL.md @@ -83,7 +83,7 @@ - **Query 参数**(缺失或大小写错误会返回 400/422): - `clientType`:浏览器路径用 `SDPBrowserClient`(桌面路径用 `SDPClient`)。 - - `platform`:**大小写敏感,必须为 `Mac`**。`Macintosh` 会报 `10000001 invalid_param in query`;`mac`(全小写)会报 422。 + - `platform`:**大小写敏感,默认使用 `Mac`**。2026-10-06 实测上科大和 ECNU 的 `/passport/v1/public/authConfig` 均接受 `Mac`、`Windows`、`Linux`(HTTP 200、业务码 0);这不代表已验证完整登录和隧道流程。历史记录中,`Macintosh` 报 `10000001 invalid_param in query`,`mac`(全小写)报 422。 - `lang`:`zh-CN`。 - **请求头**: - `x-csrf-token: `(必带)。 diff --git a/internal/config/init.go b/internal/config/init.go index 58d6421..e1d0587 100644 --- a/internal/config/init.go +++ b/internal/config/init.go @@ -116,7 +116,7 @@ device_id = %s keystore = %s [storage] -legacy_state = %s +state_file = %s `, strconv.Quote(cfg.ClientType), strconv.Quote(cfg.DeviceID), strconv.Quote(key), strconv.Quote(state))) } diff --git a/internal/config/init_test.go b/internal/config/init_test.go index 0f30a9a..d578632 100644 --- a/internal/config/init_test.go +++ b/internal/config/init_test.go @@ -58,6 +58,9 @@ func TestInitializeDefaultsAndPreservesExistingConfig(t *testing.T) { if err != nil { t.Fatal(err) } + if !strings.Contains(string(raw), "state_file =") || strings.Contains(string(raw), "legacy_state") { + t.Fatal("init did not emit only storage.state_file") + } webBlock := "config_version = 2" if !strings.Contains(string(raw), webBlock) { t.Errorf("rendered config missing complete [web] block:\n%s", raw) diff --git a/internal/config/v2.go b/internal/config/v2.go index 2d7215a..c36bb52 100644 --- a/internal/config/v2.go +++ b/internal/config/v2.go @@ -49,8 +49,10 @@ type FileV2 struct { Servers []string `toml:"servers"` } `toml:"dns"` Storage struct { - Directory string `toml:"directory"` - LegacyState string `toml:"legacy_state"` + Directory string `toml:"directory"` + StateFile string `toml:"state_file"` + // LegacyState is a read-compatible alias; new output uses state_file. + LegacyState string `toml:"legacy_state,omitempty"` } `toml:"storage"` Logging struct { Level string `toml:"level"` @@ -152,8 +154,15 @@ func loadV2(path string, data []byte) (*Config, error) { if cfg.LoginDomain == "" { cfg.LoginDomain = v.LoginDomain } - if f.Storage.LegacyState != "" { - cfg.StateFile = resolve(f.Storage.LegacyState) + stateFile := resolve(f.Storage.StateFile) + legacyState := resolve(f.Storage.LegacyState) + if meta.IsDefined("storage", "state_file") && meta.IsDefined("storage", "legacy_state") && stateFile != legacyState { + return nil, errors.New("conflicting storage.state_file and storage.legacy_state") + } + if stateFile != "" { + cfg.StateFile = stateFile + } else if legacyState != "" { + cfg.StateFile = legacyState } cfg.Gateways = f.Routing.GatewayFilter if f.Routing.FallbackAppID != "" { @@ -285,7 +294,7 @@ func Migration(path string) ([]byte, error) { if e != nil { return nil, e } - f.Storage.LegacyState, e = filepath.Abs(c.StateFile) + f.Storage.StateFile, e = filepath.Abs(c.StateFile) if e != nil { return nil, e } diff --git a/internal/config/v2_test.go b/internal/config/v2_test.go index fb53b6c..e10359e 100644 --- a/internal/config/v2_test.go +++ b/internal/config/v2_test.go @@ -52,6 +52,24 @@ func TestV2StrictAndLegacyMigration(t *testing.T) { if e != nil { t.Fatal(e) } + if !strings.Contains(string(b), "state_file =") || strings.Contains(string(b), "legacy_state") { + t.Fatal("migration did not emit only storage.state_file") + } + migrated := filepath.Join(dir, "migrated.toml") + if err := os.WriteFile(migrated, b, 0600); err != nil { + t.Fatal(err) + } + c, err := Load(migrated) + if err != nil { + t.Fatal(err) + } + expectedState, err := filepath.Abs("./state.enc") + if err != nil { + t.Fatal(err) + } + if c.StateFile != expectedState { + t.Fatal("migration changed the effective session path") + } if !strings.Contains(string(b), "0123456789ABCDEF0123456789ABCDEF") || !strings.Contains(string(b), "browser") || !strings.Contains(string(b), "custom") { t.Fatal("migration lost existing semantics") } @@ -60,3 +78,52 @@ func TestV2StrictAndLegacyMigration(t *testing.T) { t.Fatal("legacy override silently converted") } } + +func TestV2StateFileAliasAndConflicts(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "config.toml") + base := "config_version = 2\n[auth.passkey]\nkeystore = './credential'\n[storage]\ndirectory = './private'\n" + cases := []struct { + name, storage, want string + conflict bool + }{ + {"default", "", filepath.Join(dir, "private", "session.enc"), false}, + {"new path", "state_file = './current.enc'\n", filepath.Join(dir, "current.enc"), false}, + {"legacy path", "legacy_state = './previous.enc'\n", filepath.Join(dir, "previous.enc"), false}, + {"empty new path", "state_file = ''\n", filepath.Join(dir, "private", "session.enc"), false}, + {"equivalent aliases", "state_file = './cache.enc'\nlegacy_state = 'nested/../cache.enc'\n", filepath.Join(dir, "cache.enc"), false}, + {"conflicting aliases", "state_file = './new.enc'\nlegacy_state = './old.enc'\n", "", true}, + {"explicit empty conflicts", "state_file = './new.enc'\nlegacy_state = ''\n", "", true}, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + original := base + tt.storage + if err := os.WriteFile(p, []byte(original), 0600); err != nil { + t.Fatal(err) + } + cfg, err := Load(p) + if tt.conflict { + if err == nil || !strings.Contains(err.Error(), "conflicting storage.state_file") { + t.Fatalf("expected conflict, got %v", err) + } + } else { + if err != nil { + t.Fatal(err) + } + if cfg.StateFile != tt.want { + t.Fatalf("state path=%q, want %q", cfg.StateFile, tt.want) + } + if _, err := os.Stat(cfg.StateFile); !os.IsNotExist(err) { + t.Fatal("loading created a session file") + } + } + after, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + if string(after) != original { + t.Fatal("loading rewrote source configuration") + } + }) + } +} From 32bcc3a2dc258f4f9791379786b5aa974ff65742 Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Wed, 7 Oct 2026 17:54:30 +0800 Subject: [PATCH 05/28] build: update Go toolchain and networking dependencies --- go.mod | 7 +++---- go.sum | 10 ++++------ 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/go.mod b/go.mod index 01a34e9..656378b 100644 --- a/go.mod +++ b/go.mod @@ -1,13 +1,12 @@ module github.com/ShanghaitechGeekPie/geektrust -go 1.24.13 +go 1.26.8 require ( github.com/BurntSushi/toml v1.5.0 github.com/metacubex/gvisor v0.0.0-20251227095601-261ec1326fe8 - golang.org/x/net v0.43.0 - golang.org/x/sys v0.35.0 - golang.org/x/text v0.28.0 + golang.org/x/net v0.56.0 + golang.org/x/sys v0.46.0 ) require ( diff --git a/go.sum b/go.sum index 337deca..800c9d2 100644 --- a/go.sum +++ b/go.sum @@ -4,11 +4,9 @@ github.com/google/btree v1.1.2 h1:xf4v41cLI2Z6FxbKm+8Bu+m8ifhj15JuZ9sa0jZCMUU= github.com/google/btree v1.1.2/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= github.com/metacubex/gvisor v0.0.0-20251227095601-261ec1326fe8 h1:hUL81H0Ic/XIDkvtn9M1pmfDdfid7JzYQToY4Ps1TvQ= github.com/metacubex/gvisor v0.0.0-20251227095601-261ec1326fe8/go.mod h1:8LpS0IJW1VmWzUm3ylb0e2SK5QDm5lO/2qwWLZgRpBU= -golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE= -golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg= -golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI= -golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= -golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng= -golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU= +golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o= +golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec= +golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= +golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/time v0.7.0 h1:ntUhktv3OPE6TgYxXWv9vKvUSJyIFJlyohwbkEwPrKQ= golang.org/x/time v0.7.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= From 02f41e88407fe53823957ed1e23e82ebd9e1c050 Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Wed, 7 Oct 2026 17:55:34 +0800 Subject: [PATCH 06/28] refactor(sdk): unify compatibility and bind operations to session lifetime Rename deployment to compatibility and remove obsolete legacy settings. Bind cached state, controller operations and connections to the active session, preserve scoped gateway trust, and warn when version 1 configuration is loaded. --- client/README.md | 2 +- cmd/geektrust/config_cmd.go | 2 +- cmd/geektrust/library.go | 14 +- cmd/geektrust/main.go | 15 +- {deployment => compatibility}/profile.go | 4 +- config.example.toml | 2 +- docs/TECHNICAL.md | 4 +- .../{deployment => compatibility}/profile.go | 22 +- internal/compatibility/shanghaitech.go | 10 + internal/config/compatibility_test.go | 66 +--- internal/config/config.go | 76 ++-- .../controller_origin_regression_test.go | 34 ++ internal/config/v2.go | 44 +-- internal/config/v2_test.go | 45 ++- internal/deployment/shanghaitech.go | 11 - internal/idsauth/client.go | 20 +- internal/idsauth/ecnu.go | 2 +- internal/idsauth/ecnu_flow_test.go | 18 +- internal/idsauth/keystore.go | 2 +- internal/idsauth/origin_regression_test.go | 11 + internal/idsauth/redirect_origin_test.go | 69 ++++ internal/idsauth/shtu_test.go | 10 + internal/inbound/udp.go | 2 +- internal/l3/auth.go | 6 +- internal/l3/auth_test.go | 4 +- internal/l3/dialer.go | 2 +- internal/l3/dialer_test.go | 3 + internal/resolver/resolver.go | 6 +- internal/resolver/resolver_test.go | 12 + internal/runtime/client_test.go | 42 +- internal/runtime/command.go | 2 - internal/runtime/compatibility_test.go | 133 ------- internal/runtime/contract_test.go | 4 +- internal/runtime/devices.go | 100 +++-- internal/runtime/legacy_test.go | 141 ------- .../lookup_lifetime_regression_test.go | 53 +++ internal/runtime/options.go | 4 +- internal/runtime/options_test.go | 121 ++++++ internal/runtime/packet.go | 14 +- internal/runtime/review_regression_test.go | 363 ++++++++++++++++++ internal/runtime/runtime.go | 162 +++++--- internal/runtime/status.go | 136 ++++--- internal/runtime/target_test.go | 44 +-- internal/sdpc/resource.go | 5 +- internal/sdpc/resource_test.go | 29 +- internal/session/events_test.go | 69 ++-- .../session/force_login_regression_test.go | 119 ++++++ .../session/force_queue_regression_test.go | 49 +++ internal/session/interaction.go | 40 ++ internal/session/live_test.go | 18 +- internal/session/provider.go | 221 ++++++----- internal/session/provider_test.go | 9 +- internal/session/store.go | 6 - internal/settings/compatibility.go | 73 ---- internal/settings/session.go | 9 +- internal/tunnel/line_test.go | 24 +- internal/tunnel/reset.go | 11 + internal/tunnel/tcp.go | 3 +- internal/tunnel/tcp_test.go | 4 +- .../tunnel/tls_callback_regression_test.go | 138 +++++++ internal/tunnel/tunnel.go | 52 +-- internal/webui/server.go | 50 +-- internal/webui/server_test.go | 26 +- 63 files changed, 1840 insertions(+), 952 deletions(-) rename {deployment => compatibility}/profile.go (94%) rename internal/{deployment => compatibility}/profile.go (62%) create mode 100644 internal/compatibility/shanghaitech.go create mode 100644 internal/config/controller_origin_regression_test.go delete mode 100644 internal/deployment/shanghaitech.go create mode 100644 internal/idsauth/origin_regression_test.go create mode 100644 internal/idsauth/redirect_origin_test.go delete mode 100644 internal/runtime/compatibility_test.go delete mode 100644 internal/runtime/legacy_test.go create mode 100644 internal/runtime/lookup_lifetime_regression_test.go create mode 100644 internal/runtime/options_test.go create mode 100644 internal/runtime/review_regression_test.go create mode 100644 internal/session/force_login_regression_test.go create mode 100644 internal/session/force_queue_regression_test.go delete mode 100644 internal/settings/compatibility.go create mode 100644 internal/tunnel/tls_callback_regression_test.go diff --git a/client/README.md b/client/README.md index c2086cd..8aa066b 100644 --- a/client/README.md +++ b/client/README.md @@ -28,7 +28,7 @@ defer conn.Close() `New` 只检查和复制设置。`Connect`、`Authenticate` 可以发起短信交互;后台、数据连接和解析遇到短信要求时返回 `auth.ErrInteractionRequired`。挑战区分本地 `Deadline` 和服务端 `ServerExpiresAt`,提供限生命周期的 `Resend`。不提供完整控制器登录替换钩子。 -部署默认为 `deployment.Auto`。上科大的已验证 TLS 身份和缺字段补充由内部适配提供;未知控制器采用 `Generic`。`Fallbacks=nil` 使用部署默认,`&deployment.Fallbacks{}` 关闭全部兜底。TLS 设置放在 `Network.GatewayTLS`,正常 CA 验证成功时不强制检查 pin;未知 CA 的兜底需要原子的 `CheckOrEnroll`,并继续验证证书身份和有效期。 +控制器兼容适配默认为 `compatibility.Auto`。上科大的已验证 TLS 身份和缺字段补充由内部适配提供;未知控制器采用 `Generic`。`Fallbacks=nil` 使用适配默认,`&compatibility.Fallbacks{}` 关闭全部兜底。TLS 设置放在 `Network.GatewayTLS`,正常 CA 验证成功时不强制检查 pin;未知 CA 的兜底需要原子的 `CheckOrEnroll`,并继续验证证书身份和有效期。 SDK 默认仅使用控制器 DNS;额外来源由 `DNS.FallbackLookup` 明确提供。CLI 的 `auto` 顺序在命令转换层保留。`Network.AllowedGateways=nil` 不额外限制,显式空列表拒绝全部线路。`CheckTarget` 收到地址、协议、端口和代;`DNSQueryTarget` 区分基础 DNS 查询,只能收紧访问权限。 diff --git a/cmd/geektrust/config_cmd.go b/cmd/geektrust/config_cmd.go index 829458b..9c091f1 100644 --- a/cmd/geektrust/config_cmd.go +++ b/cmd/geektrust/config_cmd.go @@ -32,7 +32,7 @@ func cmdConfig(path string, args []string) error { fmt.Println("configuration valid") return nil } - fmt.Printf("config_version = %d\ncontroller = %q\ndeployment = %q\nauth_mode = %q\ndns_strategy = %q\nkeystore = %q\nstate_file = %q\n", c.Version, c.BaseURL, c.Deployment, c.ClientType, c.DNSStrategy, c.Keystore, c.StateFile) + fmt.Printf("config_version = %d\ncontroller = %q\ncompatibility = %q\nauth_mode = %q\ndns_strategy = %q\nkeystore = %q\nstate_file = %q\n", c.Version, c.BaseURL, c.Compatibility, c.ClientType, c.DNSStrategy, c.Keystore, c.StateFile) return nil case "migrate": fs := flag.NewFlagSet("config migrate", flag.ContinueOnError) diff --git a/cmd/geektrust/library.go b/cmd/geektrust/library.go index 7cab12e..6266c4d 100644 --- a/cmd/geektrust/library.go +++ b/cmd/geektrust/library.go @@ -6,7 +6,7 @@ import ( "crypto/x509" "errors" "github.com/ShanghaitechGeekPie/geektrust/auth" - "github.com/ShanghaitechGeekPie/geektrust/deployment" + "github.com/ShanghaitechGeekPie/geektrust/compatibility" "github.com/ShanghaitechGeekPie/geektrust/internal/config" "github.com/ShanghaitechGeekPie/geektrust/internal/runtime" "github.com/ShanghaitechGeekPie/geektrust/internal/session" @@ -33,18 +33,12 @@ func commandClient(cfg *config.Config, logger *slog.Logger) (*runtime.Runtime, e return "", auth.ErrUnsupported } return smsPrompt(ctx) - }}, Deployment: deployment.Options{Profile: cfg.Deployment, Protocol: deployment.ProtocolOptions{ControllerPlatform: cfg.Platform}, Fallbacks: &deployment.Fallbacks{ApplicationID: cfg.Compatibility.FallbackAppID, Gateways: cfg.Compatibility.FallbackGateways, MissingGatewayGroup: cfg.Compatibility.MissingGatewayGroupFallback, StreamToL3: cfg.Compatibility.TCPToL3Fallback}}, SessionStore: commandSessionStore{session.NewStore(cfg.StateFile)}} - if cfg.Version == 1 && cfg.CompatibilityExplicit { - o.Deployment.Profile = deployment.Generic - } + }}, Compatibility: compatibility.Options{Profile: cfg.Compatibility, Protocol: compatibility.ProtocolOptions{ControllerPlatform: cfg.Platform}, Fallbacks: &cfg.Fallbacks}, SessionStore: commandSessionStore{session.NewStore(cfg.StateFile)}} if cfg.ClientType == "client" { o.Auth.Mode = runtime.DesktopMode } - if p := cfg.Compatibility.ProcessIdentity; p != nil { - o.Deployment.Protocol.Process = &deployment.ProcessMetadata{Name: p.Name, Platform: p.Platform, Path: p.Path} - } - if cfg.Compatibility.GatewayServerName != "" { - o.Network.GatewayTLS.Config = &tls.Config{ServerName: cfg.Compatibility.GatewayServerName} + if cfg.GatewayTLSName != "" { + o.Network.GatewayTLS.Config = &tls.Config{ServerName: cfg.GatewayTLSName} } if cfg.CAFile != "" { b, e := os.ReadFile(cfg.CAFile) diff --git a/cmd/geektrust/main.go b/cmd/geektrust/main.go index a80bf97..3361bc9 100644 --- a/cmd/geektrust/main.go +++ b/cmd/geektrust/main.go @@ -84,6 +84,9 @@ func main() { fmt.Fprintln(os.Stderr, "geektrust:", err) os.Exit(1) } + if cfg.Version == 1 { + fmt.Fprintf(os.Stderr, "Warning: using a deprecated config (version 1). Run geektrust -config %q config migrate to preview the new format, then add --write to migrate.\n", configPath) + } logger := newLogger(cfg.LogLevel) switch cmd { @@ -435,14 +438,10 @@ func cmdTrustDevice(ctx context.Context, cfg *config.Config, logger *slog.Logger if _, err := c.Connect(ctx); err != nil { return fmt.Errorf("trust-device: need an active session: %w", err) } - sc := c.ActiveSDPC() - if sc == nil { - return fmt.Errorf("trust-device: no controller client available") - } switch sub { case "list": - list, err := sc.QueryTrustDevice(ctx) + list, err := c.QueryTrustDevice(ctx) if err != nil { return fmt.Errorf("query trust device: %w", err) } @@ -463,20 +462,20 @@ func cmdTrustDevice(ctx context.Context, cfg *config.Config, logger *slog.Logger } case "bind": - if err := sc.TrustDevice(ctx); err != nil { + if err := c.TrustDevice(ctx); err != nil { return fmt.Errorf("bind trust device: %w", err) } fmt.Println("device bound as trusted terminal") fmt.Println("subsequent logins with the same device_id may skip SMS verification") case "unbind": - if err := sc.UntrustDevice(ctx, args[1:]); err != nil { + if err := c.UntrustDevice(ctx, args[1:]); err != nil { return fmt.Errorf("unbind trust device: %w", err) } fmt.Printf("untrusted device(s): %s\n", strings.Join(args[1:], ", ")) case "logout": - if err := sc.LogoutDevice(ctx, args[1]); err != nil { + if err := c.LogoutTrustDevice(ctx, args[1]); err != nil { return fmt.Errorf("logout trust device: %w", err) } fmt.Printf("logged out device: %s\n", args[1]) diff --git a/deployment/profile.go b/compatibility/profile.go similarity index 94% rename from deployment/profile.go rename to compatibility/profile.go index 7ffed99..3a9d860 100644 --- a/deployment/profile.go +++ b/compatibility/profile.go @@ -1,4 +1,4 @@ -package deployment +package compatibility import ( "fmt" @@ -45,7 +45,7 @@ func (o Options) Validate() error { switch o.Profile { case Auto, Generic, ShanghaiTech, ECNU: default: - return fmt.Errorf("unknown deployment profile %q", o.Profile) + return fmt.Errorf("unknown compatibility profile %q", o.Profile) } if len(o.Protocol.ControllerPlatform) > 64 || strings.IndexFunc(o.Protocol.ControllerPlatform, unicode.IsControl) >= 0 { return fmt.Errorf("invalid controller platform") diff --git a/config.example.toml b/config.example.toml index 54d0680..5f577d8 100644 --- a/config.example.toml +++ b/config.example.toml @@ -8,7 +8,7 @@ keystore = "./ids-passkey.keystore" # 下列分组可按需启用。省略表示使用默认值。 # [controller] # url = "https://vpn.shanghaitech.edu.cn" -# deployment = "auto" # auto / shanghaitech / ecnu / generic +# compatibility = "auto" # auto / shanghaitech / ecnu / generic # platform = "Mac" # 控制器协议参数,与本机系统无关 # [auth] diff --git a/docs/TECHNICAL.md b/docs/TECHNICAL.md index d573269..ecaa9bd 100644 --- a/docs/TECHNICAL.md +++ b/docs/TECHNICAL.md @@ -451,7 +451,7 @@ TCP 不需要经过 §6 至 §8 的 L3 小包数据面。客户端对目标应 ``` 认证与目标地址必须合并写入,也不能在连接结果前额外发送空数据帧;否则部分网关 -会接受初始化后关闭第一段应用数据。显式启用 `compatibility.tcp_to_l3_fallback` 且流式命令不支持或建立阶段提前关闭时, +会接受初始化后关闭第一段应用数据。部署适配启用 `compatibility.Fallbacks.StreamToL3` 且流式命令不支持或建立阶段提前关闭时, 回退到下述 L3 路径。 --- @@ -634,7 +634,7 @@ geekTrust 提供 SOCKS5 CONNECT/UDP ASSOCIATE 和 HTTP/1.1 CONNECT/CONNECT-UDP 1. 客户端发 `0x05 `;服务器回 `0x05 0x00`(无认证)。 2. 客户端发 `0x05 0x01 0x00 `。 3. 按 §4.2 选择目标 IP、TCP `appId` 和可选域名;优先建立 §5.5 流式通道, - 显式开启 `compatibility.tcp_to_l3_fallback` 后,流式命令不支持或建立阶段提前关闭时回退到 §6 至 §8 L3 路径;无法解析时回 + 部署适配启用 `compatibility.Fallbacks.StreamToL3` 后,流式命令不支持或建立阶段提前关闭时回退到 §6 至 §8 L3 路径;无法解析时回 `REP=0x04`,拨号失败回 `REP=0x05`。 4. 成功后回 `REP=0x00`,再进行支持半关闭的双向 TCP 中继。 diff --git a/internal/deployment/profile.go b/internal/compatibility/profile.go similarity index 62% rename from internal/deployment/profile.go rename to internal/compatibility/profile.go index c64be4f..bb0ca2f 100644 --- a/internal/deployment/profile.go +++ b/internal/compatibility/profile.go @@ -1,16 +1,17 @@ -// Package deployment owns the verified defaults for known controllers. -package deployment +// Package compatibility owns the verified defaults for known controllers. +package compatibility import ( - public "github.com/ShanghaitechGeekPie/geektrust/deployment" - "github.com/ShanghaitechGeekPie/geektrust/internal/settings" + public "github.com/ShanghaitechGeekPie/geektrust/compatibility" "net/url" "strings" ) type Resolved struct { Profile public.Profile - Compatibility settings.Compatibility + Fallbacks public.Fallbacks + Process *public.ProcessMetadata + GatewayServerName string Platform, LoginDomain string } @@ -36,13 +37,14 @@ func Resolve(origin string, o public.Options) Resolved { v.Platform = o.Protocol.ControllerPlatform } if x := o.Protocol.Process; x != nil { - v.Compatibility.ProcessIdentity = &settings.ProcessIdentity{Name: x.Name, Platform: x.Platform, Path: x.Path} + value := *x + v.Process = &value } if f := o.Fallbacks; f != nil { - v.Compatibility.FallbackAppID = f.ApplicationID - v.Compatibility.FallbackGateways = append([]string(nil), f.Gateways...) - v.Compatibility.MissingGatewayGroupFallback = f.MissingGatewayGroup - v.Compatibility.TCPToL3Fallback = f.StreamToL3 + v.Fallbacks.ApplicationID = f.ApplicationID + v.Fallbacks.Gateways = append([]string(nil), f.Gateways...) + v.Fallbacks.MissingGatewayGroup = f.MissingGatewayGroup + v.Fallbacks.StreamToL3 = f.StreamToL3 } return v } diff --git a/internal/compatibility/shanghaitech.go b/internal/compatibility/shanghaitech.go new file mode 100644 index 0000000..862ec8e --- /dev/null +++ b/internal/compatibility/shanghaitech.go @@ -0,0 +1,10 @@ +package compatibility + +import ( + public "github.com/ShanghaitechGeekPie/geektrust/compatibility" +) + +// Preserve the existing compatibility's missing-information fallbacks, after server policy. +func shanghaiTechProfile() Resolved { + return Resolved{Profile: public.ShanghaiTech, Platform: "Mac", LoginDomain: "Shanghaitech.edu.cn", GatewayServerName: "vpn.shanghaitech.edu.cn", Fallbacks: public.Fallbacks{ApplicationID: "681165d0-1c77-11ed-8650-cd35a51aa42a", Gateways: []string{"119.78.254.241:441", "59.78.171.241:441"}, MissingGatewayGroup: true, StreamToL3: true}} +} diff --git a/internal/config/compatibility_test.go b/internal/config/compatibility_test.go index 65393d0..a98801c 100644 --- a/internal/config/compatibility_test.go +++ b/internal/config/compatibility_test.go @@ -7,67 +7,15 @@ import ( "testing" ) -func TestCompatibilityConfigIsExplicit(t *testing.T) { - for _, controller := range []string{DefaultBaseURL, "https://vpn.ecnu.edu.cn", "https://vpn.example.org"} { - t.Run(controller, func(t *testing.T) { - path := filepath.Join(t.TempDir(), "config.toml") - base := "keystore = 'synthetic.keystore'\nbase_url = '" + controller + "'\n" - for _, enabled := range []bool{false, true, false} { - body := base - if enabled { - body += `login_domain = "custom-domain" -[compatibility] -fallback_app_id = "custom-app" -fallback_gateways = ["gateway.example:441", "[2001:db8::1]:441"] -gateway_server_name = "gateway.example" -missing_gateway_group_fallback = true -tcp_to_l3_fallback = true -` - } - if err := os.WriteFile(path, []byte(body), 0600); err != nil { - t.Fatal(err) - } - c, err := Load(path) - if err != nil { - t.Fatal(err) - } - if enabled { - if c.Compatibility.FallbackAppID != "custom-app" || c.GatewayServerName() != "gateway.example" || c.LoginDomain != "custom-domain" { - t.Fatal("explicit settings lost") - } - } else if controller == DefaultBaseURL { - if c.GatewayServerName() != "vpn.shanghaitech.edu.cn" || c.Compatibility.FallbackAppID == "" { - t.Fatal("ShanghaiTech defaults missing") - } - } else if c.GatewayServerName() != "" || c.Compatibility.FallbackAppID != "" { - t.Fatal("school defaults leaked") - } - - after, err := os.ReadFile(path) - if err != nil || string(after) != body { - t.Fatal("loading changed original configuration") - } - } - }) +func TestRejectUnreleasedCompatibilitySection(t *testing.T) { + p := filepath.Join(t.TempDir(), "config.toml") + if err := os.WriteFile(p, []byte("keystore='fixture'\n[compatibility]\nfallback_app_id='old'\n"), 0600); err != nil { + t.Fatal(err) } -} - -func TestCompatibilityConfigRejectsMistakes(t *testing.T) { - for _, setting := range []string{ - "[compatibility]\nfallback_gateways = ['gateway:0']", - "[compatibility]\nfallback_gateways = ['gateway']", - "[compatibility]\ngateway_server_name = 'https://gateway'", - } { - path := filepath.Join(t.TempDir(), "config.toml") - if err := os.WriteFile(path, []byte("keystore = 'synthetic.keystore'\n"+setting), 0600); err != nil { - t.Fatal(err) - } - if _, err := Load(path); err == nil { - t.Fatalf("accepted invalid setting: %s", setting) - } + if _, err := Load(p); err == nil { + t.Fatal("unreleased compatibility format retained") } } - func TestGeneratedConfigDefaultsToShanghaiTech(t *testing.T) { cfg, e := PrepareInitialConfig(InitOptions{}) if e != nil { @@ -85,7 +33,7 @@ func TestGeneratedConfigDefaultsToShanghaiTech(t *testing.T) { if e != nil { t.Fatal(e) } - if v.GatewayServerName() != "vpn.shanghaitech.edu.cn" || !v.Compatibility.TCPToL3Fallback { + if v.GatewayServerName() != "vpn.shanghaitech.edu.cn" || !v.Fallbacks.StreamToL3 { t.Fatal("minimal ShanghaiTech defaults missing") } } diff --git a/internal/config/config.go b/internal/config/config.go index 220164d..e50e041 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -3,9 +3,10 @@ package config import ( "fmt" - public "github.com/ShanghaitechGeekPie/geektrust/deployment" - defaults "github.com/ShanghaitechGeekPie/geektrust/internal/deployment" + public "github.com/ShanghaitechGeekPie/geektrust/compatibility" + defaults "github.com/ShanghaitechGeekPie/geektrust/internal/compatibility" "net" + "net/url" "os" "strconv" "strings" @@ -29,29 +30,28 @@ const DefaultWebListen = "127.0.0.1:8081" // Config is the top-level configuration. type Config struct { - UnknownFields []string `toml:"-"` - CompatibilityExplicit bool `toml:"-"` - Version int `toml:"-"` - Deployment public.Profile `toml:"-"` - DNSStrategy string `toml:"-"` - Directory string `toml:"-"` - CAFile string `toml:"-"` - SourcePath string `toml:"-"` - AppID string `toml:"app_id"` + UnknownFields []string `toml:"-"` + Version int `toml:"-"` + Compatibility public.Profile `toml:"-"` + DNSStrategy string `toml:"-"` + Directory string `toml:"-"` + CAFile string `toml:"-"` + AppID string `toml:"app_id"` - Compatibility settings.Compatibility `toml:"compatibility"` - Keystore string `toml:"keystore"` - DeviceID string `toml:"device_id"` - BaseURL string `toml:"base_url"` - Platform string `toml:"platform"` - ClientType string `toml:"client_type"` - LoginDomain string `toml:"login_domain"` - Gateways []string `toml:"gateways"` - DNS []string `toml:"dns"` - StateFile string `toml:"state_file"` - LogLevel string `toml:"log_level"` - Inbound Inbound `toml:"inbound"` - Web WebConfig `toml:"web"` + Fallbacks public.Fallbacks `toml:"-"` + GatewayTLSName string `toml:"-"` + Keystore string `toml:"keystore"` + DeviceID string `toml:"device_id"` + BaseURL string `toml:"base_url"` + Platform string `toml:"platform"` + ClientType string `toml:"client_type"` + LoginDomain string `toml:"login_domain"` + Gateways []string `toml:"gateways"` + DNS []string `toml:"dns"` + StateFile string `toml:"state_file"` + LogLevel string `toml:"log_level"` + Inbound Inbound `toml:"inbound"` + Web WebConfig `toml:"web"` } // Inbound holds the proxy listener configuration. @@ -106,21 +106,18 @@ func Load(path string) (*Config, error) { for _, key := range meta.Undecoded() { cfg.UnknownFields = append(cfg.UnknownFields, key.String()) } - cfg.CompatibilityExplicit = meta.IsDefined("compatibility") + if meta.IsDefined("compatibility") { + return nil, fmt.Errorf("unsupported configuration field compatibility") + } cfg.Version = 1 - cfg.SourcePath = path cfg.DNSStrategy = "auto" cfg.applyDefaults() - if !meta.IsDefined("compatibility") { - cfg.Compatibility = defaults.Resolve(cfg.BaseURL, public.Options{}).Compatibility - } + profile := defaults.Resolve(cfg.BaseURL, public.Options{}) + cfg.Fallbacks = profile.Fallbacks + cfg.GatewayTLSName = profile.GatewayServerName if cfg.AppID != "" { - if meta.IsDefined("compatibility", "fallback_app_id") && cfg.Compatibility.FallbackAppID != cfg.AppID { - return nil, fmt.Errorf("conflicting app_id and compatibility.fallback_app_id") - } - cfg.Compatibility.FallbackAppID = cfg.AppID + cfg.Fallbacks.ApplicationID = cfg.AppID } - cfg.applyDefaults() if err := cfg.validate(); err != nil { return nil, fmt.Errorf("config %s: %w", path, err) } @@ -154,7 +151,7 @@ func (c *Config) applyDefaults() { } func (c *Config) validate() error { - if err := c.Compatibility.Validate(); err != nil { + if err := (public.Options{Fallbacks: &c.Fallbacks}).Validate(); err != nil { return err } if c.Keystore == "" { @@ -163,8 +160,9 @@ func (c *Config) validate() error { if !(c.Version == 2 && c.DeviceID == "") && !isUpperHex32(c.DeviceID) { return fmt.Errorf("device_id must be 32 uppercase hex chars, got %q", c.DeviceID) } - if !strings.HasPrefix(c.BaseURL, "https://") && !strings.HasPrefix(c.BaseURL, "http://") { - return fmt.Errorf("base_url must be an http(s) URL, got %q", c.BaseURL) + u, err := url.Parse(c.BaseURL) + if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.ForceQuery || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") { + return fmt.Errorf("base_url must be an HTTPS origin") } // Platform is a server-defined, case-sensitive protocol value, not GOOS. if len(c.Platform) > 64 || strings.IndexFunc(c.Platform, unicode.IsControl) >= 0 { @@ -279,10 +277,10 @@ func SplitHostPort(addr string) (host string, port string, err error) { // GatewayServerName returns an explicit TLS certificate identity override. func (c *Config) GatewayServerName() string { - return c.Compatibility.GatewayServerName + return c.GatewayTLSName } // SessionOptions translates the legacy file DTO to normalized session settings. func (c *Config) SessionOptions() settings.Session { - return settings.Session{BaseURL: c.BaseURL, DeviceID: c.DeviceID, Platform: c.Platform, ClientType: c.ClientType, LoginDomain: c.LoginDomain, Keystore: c.Keystore, StateFile: c.StateFile, Gateways: append([]string(nil), c.Gateways...), DNS: append([]string(nil), c.DNS...), Compatibility: c.Compatibility.Clone(), GatewayFilter: c.Version == 2 && c.Gateways != nil, LegacyGatewayOverride: c.Version != 2 && len(c.Gateways) > 0, DNSConfigured: len(c.DNS) > 0} + return settings.Session{BaseURL: c.BaseURL, DeviceID: c.DeviceID, Platform: c.Platform, ClientType: c.ClientType, LoginDomain: c.LoginDomain, Gateways: append([]string(nil), c.Gateways...), DNS: append([]string(nil), c.DNS...), Fallbacks: c.Fallbacks, GatewayFilter: c.Version == 2 && c.Gateways != nil, LegacyGatewayOverride: c.Version != 2 && len(c.Gateways) > 0, DNSConfigured: len(c.DNS) > 0} } diff --git a/internal/config/controller_origin_regression_test.go b/internal/config/controller_origin_regression_test.go new file mode 100644 index 0000000..3de632f --- /dev/null +++ b/internal/config/controller_origin_regression_test.go @@ -0,0 +1,34 @@ +package config + +import ( + "os" + "path/filepath" + "strconv" + "testing" +) + +func TestLegacyConfigRejectsControllerURLsRuntimeCannotUse(t *testing.T) { + for _, origin := range []string{"http://vpn.example.edu.cn", "https://vpn.example.edu.cn/resource", "https://private:secret@vpn.example.edu.cn", "https://vpn.example.edu.cn?ticket=secret", "https://vpn.example.edu.cn#fragment"} { + t.Run(origin, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.toml") + if err := os.WriteFile(path, []byte("keystore='fixture'\nbase_url="+strconv.Quote(origin)+"\n"), 0600); err != nil { + t.Fatal(err) + } + if _, err := Load(path); err == nil { + t.Fatal("configuration passed validation with an unusable controller URL") + } + }) + } +} + +func TestConfigRejectsEmptyQueryMarker(t *testing.T) { + for _, data := range []string{"keystore='fixture'\nbase_url='https://vpn.example.edu.cn?'\n", "config_version=2\n[auth.passkey]\nkeystore='fixture'\n[controller]\nurl='https://vpn.example.edu.cn?'\n"} { + p := filepath.Join(t.TempDir(), "config.toml") + if err := os.WriteFile(p, []byte(data), 0600); err != nil { + t.Fatal(err) + } + if _, err := Load(p); err == nil { + t.Fatal("URL ending in a query marker was accepted") + } + } +} diff --git a/internal/config/v2.go b/internal/config/v2.go index c36bb52..172c2b7 100644 --- a/internal/config/v2.go +++ b/internal/config/v2.go @@ -5,8 +5,8 @@ import ( "errors" "fmt" "github.com/BurntSushi/toml" - public "github.com/ShanghaitechGeekPie/geektrust/deployment" - defaults "github.com/ShanghaitechGeekPie/geektrust/internal/deployment" + public "github.com/ShanghaitechGeekPie/geektrust/compatibility" + defaults "github.com/ShanghaitechGeekPie/geektrust/internal/compatibility" "github.com/ShanghaitechGeekPie/geektrust/internal/storage" "net" "net/url" @@ -21,9 +21,9 @@ import ( type FileV2 struct { Version int `toml:"config_version"` Controller struct { - URL string `toml:"url"` - Deployment string `toml:"deployment"` - Platform string `toml:"platform"` + URL string `toml:"url"` + Compatibility string `toml:"compatibility"` + Platform string `toml:"platform"` } `toml:"controller"` Auth struct { Mode string `toml:"mode"` @@ -51,8 +51,6 @@ type FileV2 struct { Storage struct { Directory string `toml:"directory"` StateFile string `toml:"state_file"` - // LegacyState is a read-compatible alias; new output uses state_file. - LegacyState string `toml:"legacy_state,omitempty"` } `toml:"storage"` Logging struct { Level string `toml:"level"` @@ -100,11 +98,11 @@ func loadV2(path string, data []byte) (*Config, error) { f.Controller.URL = DefaultBaseURL } u, e := url.Parse(f.Controller.URL) - if e != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") { + if e != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.ForceQuery || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") { return nil, errors.New("controller.url must be an HTTPS origin") } - profile := public.Profile(f.Controller.Deployment) - if f.Controller.Deployment == "auto" { + profile := public.Profile(f.Controller.Compatibility) + if f.Controller.Compatibility == "auto" { profile = public.Auto } if e := (public.Options{Profile: profile}).Validate(); e != nil { @@ -144,7 +142,7 @@ func loadV2(path string, data []byte) (*Config, error) { return nil, e } } - cfg := &Config{Version: 2, SourcePath: path, Directory: directory, DeviceID: id, Keystore: resolve(f.Auth.Passkey.Keystore), BaseURL: strings.TrimRight(f.Controller.URL, "/"), Platform: v.Platform, Deployment: profile, ClientType: mode, LoginDomain: f.Auth.LoginDomain, Compatibility: v.Compatibility, StateFile: filepath.Join(directory, "session.enc"), DNS: append([]string(nil), f.DNS.Servers...), DNSStrategy: f.DNS.Strategy, LogLevel: f.Logging.Level} + cfg := &Config{Version: 2, Directory: directory, DeviceID: id, Keystore: resolve(f.Auth.Passkey.Keystore), BaseURL: strings.TrimRight(f.Controller.URL, "/"), Platform: v.Platform, Compatibility: profile, ClientType: mode, LoginDomain: f.Auth.LoginDomain, Fallbacks: v.Fallbacks, GatewayTLSName: v.GatewayServerName, StateFile: filepath.Join(directory, "session.enc"), DNS: append([]string(nil), f.DNS.Servers...), DNSStrategy: f.DNS.Strategy, LogLevel: f.Logging.Level} if cfg.DNSStrategy == "" { cfg.DNSStrategy = "auto" } @@ -154,22 +152,15 @@ func loadV2(path string, data []byte) (*Config, error) { if cfg.LoginDomain == "" { cfg.LoginDomain = v.LoginDomain } - stateFile := resolve(f.Storage.StateFile) - legacyState := resolve(f.Storage.LegacyState) - if meta.IsDefined("storage", "state_file") && meta.IsDefined("storage", "legacy_state") && stateFile != legacyState { - return nil, errors.New("conflicting storage.state_file and storage.legacy_state") - } - if stateFile != "" { - cfg.StateFile = stateFile - } else if legacyState != "" { - cfg.StateFile = legacyState + if f.Storage.StateFile != "" { + cfg.StateFile = resolve(f.Storage.StateFile) } cfg.Gateways = f.Routing.GatewayFilter if f.Routing.FallbackAppID != "" { - cfg.Compatibility.FallbackAppID = f.Routing.FallbackAppID + cfg.Fallbacks.ApplicationID = f.Routing.FallbackAppID } if f.TLS.Gateway.ServerName != "" { - cfg.Compatibility.GatewayServerName = f.TLS.Gateway.ServerName + cfg.GatewayTLSName = f.TLS.Gateway.ServerName } cfg.CAFile = resolve(f.TLS.Gateway.CAFile) socks, http, web := "127.0.0.1:1080", "127.0.0.1:8080", DefaultWebListen @@ -274,17 +265,14 @@ func Migration(path string) ([]byte, error) { if c.Version == 2 { return os.ReadFile(path) } - if c.CompatibilityExplicit && (c.Compatibility.ProcessIdentity != nil || len(c.Compatibility.FallbackGateways) > 0 || c.Compatibility.TCPToL3Fallback || c.Compatibility.MissingGatewayGroupFallback) { - return nil, errors.New("explicit legacy protocol/fallback settings require manual migration; keep the original configuration") - } if len(c.Gateways) > 0 { return nil, errors.New("legacy gateways override cannot be converted automatically; select permitted gateway filters explicitly") } var f FileV2 f.Version = 2 f.Controller.URL = c.BaseURL - if c.Compatibility.GatewayServerName == "" && c.Compatibility.FallbackAppID == "" && !c.Compatibility.TCPToL3Fallback && !c.Compatibility.MissingGatewayGroupFallback { - f.Controller.Deployment = "generic" + if c.GatewayTLSName == "" && c.Fallbacks.ApplicationID == "" && !c.Fallbacks.StreamToL3 && !c.Fallbacks.MissingGatewayGroup { + f.Controller.Compatibility = "generic" } f.Controller.Platform = c.Platform f.Auth.Mode = c.ClientType @@ -314,7 +302,7 @@ func Migration(path string) ([]byte, error) { f.DNS.Servers = c.DNS f.Logging.Level = c.LogLevel f.Routing.FallbackAppID = c.AppID - f.TLS.Gateway.ServerName = c.Compatibility.GatewayServerName + f.TLS.Gateway.ServerName = c.GatewayTLSName var b bytes.Buffer e = toml.NewEncoder(&b).Encode(f) return b.Bytes(), e diff --git a/internal/config/v2_test.go b/internal/config/v2_test.go index e10359e..db560da 100644 --- a/internal/config/v2_test.go +++ b/internal/config/v2_test.go @@ -10,7 +10,7 @@ import ( func TestV2MinimalAndReadOnly(t *testing.T) { dir := t.TempDir() p := filepath.Join(dir, "config.toml") - data := "config_version = 2\n[controller]\ndeployment='auto'\n[auth.passkey]\nkeystore = './credential'\n[storage]\ndirectory = './private'\n" + data := "config_version = 2\n[controller]\ncompatibility='auto'\n[auth.passkey]\nkeystore = './credential'\n[storage]\ndirectory = './private'\n" if e := os.WriteFile(p, []byte(data), 0600); e != nil { t.Fatal(e) } @@ -79,21 +79,21 @@ func TestV2StrictAndLegacyMigration(t *testing.T) { } } -func TestV2StateFileAliasAndConflicts(t *testing.T) { +func TestV2StateFileRejectsRemovedName(t *testing.T) { dir := t.TempDir() p := filepath.Join(dir, "config.toml") base := "config_version = 2\n[auth.passkey]\nkeystore = './credential'\n[storage]\ndirectory = './private'\n" cases := []struct { name, storage, want string - conflict bool + rejected bool }{ {"default", "", filepath.Join(dir, "private", "session.enc"), false}, {"new path", "state_file = './current.enc'\n", filepath.Join(dir, "current.enc"), false}, - {"legacy path", "legacy_state = './previous.enc'\n", filepath.Join(dir, "previous.enc"), false}, + {"removed name", "legacy_state = './previous.enc'\n", "", true}, {"empty new path", "state_file = ''\n", filepath.Join(dir, "private", "session.enc"), false}, - {"equivalent aliases", "state_file = './cache.enc'\nlegacy_state = 'nested/../cache.enc'\n", filepath.Join(dir, "cache.enc"), false}, - {"conflicting aliases", "state_file = './new.enc'\nlegacy_state = './old.enc'\n", "", true}, - {"explicit empty conflicts", "state_file = './new.enc'\nlegacy_state = ''\n", "", true}, + + {"removed name beside current name", "state_file = './new.enc'\nlegacy_state = './old.enc'\n", "", true}, + {"empty removed name", "state_file = './new.enc'\nlegacy_state = ''\n", "", true}, } for _, tt := range cases { t.Run(tt.name, func(t *testing.T) { @@ -102,9 +102,9 @@ func TestV2StateFileAliasAndConflicts(t *testing.T) { t.Fatal(err) } cfg, err := Load(p) - if tt.conflict { - if err == nil || !strings.Contains(err.Error(), "conflicting storage.state_file") { - t.Fatalf("expected conflict, got %v", err) + if tt.rejected { + if err == nil || !strings.Contains(err.Error(), "unknown configuration field storage.legacy_state") { + t.Fatalf("expected removed-field rejection, got %v", err) } } else { if err != nil { @@ -127,3 +127,28 @@ func TestV2StateFileAliasAndConflicts(t *testing.T) { }) } } + +func TestV2ControllerCompatibilityName(t *testing.T) { + for _, field := range []string{"compatibility", "deployment"} { + t.Run(field, func(t *testing.T) { + p := filepath.Join(t.TempDir(), "config.toml") + data := "config_version=2\n[controller]\n" + field + "='generic'\n[auth.passkey]\nkeystore='credential'\n" + if err := os.WriteFile(p, []byte(data), 0600); err != nil { + t.Fatal(err) + } + c, err := Load(p) + if field == "deployment" { + if err == nil { + t.Fatal("removed controller.deployment accepted") + } + return + } + if err != nil { + t.Fatal(err) + } + if string(c.Compatibility) != "generic" { + t.Fatalf("compatibility = %q", c.Compatibility) + } + }) + } +} diff --git a/internal/deployment/shanghaitech.go b/internal/deployment/shanghaitech.go deleted file mode 100644 index 6cc75e4..0000000 --- a/internal/deployment/shanghaitech.go +++ /dev/null @@ -1,11 +0,0 @@ -package deployment - -import ( - public "github.com/ShanghaitechGeekPie/geektrust/deployment" - "github.com/ShanghaitechGeekPie/geektrust/internal/settings" -) - -// Preserve the existing deployment's missing-information fallbacks, after server policy. -func shanghaiTechProfile() Resolved { - return Resolved{Profile: public.ShanghaiTech, Platform: "Mac", LoginDomain: "Shanghaitech.edu.cn", Compatibility: settings.Compatibility{GatewayServerName: "vpn.shanghaitech.edu.cn", FallbackAppID: "681165d0-1c77-11ed-8650-cd35a51aa42a", FallbackGateways: []string{"119.78.254.241:441", "59.78.171.241:441"}, MissingGatewayGroupFallback: true, TCPToL3Fallback: true}} -} diff --git a/internal/idsauth/client.go b/internal/idsauth/client.go index c4502be..34ab0e5 100644 --- a/internal/idsauth/client.go +++ b/internal/idsauth/client.go @@ -2,6 +2,7 @@ package idsauth import ( "context" + "errors" "net/http" "strings" ) @@ -55,7 +56,24 @@ func (c *Client) IsLoggedIn(ctx context.Context) (bool, error) { return c.backen func (c *Client) do(req *http.Request) (*http.Response, error) { c.setHeaders(req) - return c.HTTP.Do(req) + hc := *c.HTTP + checkRedirect := hc.CheckRedirect + hc.CheckRedirect = func(r *http.Request, via []*http.Request) error { + // A successful login may navigate to another service. Return that + // response and confirm the identity session separately; never forward + // assertion data or fetch challenges outside the credential origin. + if r.URL.Scheme != req.URL.Scheme || r.URL.Host != req.URL.Host { + return http.ErrUseLastResponse + } + if checkRedirect != nil { + return checkRedirect(r, via) + } + if len(via) >= 10 { + return errors.New("identity redirect limit") + } + return nil + } + return hc.Do(req) } // doNoRedirect performs a request without following redirects, regardless of diff --git a/internal/idsauth/ecnu.go b/internal/idsauth/ecnu.go index 33e93bf..d368c56 100644 --- a/internal/idsauth/ecnu.go +++ b/internal/idsauth/ecnu.go @@ -192,7 +192,7 @@ func (c *ecnuClient) request(ctx context.Context, method, target, content string return b, nil } func (c *ecnuClient) Login(ctx context.Context) error { - if c.BaseURL != c.Keystore.BaseURL() || c.Origin != c.BaseURL { + if c.BaseURL != strings.TrimRight(c.Keystore.BaseURL(), "/") || c.Origin != c.BaseURL { return errors.New("credential origin mismatch") } page, err := c.request(ctx, http.MethodGet, c.BaseURL+"/login", "", nil, nil, true) diff --git a/internal/idsauth/ecnu_flow_test.go b/internal/idsauth/ecnu_flow_test.go index 1b89d01..df2c954 100644 --- a/internal/idsauth/ecnu_flow_test.go +++ b/internal/idsauth/ecnu_flow_test.go @@ -25,8 +25,16 @@ func TestECNUFlow(t *testing.T) { t.Fatal(err) } script := pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: der}) - for _, failSave := range []bool{false, true} { - t.Run(fmt.Sprintf("storage_failure_%t", failSave), func(t *testing.T) { + for _, tc := range []struct { + name string + failSave bool + suffix string + }{ + {name: "storage_failure_false"}, + {name: "storage_failure_true", failSave: true}, + {name: "trailing_slash", suffix: "/"}, + } { + t.Run(tc.name, func(t *testing.T) { persisted, submitted := false, false var origin string server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -67,11 +75,11 @@ func TestECNUFlow(t *testing.T) { origin = server.URL u, _ := url.Parse(origin) fields := testKeystoreMap(t) - fields["base_url"], fields["rp_id"] = origin, u.Hostname() + fields["base_url"], fields["rp_id"] = origin+tc.suffix, u.Hostname() blob := pythonFormat(t, fields) blob = append(append([]byte{}, ecnuMagic...), blob[len(keystoreMagic):]...) store, err := ParseKeystore(blob, func(b []byte) error { - if failSave { + if tc.failSave { return errors.New("storage unavailable") } k, e := ParseKeystore(b, nil) @@ -89,7 +97,7 @@ func TestECNUFlow(t *testing.T) { t.Fatal(err) } err = NewClient(store, server.Client()).Login(context.Background()) - if failSave { + if tc.failSave { if err == nil || submitted { t.Fatal("failed persistence did not stop authentication") } diff --git a/internal/idsauth/keystore.go b/internal/idsauth/keystore.go index 7824153..ebc27f8 100644 --- a/internal/idsauth/keystore.go +++ b/internal/idsauth/keystore.go @@ -96,7 +96,7 @@ func (k *Keystore) validate() error { } } u, err := url.Parse(k.BaseURL()) - if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") { + if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.ForceQuery || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") { return fmt.Errorf("credential base_url must be an HTTPS origin") } if !rpIDMatchesOrigin(k.RpID(), k.BaseURL()) { diff --git a/internal/idsauth/origin_regression_test.go b/internal/idsauth/origin_regression_test.go new file mode 100644 index 0000000..cd9c2d7 --- /dev/null +++ b/internal/idsauth/origin_regression_test.go @@ -0,0 +1,11 @@ +package idsauth + +import "testing" + +func TestKeystoreRejectsEmptyQueryMarker(t *testing.T) { + fields := testKeystoreMap(t) + fields["base_url"] = "https://ids.shanghaitech.edu.cn?" + if _, err := ParseKeystore(pythonFormat(t, fields), nil); err == nil { + t.Fatal("credential origin ending in a query marker was accepted") + } +} diff --git a/internal/idsauth/redirect_origin_test.go b/internal/idsauth/redirect_origin_test.go new file mode 100644 index 0000000..6d15a2f --- /dev/null +++ b/internal/idsauth/redirect_origin_test.go @@ -0,0 +1,69 @@ +package idsauth + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" +) + +func TestIdentityRequestDoesNotForwardAcrossOrigins(t *testing.T) { + for _, status := range []int{http.StatusFound, http.StatusTemporaryRedirect, http.StatusPermanentRedirect} { + t.Run(http.StatusText(status), func(t *testing.T) { + var foreignCalls atomic.Int32 + foreign := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + foreignCalls.Add(1) + })) + defer foreign.Close() + identity := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, foreign.URL+"/collect", status) + })) + defer identity.Close() + client := &Client{HTTP: identity.Client(), UserAgent: DefaultUserAgent} + req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, identity.URL+"/authserver/login", strings.NewReader("assertion=identity-only")) + if err != nil { + t.Fatal(err) + } + resp, err := client.do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if foreignCalls.Load() != 0 { + t.Fatal("identity request was forwarded outside its origin") + } + if resp.StatusCode != status { + t.Fatal("terminal redirect was lost") + } + }) + } +} + +func TestIdentityRequestFollowsSameOriginRedirect(t *testing.T) { + identity := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/result" { + http.Redirect(w, r, "/result", http.StatusTemporaryRedirect) + return + } + if r.Method != http.MethodPost { + t.Error("same-origin redirect lost POST") + } + w.WriteHeader(http.StatusOK) + })) + defer identity.Close() + client := &Client{HTTP: identity.Client(), UserAgent: DefaultUserAgent} + req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, identity.URL+"/authserver/login", strings.NewReader("assertion=identity-only")) + if err != nil { + t.Fatal(err) + } + resp, err := client.do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatal("same-origin redirect failed") + } +} diff --git a/internal/idsauth/shtu_test.go b/internal/idsauth/shtu_test.go index d9a3fdd..e4cb0b1 100644 --- a/internal/idsauth/shtu_test.go +++ b/internal/idsauth/shtu_test.go @@ -9,6 +9,7 @@ import ( "net/http/cookiejar" "net/http/httptest" "net/url" + "sync/atomic" "testing" ) @@ -16,6 +17,11 @@ func TestShanghaiTechLoginAndDurableCounter(t *testing.T) { for _, failSave := range []bool{false, true} { t.Run(fmt.Sprintf("save_failure_%t", failSave), func(t *testing.T) { persisted, submitted := false, false + var foreignCalls atomic.Int32 + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + foreignCalls.Add(1) + })) + defer service.Close() var origin string server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { @@ -32,6 +38,7 @@ func TestShanghaiTechLoginAndDurableCounter(t *testing.T) { t.Error("ShanghaiTech form fields changed") } http.SetCookie(w, &http.Cookie{Name: "CASTGC", Value: "synthetic-cookie", Path: "/"}) + http.Redirect(w, r, service.URL+"/", http.StatusSeeOther) case "/authserver/startAssertion": parsed, _ := url.Parse(origin) options := challengeOptions() @@ -66,6 +73,9 @@ func TestShanghaiTechLoginAndDurableCounter(t *testing.T) { hc := server.Client() hc.Jar, _ = cookiejar.New(nil) err = NewClient(store, hc).Login(context.Background()) + if foreignCalls.Load() != 0 { + t.Fatal("login followed an external service instead of checking the identity session") + } if failSave { if err == nil || submitted { t.Fatal("storage failure did not stop login") diff --git a/internal/inbound/udp.go b/internal/inbound/udp.go index 5fd4586..7c4c030 100644 --- a/internal/inbound/udp.go +++ b/internal/inbound/udp.go @@ -146,7 +146,7 @@ func (t *udpFlowTable) flow(ctx context.Context, target udpTarget, boundSetup bo if err != nil { return nil, err } - conn, err := t.server.dialer.DialUDP(ctx, resolved.IP, target.port, resolved.AppID, resolved.Domain) + conn, err := t.server.dialTarget(ctx, resolved, target.port, "udp") if err != nil { return nil, err } diff --git a/internal/l3/auth.go b/internal/l3/auth.go index 4d064ae..1bc56e9 100644 --- a/internal/l3/auth.go +++ b/internal/l3/auth.go @@ -8,7 +8,7 @@ import ( "net" "time" - "github.com/ShanghaitechGeekPie/geektrust/internal/settings" + "github.com/ShanghaitechGeekPie/geektrust/compatibility" ) const ( @@ -72,7 +72,7 @@ var procFingerprint = fmt.Sprintf("%X", sha256.Sum256([]byte(procPath))) // buildAuthRequestIP serializes a per-flow auth body. domain is the original // hostname for wildcard-authorized targets (empty otherwise). -func buildAuthRequestIP(sid, appID, deviceID, dstIP string, dstPort int, vip net.IP, srcPort uint16, conntrackHash uint64, domain string, protocol int, identity *settings.ProcessIdentity) ([]byte, error) { +func buildAuthRequestIP(sid, appID, deviceID, dstIP string, dstPort int, vip net.IP, srcPort uint16, conntrackHash uint64, domain string, protocol int, identity *compatibility.ProcessMetadata) ([]byte, error) { network, err := protocolName(protocol) if err != nil { return nil, err @@ -89,7 +89,7 @@ func buildAuthRequestIP(sid, appID, deviceID, dstIP string, dstPort int, vip net p.Description = "TrustAppClosed" p.Path = procPath if identity != nil { - if err := identity.Validate(); err != nil { + if err := (compatibility.Options{Protocol: compatibility.ProtocolOptions{Process: identity}}).Validate(); err != nil { return nil, err } p.Name, p.Platform, p.Path = identity.Name, identity.Platform, identity.Path diff --git a/internal/l3/auth_test.go b/internal/l3/auth_test.go index d995b04..1e4e365 100644 --- a/internal/l3/auth_test.go +++ b/internal/l3/auth_test.go @@ -9,7 +9,7 @@ import ( "strings" "testing" - "github.com/ShanghaitechGeekPie/geektrust/internal/settings" + "github.com/ShanghaitechGeekPie/geektrust/compatibility" ) func TestBuildAuthRequestIPShape(t *testing.T) { @@ -165,7 +165,7 @@ func TestBuildAuthRequestICMP(t *testing.T) { } func TestConfiguredProcessIdentity(t *testing.T) { - identity := &settings.ProcessIdentity{Name: "custom-client", Platform: "Windows", Path: "custom-client.exe"} + identity := &compatibility.ProcessMetadata{Name: "custom-client", Platform: "Windows", Path: "custom-client.exe"} body, err := buildAuthRequestIP("sid", "app", "device", "192.0.2.1", 443, net.IPv4(10, 0, 0, 1), 30000, 1, "", protocolTCP, identity) if err != nil { t.Fatal(err) diff --git a/internal/l3/dialer.go b/internal/l3/dialer.go index f0f9e4f..8f5c085 100644 --- a/internal/l3/dialer.go +++ b/internal/l3/dialer.go @@ -127,7 +127,7 @@ func (d *Dialer) dialWithRetry(ctx context.Context, network, ip string, port int return nil, fmt.Errorf("dial %s:%d after %d attempt(s): %w", ip, port, attempts, lastErr) } func shouldRetryDial(err error) bool { - if errors.Is(err, syscall.ECONNREFUSED) { + if errors.Is(err, syscall.ECONNREFUSED) || errors.Is(err, context.Canceled) || errors.Is(err, session.ErrSessionReplaced) { return false } var rejected *AuthRejectedError diff --git a/internal/l3/dialer_test.go b/internal/l3/dialer_test.go index 05afffb..8a379b3 100644 --- a/internal/l3/dialer_test.go +++ b/internal/l3/dialer_test.go @@ -3,6 +3,7 @@ package l3 import ( "context" "errors" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" "io" "log/slog" "net" @@ -35,6 +36,8 @@ func TestShouldRetryDial(t *testing.T) { {name: "line switch", err: &AuthRejectedError{Code: 1001, SwitchLine: true}, want: true}, {name: "persistent rejection", err: &AuthRejectedError{Code: 10000005}, want: false}, {name: "connection refused", err: syscall.ECONNREFUSED, want: false}, + {name: "session replaced", err: session.ErrSessionReplaced, want: false}, + {name: "cancelled", err: context.Canceled, want: false}, {name: "handshake timeout", err: context.DeadlineExceeded, want: true}, } for _, tc := range cases { diff --git a/internal/resolver/resolver.go b/internal/resolver/resolver.go index b50ac46..2ba66c2 100644 --- a/internal/resolver/resolver.go +++ b/internal/resolver/resolver.go @@ -41,7 +41,6 @@ type Resolver struct { tunnel TunnelDialer stages []lookupStage // direct public resolvers, then the system resolver tunnelDNS *dnsPool - controllerFirst bool disableTunnelDNS bool fallback func(context.Context, string) ([]netip.Addr, error) } @@ -183,6 +182,7 @@ func (r *Resolver) lookupIPv4(ctx context.Context, host string, cred *session.Cr } } if r.tunnel != nil && !r.disableTunnelDNS && len(cred.DNS) > 0 { + ctx = session.ExpectGeneration(ctx, cred.Generation) scope := r.tunnelDNSScope(cred) result, lookupErr := r.tunnelDNS.lookup(ctx, host, scope, cred.DNS, func(ctx context.Context, network, address string) (net.Conn, error) { server, _, err := net.SplitHostPort(address) @@ -220,7 +220,7 @@ func (r *Resolver) lookupIPv4(ctx context.Context, host string, cred *session.Cr return nil, err } for _, ip := range answers { - if ip.Is4() { + if ip.Is4() && !IsFakeIP(net.IP(ip.AsSlice())) { return net.IP(ip.AsSlice()), nil } } @@ -319,5 +319,5 @@ func (r *Resolver) LookupHost(ctx context.Context, host string) ([]string, error // NewController uses only controller DNS, with an explicit host fallback. func NewController(p session.CredentialProvider, t TunnelDialer, f func(context.Context, string) ([]netip.Addr, error), disabled bool) *Resolver { - return &Resolver{provider: p, tunnel: t, tunnelDNS: newDNSPool(), controllerFirst: true, disableTunnelDNS: disabled, fallback: f} + return &Resolver{provider: p, tunnel: t, tunnelDNS: newDNSPool(), disableTunnelDNS: disabled, fallback: f} } diff --git a/internal/resolver/resolver_test.go b/internal/resolver/resolver_test.go index 852d89c..5e3e27e 100644 --- a/internal/resolver/resolver_test.go +++ b/internal/resolver/resolver_test.go @@ -5,6 +5,7 @@ import ( "encoding/binary" "errors" "net" + "net/netip" "testing" "time" @@ -220,3 +221,14 @@ func TestResolveRejectsGatewayLoops(t *testing.T) { t.Fatalf("non-gateway endpoint resolution = %+v", got) } } + +func TestHostFallbackSkipsFakeIP(t *testing.T) { + provider := &staticProvider{cred: &session.Credential{Policy: &sdpc.Resource{}, AppID: "fixture"}} + r := NewController(provider, nil, func(context.Context, string) ([]netip.Addr, error) { + return []netip.Addr{netip.MustParseAddr("198.18.1.1"), netip.MustParseAddr("192.0.2.1")}, nil + }, false) + got, err := r.Resolve(context.Background(), "resource.example", 443) + if err != nil || got.IP != "192.0.2.1" { + t.Fatalf("fallback = %+v, %v", got, err) + } +} diff --git a/internal/runtime/client_test.go b/internal/runtime/client_test.go index d29f8ba..3d99b29 100644 --- a/internal/runtime/client_test.go +++ b/internal/runtime/client_test.go @@ -14,7 +14,8 @@ import ( "golang.org/x/net/dns/dnsmessage" - "github.com/ShanghaitechGeekPie/geektrust/internal/idsauth" + "github.com/ShanghaitechGeekPie/geektrust/auth" + "github.com/ShanghaitechGeekPie/geektrust/internal/storage" ) type testGatewayPins struct { @@ -22,35 +23,33 @@ type testGatewayPins struct { pins map[string][]byte } -func (s *testGatewayPins) LoadPin(ctx context.Context, addr string) ([]byte, error) { - s.mu.Lock() - defer s.mu.Unlock() - return append([]byte(nil), s.pins[addr]...), nil -} - -func (s *testGatewayPins) SavePin(ctx context.Context, addr string, pin []byte) error { +func (s *testGatewayPins) CheckOrEnroll(_ context.Context, id GatewayIdentity, pin [32]byte) (bool, error) { s.mu.Lock() defer s.mu.Unlock() if s.pins == nil { s.pins = make(map[string][]byte) } - s.pins[addr] = append([]byte(nil), pin...) - return nil + key := id.ControllerURL + "|" + id.Address + "|" + id.ServerName + if old := s.pins[key]; old != nil { + return string(old) == string(pin[:]), nil + } + s.pins[key] = append([]byte(nil), pin[:]...) + return true, nil } func TestValidateOptions(t *testing.T) { for _, url := range []string{"http://vpn.example", "https://user:secret@vpn.example", "https://vpn.example/?token=x"} { - if _, err := newLegacy(legacyOptions{ControllerURL: url, DeviceID: "0123456789ABCDEF0123456789ABCDEF", Authenticator: AuthenticatorFunc(func(context.Context, *http.Client) (string, error) { return "", nil })}); err == nil { + if _, err := New(Options{ControllerURL: url, DeviceID: "0123456789ABCDEF0123456789ABCDEF", Auth: AuthOptions{Identity: identityFunc(func(context.Context, *http.Client, auth.IdentityRequest) error { return nil })}}); err == nil { t.Fatal("invalid options accepted") } } } func TestClosedClient(t *testing.T) { id, _ := NewDeviceID() - c, err := newLegacy(legacyOptions{ControllerURL: "https://vpn.example", DeviceID: id, Authenticator: AuthenticatorFunc(func(context.Context, *http.Client) (string, error) { + c, err := New(Options{ControllerURL: "https://vpn.example", DeviceID: id, Auth: AuthOptions{Identity: identityFunc(func(context.Context, *http.Client, auth.IdentityRequest) error { t.Error("closed client authenticated") - return "", nil - })}) + return nil + })}}) if err != nil { t.Fatal(err) } @@ -80,16 +79,11 @@ func TestECNULiveAccess(t *testing.T) { t.Skip("explicit live credential required") } id, _ := NewDeviceID() - c, err := newLegacy(legacyOptions{Logger: slog.New(stageHandler{t}), ControllerURL: "https://vpn.ecnu.edu.cn", DeviceID: id, GatewayTrustStore: &testGatewayPins{}, Authenticator: AuthenticatorFunc(func(ctx context.Context, h *http.Client) (string, error) { - k, err := idsauth.LoadKeystore(path) - if err != nil { - return "", err - } - if err = idsauth.NewClient(k, h).Login(ctx); err != nil { - return "", err - } - return k.Username(), nil - })}) + identity, err := auth.NewPasskey(storage.CredentialFile(path)) + if err != nil { + t.Fatal(err) + } + c, err := New(Options{Logger: slog.New(stageHandler{t}), ControllerURL: "https://vpn.ecnu.edu.cn", DeviceID: id, Auth: AuthOptions{Identity: identity}, Network: NetworkOptions{GatewayTLS: GatewayTLSOptions{Mode: VerifyCAOrTOFU, PinStore: &testGatewayPins{}}}}) if err != nil { t.Fatal(err) } diff --git a/internal/runtime/command.go b/internal/runtime/command.go index d3ed888..1bdc664 100644 --- a/internal/runtime/command.go +++ b/internal/runtime/command.go @@ -3,7 +3,6 @@ package runtime import ( "context" "github.com/ShanghaitechGeekPie/geektrust/internal/resolver" - "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" "github.com/ShanghaitechGeekPie/geektrust/internal/session" "github.com/ShanghaitechGeekPie/geektrust/internal/settings" "net" @@ -49,7 +48,6 @@ func (c *Runtime) DialUDP(ctx context.Context, ip string, p int, app, domain str } return c.DialContext(ctx, "udp", net.JoinHostPort(host, strconv.Itoa(p))) } -func (c *Runtime) ActiveSDPC() *sdpc.Client { return c.provider.ActiveSDPC() } func (c *Runtime) TryForceRelogin() (func(context.Context), bool) { run, ok := c.provider.TryForceRelogin() if !ok { diff --git a/internal/runtime/compatibility_test.go b/internal/runtime/compatibility_test.go deleted file mode 100644 index 2f3ca39..0000000 --- a/internal/runtime/compatibility_test.go +++ /dev/null @@ -1,133 +0,0 @@ -package runtime - -import ( - "context" - "crypto/tls" - "errors" - "io" - "net/http" - "strings" - "testing" - "time" - - "github.com/ShanghaitechGeekPie/geektrust/internal/config" - "github.com/ShanghaitechGeekPie/geektrust/internal/settings" -) - -type compatibilityStore string - -func (s compatibilityStore) Load(context.Context) ([]byte, error) { return []byte(s), nil } -func (s compatibilityStore) Save(context.Context, []byte) error { return nil } - -type compatibilityTransport struct{} - -func (compatibilityTransport) RoundTrip(r *http.Request) (*http.Response, error) { - body := `{"code":0,"data":{}}` - switch r.URL.Path { - case "/passport/v1/user/onlineInfo": - body = `{"code":0,"data":{"isOnline":true}}` - case "/controller/v1/user/clientResource": - default: - return nil, errors.New("unexpected controller request") - } - return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}, nil -} - -func TestExplicitCompatibilityOptions(t *testing.T) { - template := &tls.Config{} - options := legacyOptions{ - Compatibility: settings.Compatibility{FallbackAppID: "custom-app", GatewayServerName: "gateway.example"}, - LoginDomain: "custom-domain", - ControllerURL: config.DefaultBaseURL, - DeviceID: "0123456789ABCDEF0123456789ABCDEF", - Gateways: []string{"override:441"}, DNS: []string{"10.0.0.53"}, - GatewayTLSConfig: template, Transport: compatibilityTransport{}, - SessionStore: compatibilityStore(`{"sid":"synthetic-session","device_id":"0123456789ABCDEF0123456789ABCDEF","client_type":"browser","cookies":[{"name":"sid","value":"synthetic-session"}]}`), - Authenticator: AuthenticatorFunc(func(context.Context, *http.Client) (string, error) { - return "", errors.New("unexpected full login") - }), - } - c, err := newLegacy(options) - if err != nil { - t.Fatal(err) - } - defer c.Close() - options.Gateways[0] = "mutated" - info, err := c.Connect(context.Background()) - if err != nil { - t.Fatal(err) - } - if len(info.Gateways) != 1 || info.Gateways[0] != "override:441" || len(info.DNS) != 1 || info.DNS[0] != "10.0.0.53" { - t.Fatal("configured routing overrides lost") - } - target, err := c.resolver.Resolve(context.Background(), "192.0.2.1", 443) - if err != nil || target.AppID != "custom-app" { - t.Fatal("legacy application fallback lost") - } - if c.provider.ActiveSDPC().LoginDomain != "custom-domain" { - t.Fatal("legacy CAS domain lost") - } - if c.manager.GatewayTLSConfig.ServerName != "gateway.example" || template.ServerName != "" { - t.Fatal("gateway certificate identity missing or caller TLS config mutated") - } -} - -func TestAuthenticationUsesCallerDeadline(t *testing.T) { - parent, cancel := context.WithTimeout(context.Background(), 90*time.Second) - defer cancel() - want, _ := parent.Deadline() - called := false - c, err := newLegacy(legacyOptions{ControllerURL: config.DefaultBaseURL, DeviceID: "0123456789ABCDEF0123456789ABCDEF", Authenticator: AuthenticatorFunc(func(ctx context.Context, _ *http.Client) (string, error) { - called = true - got, ok := ctx.Deadline() - if !ok || !got.Equal(want) { - t.Errorf("authentication deadline shortened: %v", got) - } - return "", errors.New("synthetic stop before network login") - })}) - if err != nil { - t.Fatal(err) - } - defer c.Close() - if _, err := c.Connect(parent); err == nil || !called { - t.Fatal("authentication fixture not exercised") - } -} - -type controllerTransport func(*http.Request) (*http.Response, error) - -func (f controllerTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } - -func TestRestoredSessionUsesCurrentCompatibility(t *testing.T) { - state := compatibilityStore(`{"sid":"synthetic","device_id":"0123456789ABCDEF0123456789ABCDEF","client_type":"browser","cookies":[{"name":"sid","value":"synthetic"}],"gateways":["stale.example:441"]}`) - for _, enabled := range []bool{true, false} { - options := legacyOptions{ControllerURL: config.DefaultBaseURL, DeviceID: "0123456789ABCDEF0123456789ABCDEF", Transport: compatibilityTransport{}, SessionStore: state, - Authenticator: AuthenticatorFunc(func(context.Context, *http.Client) (string, error) { - return "", errors.New("synthetic no fresh login") - }), - } - if enabled { - options.Compatibility = settings.Compatibility{FallbackAppID: "app", FallbackGateways: []string{"configured.example:441"}, TCPToL3Fallback: true} - } - c, err := newLegacy(options) - if err != nil { - t.Fatal(err) - } - if enabled { - options.Compatibility.FallbackGateways[0] = "mutated.example:441" - } - info, err := c.Connect(context.Background()) - if enabled { - if err != nil || len(info.Gateways) != 1 || info.Gateways[0] != "configured.example:441" { - t.Fatalf("configured fallback lost: %v", err) - } - cred, err := c.provider.Credential(context.Background()) - if err != nil || !cred.AllowTCPFallback || cred.MissingGatewayGroupFallback { - t.Fatal("independent compatibility switches not preserved") - } - } else if err == nil { - t.Fatal("cached gateways re-enabled a removed compatibility setting") - } - c.Close() - } -} diff --git a/internal/runtime/contract_test.go b/internal/runtime/contract_test.go index 77dd98e..5c4d554 100644 --- a/internal/runtime/contract_test.go +++ b/internal/runtime/contract_test.go @@ -5,7 +5,7 @@ import ( "encoding/json" "errors" "github.com/ShanghaitechGeekPie/geektrust/auth" - "github.com/ShanghaitechGeekPie/geektrust/deployment" + "github.com/ShanghaitechGeekPie/geektrust/compatibility" "github.com/ShanghaitechGeekPie/geektrust/internal/session" "io" "net/http" @@ -41,7 +41,7 @@ func (s *contractStore) Load(context.Context, SessionScope) ([]byte, error) { func (s *contractStore) Save(context.Context, SessionScope, []byte) error { return nil } func (s *contractStore) Delete(context.Context, SessionScope) error { return nil } func contractOptions(id *contractIdentity, store *contractStore) Options { - return Options{ControllerURL: "https://controller.example", DeviceID: "0123456789ABCDEF0123456789ABCDEF", Auth: AuthOptions{Identity: id}, Deployment: deployment.Options{Profile: deployment.Generic, Fallbacks: &deployment.Fallbacks{ApplicationID: "app", Gateways: []string{"gateway.example:441"}}}, Network: NetworkOptions{ControlTransport: compatibilityTransport{}}, SessionStore: store} + return Options{ControllerURL: "https://controller.example", DeviceID: "0123456789ABCDEF0123456789ABCDEF", Auth: AuthOptions{Identity: id}, Compatibility: compatibility.Options{Profile: compatibility.Generic, Fallbacks: &compatibility.Fallbacks{ApplicationID: "app", Gateways: []string{"gateway.example:441"}}}, Network: NetworkOptions{ControlTransport: fixtureTransport{}}, SessionStore: store} } func validState() session.State { return session.State{Version: 1, ControllerURL: "https://controller.example", IdentityIssuer: "fixture", IdentitySubject: "account", IdentityKind: "passkey", DeviceID: "0123456789ABCDEF0123456789ABCDEF", ClientType: "browser", SID: "secret", Cookies: []session.CookieRecord{{Name: "sid", Value: "secret"}}} diff --git a/internal/runtime/devices.go b/internal/runtime/devices.go index bf245ea..43c6310 100644 --- a/internal/runtime/devices.go +++ b/internal/runtime/devices.go @@ -4,29 +4,81 @@ import ( "context" "errors" "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" ) -func (c *Runtime) controller(ctx context.Context) (*sdpc.Client, error) { - if e := c.prepare(ctx); e != nil { - return nil, e +var ErrNoSession = errors.New("no active controller session") + +func (c *Runtime) prepareDevices(ctx context.Context) error { + if err := c.prepare(ctx); err != nil { + return err + } + _, err := c.provider.Credential(ctx) + return err +} + +// deviceOperation binds a controller request to the current session and lifetime. +func (c *Runtime) deviceOperation(parent context.Context, fn func(context.Context, *sdpc.Client) error) (*session.Credential, error) { + ctx, done := c.operation(parent) + defer done() + if err := ctx.Err(); err != nil { + return nil, err } - if _, e := c.provider.Credential(ctx); e != nil { - return nil, e + cred, sc := c.provider.ActiveSession() + if cred == nil || sc == nil { + return nil, ErrNoSession } - sc := c.provider.ActiveSDPC() - if sc == nil { - return nil, errors.New("no active controller session") + ctx, releaseSession := bindSession(ctx, cred) + defer releaseSession() + err := fn(ctx, sc) + if c.provider.Current() != cred { + return nil, session.ErrSessionReplaced } - return sc, nil + return cred, err } + +// These controller DTO methods are internal panel hooks; they require an active session. +func (c *Runtime) QueryTrustDevice(parent context.Context) (*sdpc.TrustDeviceList, error) { + var list *sdpc.TrustDeviceList + _, err := c.deviceOperation(parent, func(ctx context.Context, sc *sdpc.Client) error { + var err error + list, err = sc.QueryTrustDevice(ctx) + return err + }) + return list, err +} +func (c *Runtime) TrustDevice(parent context.Context) error { + _, err := c.deviceOperation(parent, func(ctx context.Context, sc *sdpc.Client) error { return sc.TrustDevice(ctx) }) + return err +} +func (c *Runtime) UntrustDevice(parent context.Context, ids []string) error { + _, err := c.deviceOperation(parent, func(ctx context.Context, sc *sdpc.Client) error { return sc.UntrustDevice(ctx, ids) }) + return err +} +func (c *Runtime) LogoutTrustDevice(parent context.Context, id string) error { + self := "" + cred, err := c.deviceOperation(parent, func(ctx context.Context, sc *sdpc.Client) error { + list, err := sc.QueryTrustDevice(ctx) + if err != nil { + return err + } + self = list.SelfID + return sc.LogoutDevice(ctx, id) + }) + if err == nil && id == self && c.provider.InvalidateIfCurrent(cred) { + c.resetConnections() + } + return err +} + func (c *Runtime) TrustedDevices(parent context.Context) (TrustedDeviceList, error) { ctx, done := c.operation(parent) defer done() - sc, e := c.controller(ctx) + e := c.prepareDevices(ctx) if e != nil { return TrustedDeviceList{}, e } - v, e := sc.QueryTrustDevice(ctx) + v, e := c.QueryTrustDevice(ctx) if e != nil { return TrustedDeviceList{}, e } @@ -39,38 +91,26 @@ func (c *Runtime) TrustedDevices(parent context.Context) (TrustedDeviceList, err func (c *Runtime) TrustCurrentDevice(parent context.Context) error { ctx, done := c.operation(parent) defer done() - sc, e := c.controller(ctx) + e := c.prepareDevices(ctx) if e != nil { return e } - return sc.TrustDevice(ctx) + return c.TrustDevice(ctx) } func (c *Runtime) UntrustDevices(parent context.Context, ids []string) error { ctx, done := c.operation(parent) defer done() - sc, e := c.controller(ctx) + e := c.prepareDevices(ctx) if e != nil { return e } - return sc.UntrustDevice(ctx, ids) + return c.UntrustDevice(ctx, ids) } func (c *Runtime) LogoutDevice(parent context.Context, id string) error { ctx, done := c.operation(parent) defer done() - list, e := c.TrustedDevices(ctx) - if e != nil { - return e - } - sc, e := c.controller(ctx) - if e != nil { - return e - } - if e = sc.LogoutDevice(ctx, id); e != nil { - return e - } - if id == list.CurrentDeviceID { - c.provider.Invalidate() - c.resetConnections() + if err := c.prepareDevices(ctx); err != nil { + return err } - return nil + return c.LogoutTrustDevice(ctx, id) } diff --git a/internal/runtime/legacy_test.go b/internal/runtime/legacy_test.go deleted file mode 100644 index ffa1e60..0000000 --- a/internal/runtime/legacy_test.go +++ /dev/null @@ -1,141 +0,0 @@ -package runtime - -// These adapters migrate old regression fixtures to the new API; no legacy engine is used. -import ( - "context" - "crypto/tls" - "encoding/json" - "github.com/ShanghaitechGeekPie/geektrust/auth" - "github.com/ShanghaitechGeekPie/geektrust/deployment" - "github.com/ShanghaitechGeekPie/geektrust/internal/settings" - "log/slog" - "net" - "net/http" - "net/netip" -) - -type BlobStore interface { - Load(context.Context) ([]byte, error) - Save(context.Context, []byte) error -} -type AuthenticatorFunc func(context.Context, *http.Client) (string, error) - -func (f AuthenticatorFunc) Authenticate(c context.Context, h *http.Client) (string, error) { - return f(c, h) -} - -type legacyIdentity struct{ f AuthenticatorFunc } - -func (l legacyIdentity) Info(context.Context) (auth.IdentityInfo, error) { - return auth.IdentityInfo{Issuer: "fixture", Subject: "fixture", Kind: "fixture"}, nil -} -func (l legacyIdentity) Authenticate(c context.Context, h *http.Client, _ auth.IdentityRequest) error { - if l.f == nil { - return nil - } - _, e := l.f(c, h) - return e -} - -type legacyOptions struct { - CheckTarget func(netip.Addr) error - Compatibility settings.Compatibility - Gateways, DNS []string - ControllerURL, DeviceID, Platform, LoginDomain string - ClientMode bool - Authenticator AuthenticatorFunc - ChallengeHandler auth.Handler - SessionStore BlobStore - Transport http.RoundTripper - DialContext func(context.Context, string, string) (net.Conn, error) - DisableSystemResolver bool - GatewayTLSConfig *tls.Config - GatewayTrustStore interface { - LoadPin(context.Context, string) ([]byte, error) - SavePin(context.Context, string, []byte) error - } - Logger *slog.Logger -} -type fixtureSession struct{ old BlobStore } - -func (f fixtureSession) Load(ctx context.Context, s SessionScope) ([]byte, error) { - b, e := f.old.Load(ctx) - if e != nil || len(b) == 0 { - return b, e - } - var v map[string]any - if e = json.Unmarshal(b, &v); e != nil { - return nil, e - } - v["version"] = 1 - v["controller_url"] = s.ControllerURL - v["identity_issuer"] = s.IdentityIssuer - v["identity_subject"] = s.IdentitySubject - v["identity_kind"] = s.IdentityKind - v["login_domain"] = s.LoginDomain - return json.Marshal(v) -} -func (f fixtureSession) Save(c context.Context, _ SessionScope, b []byte) error { - return f.old.Save(c, b) -} -func (f fixtureSession) Delete(context.Context, SessionScope) error { return nil } - -type legacyPins struct { - old interface { - LoadPin(context.Context, string) ([]byte, error) - SavePin(context.Context, string, []byte) error - } -} - -func (p legacyPins) CheckOrEnroll(c context.Context, i GatewayIdentity, b [32]byte) (bool, error) { - v, e := p.old.LoadPin(c, i.Address) - if e != nil { - return false, e - } - if len(v) == 0 { - return true, p.old.SavePin(c, i.Address, b[:]) - } - return string(v) == string(b[:]), nil -} -func newLegacy(o legacyOptions) (*Runtime, error) { - opts := Options{ControllerURL: o.ControllerURL, DeviceID: o.DeviceID, Logger: o.Logger, Auth: AuthOptions{Identity: legacyIdentity{o.Authenticator}, LoginDomain: o.LoginDomain, OnChallenge: o.ChallengeHandler}, Deployment: deployment.Options{Profile: deployment.Generic, Protocol: deployment.ProtocolOptions{ControllerPlatform: o.Platform}, Fallbacks: &deployment.Fallbacks{ApplicationID: o.Compatibility.FallbackAppID, Gateways: append([]string(nil), o.Compatibility.FallbackGateways...), MissingGatewayGroup: o.Compatibility.MissingGatewayGroupFallback, StreamToL3: o.Compatibility.TCPToL3Fallback}}, Network: NetworkOptions{ControlTransport: o.Transport, DialContext: o.DialContext, GatewayTLS: GatewayTLSOptions{Config: o.GatewayTLSConfig}}} - if o.ClientMode { - opts.Auth.Mode = DesktopMode - } - if o.SessionStore != nil { - opts.SessionStore = fixtureSession{o.SessionStore} - } - if o.GatewayTrustStore != nil { - opts.Network.GatewayTLS.Mode = VerifyCAOrTOFU - opts.Network.GatewayTLS.PinStore = legacyPins{o.GatewayTrustStore} - } - if o.Compatibility.GatewayServerName != "" { - if opts.Network.GatewayTLS.Config == nil { - opts.Network.GatewayTLS.Config = &tls.Config{} - } else { - opts.Network.GatewayTLS.Config = opts.Network.GatewayTLS.Config.Clone() - } - opts.Network.GatewayTLS.Config.ServerName = o.Compatibility.GatewayServerName - } - if o.CheckTarget != nil { - opts.CheckTarget = func(_ context.Context, t Target) error { return o.CheckTarget(t.IP) } - } - if p := o.Compatibility.ProcessIdentity; p != nil { - opts.Deployment.Protocol.Process = &deployment.ProcessMetadata{Name: p.Name, Platform: p.Platform, Path: p.Path} - } - for _, s := range o.DNS { - a, e := netip.ParseAddr(s) - if e != nil { - return nil, e - } - opts.DNS.Servers = append(opts.DNS.Servers, a) - } - if len(o.Gateways) > 0 { - opts.Deployment.Fallbacks.Gateways = append([]string(nil), o.Gateways...) - } - c, e := New(opts) - if e == nil { - - } - return c, e -} diff --git a/internal/runtime/lookup_lifetime_regression_test.go b/internal/runtime/lookup_lifetime_regression_test.go new file mode 100644 index 0000000..e9f6df9 --- /dev/null +++ b/internal/runtime/lookup_lifetime_regression_test.go @@ -0,0 +1,53 @@ +package runtime + +import ( + "context" + "errors" + "github.com/ShanghaitechGeekPie/geektrust/internal/session" + "net/netip" + "testing" + "time" +) + +func TestLookupCancelsWhenItsSessionIsInvalidated(t *testing.T) { + entered := make(chan struct{}) + opts := contractOptions(&contractIdentity{subject: "account"}, &contractStore{state: validState()}) + opts.DNS.Servers = []netip.Addr{} + opts.DNS.FallbackLookup = func(ctx context.Context, _ string) ([]netip.Addr, error) { + close(entered) + <-ctx.Done() + return nil, ctx.Err() + } + c, err := New(opts) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if _, err := c.Connect(context.Background()); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + result := make(chan error, 1) + go func() { _, err := c.LookupContextHost(ctx, "lookup.example.invalid"); result <- err }() + <-entered + c.provider.Invalidate() + select { + case err := <-result: + if !errors.Is(err, session.ErrSessionReplaced) { + t.Fatalf("lookup after invalidation = %v", err) + } + case <-time.After(time.Second): + t.Fatal("a lookup from the invalidated session remained active") + } +} + +func TestNewRejectsControllerEmptyQueryMarker(t *testing.T) { + options := contractOptions(&contractIdentity{subject: "account"}, &contractStore{state: validState()}) + options.ControllerURL = "https://controller.example?" + c, err := New(options) + if err == nil { + c.Close() + t.Fatal("controller URL ending in a query marker was accepted") + } +} diff --git a/internal/runtime/options.go b/internal/runtime/options.go index 9d9a9a1..9d4e4bc 100644 --- a/internal/runtime/options.go +++ b/internal/runtime/options.go @@ -10,13 +10,13 @@ import ( "time" "github.com/ShanghaitechGeekPie/geektrust/auth" - "github.com/ShanghaitechGeekPie/geektrust/deployment" + "github.com/ShanghaitechGeekPie/geektrust/compatibility" ) type Options struct { ControllerURL string DeviceID string - Deployment deployment.Options + Compatibility compatibility.Options Auth AuthOptions SessionStore SessionStore Network NetworkOptions diff --git a/internal/runtime/options_test.go b/internal/runtime/options_test.go new file mode 100644 index 0000000..96263aa --- /dev/null +++ b/internal/runtime/options_test.go @@ -0,0 +1,121 @@ +package runtime + +import ( + "context" + "crypto/tls" + "errors" + "github.com/ShanghaitechGeekPie/geektrust/auth" + "github.com/ShanghaitechGeekPie/geektrust/compatibility" + "io" + "net/http" + "net/netip" + "strings" + "testing" + "time" +) + +type controllerTransport func(*http.Request) (*http.Response, error) + +func (f controllerTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +type fixtureTransport struct{} + +func (fixtureTransport) RoundTrip(r *http.Request) (*http.Response, error) { + body := `{"code":0,"data":{}}` + switch r.URL.Path { + case "/passport/v1/user/onlineInfo": + body = `{"code":0,"data":{"isOnline":true}}` + case "/controller/v1/user/clientResource": + default: + return nil, errors.New("unexpected controller request") + } + return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}, nil +} + +type identityFunc func(context.Context, *http.Client, auth.IdentityRequest) error + +func (f identityFunc) Info(context.Context) (auth.IdentityInfo, error) { + return auth.IdentityInfo{Issuer: "fixture", Subject: "account", Kind: "passkey"}, nil +} +func (f identityFunc) Authenticate(c context.Context, h *http.Client, r auth.IdentityRequest) error { + return f(c, h, r) +} +func TestOptionsCopiedAndProfileDefaults(t *testing.T) { + s := validState() + s.LoginDomain = "custom-domain" + o := contractOptions(&contractIdentity{subject: "account"}, &contractStore{state: s}) + o.Auth.LoginDomain = "custom-domain" + o.Compatibility.Fallbacks.ApplicationID = "custom-app" + o.Compatibility.Fallbacks.Gateways = []string{"configured.example:441"} + o.DNS.Servers = []netip.Addr{netip.MustParseAddr("10.0.0.53")} + template := &tls.Config{ServerName: "gateway.example"} + o.Network.GatewayTLS.Config = template + c, e := New(o) + if e != nil { + t.Fatal(e) + } + defer c.Close() + o.Compatibility.Fallbacks.Gateways[0] = "mutated.example:441" + template.ServerName = "mutated" + info, e := c.Connect(context.Background()) + if e != nil { + t.Fatal(e) + } + if info.Gateways[0] != "configured.example:441" || info.DNS[0] != "10.0.0.53" { + t.Fatal("caller mutated active routing") + } + target, e := c.resolver.Resolve(context.Background(), "192.0.2.1", 443) + if e != nil || target.AppID != "custom-app" { + t.Fatal("application fallback lost") + } + _, sc := c.provider.ActiveSession() + if c.manager.GatewayTLSConfig.ServerName != "gateway.example" || sc.LoginDomain != "custom-domain" { + t.Fatal("TLS/login settings lost") + } +} +func TestAuthenticationUsesCallerDeadline(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + want, _ := ctx.Deadline() + called := false + o := contractOptions(&contractIdentity{subject: "account"}, &contractStore{}) + o.SessionStore = nil + o.Auth.Identity = identityFunc(func(ctx context.Context, _ *http.Client, r auth.IdentityRequest) error { + called = true + got, _ := ctx.Deadline() + if got != want || !r.AllowInteraction { + t.Error("caller authentication context changed") + } + return errors.New("fixture stop") + }) + c, e := New(o) + if e != nil { + t.Fatal(e) + } + defer c.Close() + if _, e = c.Connect(ctx); e == nil || !called { + t.Fatal("real authentication was not called") + } +} +func TestCacheCannotRestoreRemovedFallbacks(t *testing.T) { + for _, enabled := range []bool{true, false} { + state := validState() + state.Gateways = []string{"stale.example:441"} + o := contractOptions(&contractIdentity{subject: "account"}, &contractStore{state: state}) + if !enabled { + o.Compatibility.Fallbacks = &compatibility.Fallbacks{} + } + c, e := New(o) + if e != nil { + t.Fatal(e) + } + _, e = c.Connect(context.Background()) + if enabled && e != nil { + t.Fatal(e) + } + if !enabled && e == nil { + t.Fatal("cache revived a removed gateway fallback") + } + c.Close() + } +} diff --git a/internal/runtime/packet.go b/internal/runtime/packet.go index 9d3682b..07fe440 100644 --- a/internal/runtime/packet.go +++ b/internal/runtime/packet.go @@ -10,17 +10,23 @@ func (c *Runtime) ExchangeICMPEcho(parent context.Context, packet []byte) ([]byt if c.isClosed() { return nil, ErrClosed } + if len(packet) < 20 || packet[0]>>4 != 4 { + return nil, errors.New("invalid IPv4 packet") + } ctx, done := c.operation(parent) defer done() if e := c.prepare(ctx); e != nil { return nil, e } + cred, err := c.provider.Credential(ctx) + if err != nil { + return nil, err + } + ctx, releaseSession := bindSession(ctx, cred) + defer releaseSession() if c.checkTarget != nil { - if len(packet) < 20 || packet[0]>>4 != 4 { - return nil, errors.New("invalid IPv4 packet") - } ip := netip.AddrFrom4([4]byte(packet[16:20])) - if err := c.checkTarget(ctx, Target{Generation: c.currentGeneration(), Network: "icmp", IP: ip}); err != nil { + if err := c.checkTarget(ctx, Target{Generation: cred.Generation, Network: "icmp", IP: ip}); err != nil { return nil, err } } diff --git a/internal/runtime/review_regression_test.go b/internal/runtime/review_regression_test.go new file mode 100644 index 0000000..4f6298a --- /dev/null +++ b/internal/runtime/review_regression_test.go @@ -0,0 +1,363 @@ +package runtime + +import ( + "context" + "errors" + "io" + "net" + "net/http" + "strings" + "sync" + "testing" + "time" + + "github.com/ShanghaitechGeekPie/geektrust/internal/session" +) + +func reviewClient(t *testing.T) *Runtime { + t.Helper() + c, err := New(contractOptions(&contractIdentity{subject: "account"}, &contractStore{state: validState()})) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { c.Close() }) + return c +} +func TestConnectResultDoesNotOwnStatusMemory(t *testing.T) { + c := reviewClient(t) + info, err := c.Connect(context.Background()) + if err != nil { + t.Fatal(err) + } + original := info.Gateways[0] + info.Gateways[0] = "caller mutation" + if c.Status().Session.Gateways[0] != original { + t.Fatal("caller mutated the runtime snapshot") + } +} +func receiveReady(t *testing.T, ch <-chan Event) Event { + t.Helper() + timer := time.NewTimer(time.Second) + defer timer.Stop() + for { + select { + case e := <-ch: + if e.Status.State == Ready { + return e + } + case <-timer.C: + t.Fatal("ready event missing") + } + } +} +func TestSubscriberSnapshotsAreIndependent(t *testing.T) { + c := reviewClient(t) + a := c.Subscribe(context.Background()) + b := c.Subscribe(context.Background()) + <-a + <-b + if _, err := c.Connect(context.Background()); err != nil { + t.Fatal(err) + } + first, second := receiveReady(t, a), receiveReady(t, b) + expected := second.Status.Session.Gateways[0] + first.Status.Session.Gateways[0] = "one subscriber" + if second.Status.Session.Gateways[0] != expected { + t.Fatal("subscribers shared mutable snapshot memory") + } +} +func TestLateSuccessDoesNotResurrectInvalidatedStatus(t *testing.T) { + c := reviewClient(t) + if _, err := c.Connect(context.Background()); err != nil { + t.Fatal(err) + } + old := c.provider.Current() + c.provider.Invalidate() + o := clientObserver{c} + o.OnSessionEvent(session.Event{Kind: session.EventInvalidated}) + o.OnSessionEvent(session.Event{Kind: session.EventLoginSuccess, Session: &session.SessionInfo{Generation: old.Generation, Username: old.Username}}) + if c.Status().State == Ready { + t.Fatal("queued success resurrected an invalidated session") + } +} +func TestDisjointGatewayFilterFailsConnect(t *testing.T) { + opts := contractOptions(&contractIdentity{subject: "account"}, &contractStore{state: validState()}) + opts.Network.AllowedGateways = []string{"excluded.example:441"} + c, err := New(opts) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if _, err = c.Connect(context.Background()); err == nil { + t.Fatal("connect accepted a filter with no usable gateway") + } +} + +func TestInvalidationClosesBlockedConnection(t *testing.T) { + c := reviewClient(t) + if _, err := c.Connect(context.Background()); err != nil { + t.Fatal(err) + } + left, right := net.Pipe() + defer right.Close() + conn, err := c.ownConnection(c.provider.Current(), left, false) + if err != nil { + t.Fatal(err) + } + reading := make(chan error, 1) + go func() { _, err := conn.Read(make([]byte, 1)); reading <- err }() + c.provider.Invalidate() + select { + case err := <-reading: + if err == nil { + t.Fatal("invalidated read succeeded") + } + case <-time.After(time.Second): + t.Fatal("old session left a blocked connection open") + } +} + +func TestIdentityWaitHonorsCancellation(t *testing.T) { + i := blockingIdentity{make(chan struct{}), make(chan struct{})} + o := contractOptions(&contractIdentity{subject: "account"}, &contractStore{state: validState()}) + o.Auth.Identity = i + c, err := New(o) + if err != nil { + t.Fatal(err) + } + defer c.Close() + first := make(chan error, 1) + go func() { _, err := c.Connect(context.Background()); first <- err }() + <-i.entered + ctx, cancel := context.WithCancel(context.Background()) + cancel() + second := make(chan error, 1) + go func() { _, err := c.Connect(ctx); second <- err }() + select { + case err := <-second: + if !errors.Is(err, context.Canceled) { + t.Fatalf("second caller = %v", err) + } + case <-time.After(time.Second): + close(i.release) + <-first + t.Fatal("cancelled caller waited for another identity operation") + } + close(i.release) + if err := <-first; err != nil { + t.Fatal(err) + } +} + +type blockingSaveStore struct { + contractStore + entered, release, deleted chan struct{} + mu sync.Mutex + present bool +} + +func (s *blockingSaveStore) Save(context.Context, SessionScope, []byte) error { + close(s.entered) + <-s.release + s.mu.Lock() + s.present = true + s.mu.Unlock() + return nil +} +func (s *blockingSaveStore) Delete(context.Context, SessionScope) error { + s.mu.Lock() + s.present = false + s.mu.Unlock() + close(s.deleted) + return nil +} +func TestForgetOrdersDeletionAfterInFlightSave(t *testing.T) { + s := &blockingSaveStore{contractStore: contractStore{state: validState()}, entered: make(chan struct{}), release: make(chan struct{}), deleted: make(chan struct{})} + o := contractOptions(&contractIdentity{subject: "account"}, nil) + o.SessionStore = s + c, err := New(o) + if err != nil { + t.Fatal(err) + } + defer c.Close() + connecting := make(chan error, 1) + go func() { _, err := c.Connect(context.Background()); connecting <- err }() + <-s.entered + forgetting := make(chan error, 1) + go func() { forgetting <- c.ForgetSession(context.Background()) }() + select { + case <-s.deleted: + close(s.release) + <-connecting + <-forgetting + t.Fatal("session was deleted before its pending save completed") + case <-time.After(30 * time.Millisecond): + } + close(s.release) + <-connecting // either publication won the race or it was rejected + if err := <-forgetting; err != nil { + t.Fatal(err) + } + s.mu.Lock() + present := s.present + s.mu.Unlock() + if present || c.provider.Current() != nil { + t.Fatal("forgotten session survived") + } +} + +func TestCancelledForgetPreservesCurrentSession(t *testing.T) { + c := reviewClient(t) + if _, err := c.Connect(context.Background()); err != nil { + t.Fatal(err) + } + current := c.provider.Current() + ctx, cancel := context.WithCancel(context.Background()) + cancel() + // Ready gates and a canceled context must never select a destructive path. + for range 64 { + if err := c.ForgetSession(ctx); !errors.Is(err, context.Canceled) { + t.Fatalf("canceled forget = %v", err) + } + if c.provider.Current() != current { + t.Fatal("already canceled forget invalidated the active session") + } + } +} + +type slowCloseConn struct { + net.Conn + entered chan struct{} + release chan struct{} + once sync.Once +} + +func (c *slowCloseConn) Close() error { + c.once.Do(func() { close(c.entered); <-c.release }) + return c.Conn.Close() +} + +func TestShutdownDeadlineBoundsConnectionClose(t *testing.T) { + c := reviewClient(t) + if _, err := c.Connect(context.Background()); err != nil { + t.Fatal(err) + } + left, right := net.Pipe() + defer right.Close() + raw := &slowCloseConn{Conn: left, entered: make(chan struct{}), release: make(chan struct{})} + if _, err := c.ownConnection(c.provider.Current(), raw, false); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + result := make(chan error, 1) + go func() { result <- c.Shutdown(ctx) }() + <-raw.entered + select { + case err := <-result: + if !errors.Is(err, context.DeadlineExceeded) { + t.Errorf("shutdown = %v", err) + } + case <-time.After(200 * time.Millisecond): + t.Error("shutdown deadline did not bound connection close") + } + close(raw.release) + if err := c.Shutdown(context.Background()); err != nil { + t.Fatal(err) + } +} + +func TestControllerRequestIsCancelledBySessionInvalidation(t *testing.T) { + entered := make(chan struct{}) + o := contractOptions(&contractIdentity{subject: "account"}, &contractStore{state: validState()}) + o.Network.ControlTransport = controllerTransport(func(r *http.Request) (*http.Response, error) { + if r.URL.Path == "/passport/v1/security/queryDevice" { + close(entered) + <-r.Context().Done() + return nil, r.Context().Err() + } + return (fixtureTransport{}).RoundTrip(r) + }) + c, err := New(o) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if _, err := c.Connect(context.Background()); err != nil { + t.Fatal(err) + } + result := make(chan error, 1) + go func() { _, err := c.QueryTrustDevice(context.Background()); result <- err }() + <-entered + c.provider.Invalidate() + select { + case err := <-result: + if !errors.Is(err, session.ErrSessionReplaced) { + t.Fatalf("request = %v", err) + } + case <-time.After(time.Second): + t.Fatal("old controller request remained active") + } +} + +func TestLogoutCurrentDeviceInvalidatesSessionAndConnections(t *testing.T) { + o := contractOptions(&contractIdentity{subject: "account"}, &contractStore{state: validState()}) + o.Network.ControlTransport = controllerTransport(func(r *http.Request) (*http.Response, error) { + if r.URL.Path == "/passport/v1/security/queryDevice" || r.URL.Path == "/passport/v1/security/logoutDevice" { + return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"code":0,"data":{"selfId":"current-device"}}`))}, nil + } + return (fixtureTransport{}).RoundTrip(r) + }) + c, err := New(o) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if _, err := c.Connect(context.Background()); err != nil { + t.Fatal(err) + } + left, right := net.Pipe() + defer right.Close() + conn, err := c.ownConnection(c.provider.Current(), left, false) + if err != nil { + t.Fatal(err) + } + read := make(chan error, 1) + go func() { _, err := conn.Read(make([]byte, 1)); read <- err }() + if err := c.LogoutTrustDevice(context.Background(), "current-device"); err != nil { + t.Fatal(err) + } + if c.provider.Current() != nil { + t.Fatal("self logout left current credentials active") + } + select { + case <-read: + case <-time.After(time.Second): + t.Fatal("self logout left a blocked connection open") + } +} + +func TestSessionEventsIncludeCurrentResources(t *testing.T) { + o := contractOptions(&contractIdentity{subject: "account"}, &contractStore{state: validState()}) + o.Network.ControlTransport = controllerTransport(func(r *http.Request) (*http.Response, error) { + if r.URL.Path == "/controller/v1/user/clientResource" { + return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"code":0,"data":{"appList":{"data":{"appInfo":[{"apps":[{"id":"resource-app","addressList":[{"host":"192.0.2.1","port":"443","protocol":"tcp"}]}]}]}}}}`))}, nil + } + return (fixtureTransport{}).RoundTrip(r) + }) + c, err := New(o) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if err := c.prepare(context.Background()); err != nil { + t.Fatal(err) + } + if _, err := c.provider.Credential(context.Background()); err != nil { + t.Fatal(err) + } + event := receiveReady(t, c.Subscribe(context.Background())) + if event.Status.Session == nil || len(event.Status.Session.Resources) != 1 || event.Status.Session.Resources[0].Address != "192.0.2.1" { + t.Fatalf("session event omitted policy resources: %+v", event.Status.Session) + } +} diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index 1d03c8f..22be0ba 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -19,8 +19,8 @@ import ( "time" "github.com/ShanghaitechGeekPie/geektrust/auth" - "github.com/ShanghaitechGeekPie/geektrust/deployment" - defaults "github.com/ShanghaitechGeekPie/geektrust/internal/deployment" + "github.com/ShanghaitechGeekPie/geektrust/compatibility" + defaults "github.com/ShanghaitechGeekPie/geektrust/internal/compatibility" "github.com/ShanghaitechGeekPie/geektrust/internal/settings" "github.com/ShanghaitechGeekPie/geektrust/internal/l3" @@ -71,14 +71,12 @@ type Runtime struct { subscribers map[uint64]chan Event nextSubscriber uint64 status Status - store SessionStore - generation uint64 + cache *stateStore identity auth.IdentityProvider scope SessionScope - identityMu sync.Mutex + identityGate chan struct{} identityReady bool - mode SessionMode - profile deployment.Profile + profile compatibility.Profile dialTimeout time.Duration startOnce sync.Once tasksDone chan struct{} @@ -87,7 +85,7 @@ type Runtime struct { func New(opts Options) (*Runtime, error) { u, err := url.Parse(opts.ControllerURL) - if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") { + if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.ForceQuery || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") { return nil, errors.New("controller must be an HTTPS origin") } if len(opts.DeviceID) != 32 || strings.Trim(opts.DeviceID, "0123456789ABCDEF") != "" { @@ -102,7 +100,7 @@ func New(opts Options) (*Runtime, error) { if opts.Network.DialTimeout < 0 || opts.Network.HTTPTimeout < 0 { return nil, errors.New("invalid network timeout") } - if err := opts.Deployment.Validate(); err != nil { + if err := opts.Compatibility.Validate(); err != nil { return nil, err } if opts.Network.GatewayTLS.Mode != VerifyCA && opts.Network.GatewayTLS.Mode != VerifyCAOrTOFU { @@ -117,7 +115,7 @@ func New(opts Options) (*Runtime, error) { if opts.Logger == nil { opts.Logger = slog.New(slog.NewTextHandler(io.Discard, nil)) } - resolved := defaults.Resolve(opts.ControllerURL, opts.Deployment) + resolved := defaults.Resolve(opts.ControllerURL, opts.Compatibility) mode := "browser" if opts.Auth.Mode == DesktopMode { mode = "client" @@ -131,7 +129,7 @@ func New(opts Options) (*Runtime, error) { } u.Path = "" u.RawPath = "" - cfg := settings.Session{BaseURL: u.String(), DeviceID: opts.DeviceID, Platform: resolved.Platform, LoginDomain: opts.Auth.LoginDomain, ClientType: mode, Compatibility: resolved.Compatibility, StrictStorage: true, GatewayFilter: opts.Network.AllowedGateways != nil} + cfg := settings.Session{BaseURL: u.String(), DeviceID: opts.DeviceID, Platform: resolved.Platform, LoginDomain: opts.Auth.LoginDomain, ClientType: mode, Fallbacks: resolved.Fallbacks, Process: resolved.Process, GatewayFilter: opts.Network.AllowedGateways != nil} if cfg.LoginDomain == "" { cfg.LoginDomain = resolved.LoginDomain } @@ -155,7 +153,7 @@ func New(opts Options) (*Runtime, error) { cfg.DNS[i] = x.String() } } - mapDomains := resolved.Profile == deployment.ShanghaiTech + mapDomains := resolved.Profile == compatibility.ShanghaiTech cfg.DomainMapping = &mapDomains p := session.NewProvider(cfg, opts.Logger, nil) p.ChallengeHandler = opts.Auth.OnChallenge @@ -178,7 +176,7 @@ func New(opts Options) (*Runtime, error) { m.GatewayTLSConfig.RootCAs = t.RootCAs.Clone() } } - if name := resolved.Compatibility.GatewayServerName; name != "" { + if name := resolved.GatewayServerName; name != "" { if m.GatewayTLSConfig == nil { m.GatewayTLSConfig = &tls.Config{ServerName: name} } else if m.GatewayTLSConfig.ServerName == "" { @@ -186,11 +184,11 @@ func New(opts Options) (*Runtime, error) { } } if opts.Network.GatewayTLS.PinStore != nil { - m.GatewayTrustStore = pinAdapter{store: opts.Network.GatewayTLS.PinStore, controller: cfg.BaseURL, template: m.GatewayTLSConfig} + m.GatewayTrustStore = pinAdapter{store: opts.Network.GatewayTLS.PinStore, controller: cfg.BaseURL} } d := &l3.Dialer{Manager: m, Provider: p, Logger: opts.Logger} ctx, cancel := context.WithCancel(context.Background()) - c := &Runtime{checkTarget: opts.CheckTarget, provider: p, manager: m, dialer: d, transport: owned, ctx: ctx, cancel: cancel, conns: make(map[*ownedConn]struct{}), store: opts.SessionStore, status: Status{State: Idle}, identity: opts.Auth.Identity, mode: opts.Auth.Mode, profile: resolved.Profile, dialTimeout: opts.Network.DialTimeout, subscribers: make(map[uint64]chan Event), tasksDone: make(chan struct{}), shutdownDone: make(chan struct{})} + c := &Runtime{checkTarget: opts.CheckTarget, provider: p, manager: m, dialer: d, transport: owned, ctx: ctx, cancel: cancel, conns: make(map[*ownedConn]struct{}), status: Status{State: Idle}, identity: opts.Auth.Identity, identityGate: make(chan struct{}, 1), profile: resolved.Profile, dialTimeout: opts.Network.DialTimeout, subscribers: make(map[uint64]chan Event), tasksDone: make(chan struct{}), shutdownDone: make(chan struct{})} p.Authenticate = func(ctx context.Context, h *http.Client) (string, error) { if e := c.prepare(ctx); e != nil { return "", e @@ -202,7 +200,8 @@ func New(opts Options) (*Runtime, error) { } c.resolver = resolver.NewController(p, checkedDNSDialer{c}, opts.DNS.FallbackLookup, opts.DNS.Servers != nil && len(opts.DNS.Servers) == 0) c.scope = SessionScope{ControllerURL: cfg.BaseURL, DeviceID: cfg.DeviceID, Mode: opts.Auth.Mode, LoginDomain: cfg.LoginDomain} - p.SetStore(&stateStore{store: opts.SessionStore, client: c}) + c.cache = &stateStore{store: opts.SessionStore, client: c, gate: make(chan struct{}, 1)} + p.SetStore(c.cache) return c, nil } func NewDeviceID() (string, error) { @@ -269,29 +268,15 @@ func (c *Runtime) Connect(parent context.Context) (SessionInfo, error) { if c.closed { return SessionInfo{}, ErrClosed } - c.start() - c.generation = cred.Generation - info := SessionInfo{Gateways: append([]string(nil), cred.Gateways...), DNS: append([]string(nil), cred.DNS...), Generation: c.generation, Username: cred.Username, DisplayName: cred.DisplayName} - for _, r := range cred.Policy.IPRules { - address := "" - switch { - case r.IP != nil: - address = r.IP.String() - case r.Net != nil: - address = r.Net.String() - case r.IPMin != nil: - address = r.IPMin.String() + "-" + r.IPMax.String() - } - info.Resources = append(info.Resources, Resource{Address: address, Protocol: r.Proto, ApplicationID: r.AppID, GatewayGroup: cred.Policy.AppNodeGroups[r.AppID], PortMin: r.Port.Min, PortMax: r.Port.Max}) - } - for _, r := range cred.Policy.DomainRules { - info.Resources = append(info.Resources, Resource{Address: r.Domain, Protocol: r.Proto, ApplicationID: r.AppID, GatewayGroup: cred.Policy.AppNodeGroups[r.AppID], PortMin: r.Port.Min, PortMax: r.Port.Max}) - } - for _, r := range cred.Policy.SuffixRules { - info.Resources = append(info.Resources, Resource{Address: "*" + r.Suffix, Protocol: r.Proto, ApplicationID: r.AppID, GatewayGroup: cred.Policy.AppNodeGroups[r.AppID], PortMin: r.Port.Min, PortMax: r.Port.Max}) + if c.provider.Current() != cred { + return SessionInfo{}, session.ErrSessionReplaced } + c.start() + info := sessionInfo(cred) + c.status.Generation = cred.Generation c.status.State = Ready - c.status.Session = &info + snapshot := cloneSession(info) + c.status.Session = &snapshot c.status.LastError = nil c.publishLocked() return info, nil @@ -309,6 +294,12 @@ func (c *Runtime) OpenTransport(parent context.Context) (TransportInfo, error) { if err := c.prepare(ctx); err != nil { return TransportInfo{}, err } + cred, err := c.provider.Credential(ctx) + if err != nil { + return TransportInfo{}, err + } + ctx, releaseSession := bindSession(ctx, cred) + defer releaseSession() t, err := c.manager.Tunnel(ctx) if err != nil { return TransportInfo{}, err @@ -317,7 +308,13 @@ func (c *Runtime) OpenTransport(parent context.Context) (TransportInfo, error) { if ip == nil { return TransportInfo{}, errors.New("gateway did not assign an IPv4 virtual address") } - return TransportInfo{Generation: c.currentGeneration(), Gateway: t.Addr(), VirtualIPv4: ip.String()}, nil + if c.provider.Current() != cred { + return TransportInfo{}, session.ErrSessionReplaced + } + if err := ctx.Err(); err != nil { + return TransportInfo{}, err + } + return TransportInfo{Generation: cred.Generation, Gateway: t.Addr(), VirtualIPv4: ip.String()}, nil } func (c *Runtime) DialContext(parent context.Context, network, address string) (net.Conn, error) { @@ -355,16 +352,6 @@ func (c *Runtime) DialContext(parent context.Context, network, address string) ( return c.dialResolved(ctx, target, port, protocol) } -// RoutePlan is an immutable decision under one credential generation. -type RoutePlan struct { - Target resolver.Resolution - Port int - Network string - Gateways []string - GatewayGroup string - Credential *session.Credential -} - func (c *Runtime) dialResolved(ctx context.Context, target resolver.Resolution, port int, network string) (net.Conn, error) { cred, e := c.provider.Credential(ctx) if e != nil { @@ -373,12 +360,13 @@ func (c *Runtime) dialResolved(ctx context.Context, target resolver.Resolution, if target.Generation != 0 && target.Generation != cred.Generation { return nil, &Error{Info: ErrorInfo{Kind: ErrorSessionReplaced, Message: "session replaced during resolution"}} } - ctx = session.ExpectGeneration(ctx, cred.Generation) - plan := RoutePlan{Target: target, Port: port, Network: network, Credential: cred, Gateways: cred.GatewaysForApp(target.AppID), GatewayGroup: cred.GatewayGroupForApp(target.AppID)} + ctx, releaseSession := bindSession(ctx, cred) + defer releaseSession() + gateways := cred.GatewaysForApp(target.AppID) if target.AppID == "" { return nil, ErrDenied } - if len(plan.Gateways) == 0 { + if len(gateways) == 0 { return nil, tunnel.ErrNoLines } if c.checkTarget != nil { @@ -403,16 +391,29 @@ func (c *Runtime) dialResolved(ctx context.Context, target resolver.Resolution, conn.Close() return nil, &Error{Info: ErrorInfo{Kind: ErrorSessionReplaced, Message: "session replaced during dial"}} } + return c.ownConnection(cred, conn, network == "udp") +} +func (c *Runtime) ownConnection(cred *session.Credential, conn net.Conn, datagram bool) (net.Conn, error) { c.mu.Lock() defer c.mu.Unlock() if c.closed { conn.Close() return nil, ErrClosed } - owned := &ownedConn{Conn: conn, owner: c, credential: cred, datagram: network == "udp"} + if c.provider.Current() != cred { + conn.Close() + return nil, session.ErrSessionReplaced + } + owned := &ownedConn{Conn: conn, owner: c, credential: cred, datagram: datagram} c.conns[owned] = struct{}{} + if cred.Lifetime != nil { + owned.stopMu.Lock() + owned.stop = context.AfterFunc(cred.Lifetime, func() { owned.Close() }) + owned.stopMu.Unlock() + } return owned, nil } + func (c *Runtime) DialResolved(parent context.Context, t resolver.Resolution, p int, n string) (net.Conn, error) { ctx, done := c.operation(parent) defer done() @@ -437,7 +438,17 @@ func (c *Runtime) LookupContextHost(parent context.Context, host string) ([]stri if err := c.prepare(ctx); err != nil { return nil, err } - return c.resolver.LookupHost(ctx, host) + cred, err := c.provider.Credential(ctx) + if err != nil { + return nil, err + } + ctx, releaseSession := bindSession(ctx, cred) + defer releaseSession() + result, err := c.resolver.LookupHost(ctx, host) + if c.provider.Current() != cred { + return nil, session.ErrSessionReplaced + } + return result, err } func (c *Runtime) Close() error { c.mu.Lock() @@ -457,7 +468,6 @@ func (c *Runtime) Close() error { close(ch) delete(c.subscribers, id) } - c.status.State = Closed c.mu.Unlock() for _, conn := range conns { conn.Close() @@ -478,6 +488,8 @@ type ownedConn struct { credential *session.Credential owner *Runtime once sync.Once + stopMu sync.Mutex + stop func() bool err error } @@ -499,7 +511,17 @@ func (c *ownedConn) Write(b []byte) (int, error) { return c.Conn.Write(b) } func (c *ownedConn) Close() error { - c.once.Do(func() { c.err = c.Conn.Close(); c.owner.mu.Lock(); delete(c.owner.conns, c); c.owner.mu.Unlock() }) + c.once.Do(func() { + c.stopMu.Lock() + if c.stop != nil { + c.stop() + } + c.stopMu.Unlock() + c.err = c.Conn.Close() + c.owner.mu.Lock() + delete(c.owner.conns, c) + c.owner.mu.Unlock() + }) return c.err } func (c *ownedConn) CloseWrite() error { @@ -508,3 +530,33 @@ func (c *ownedConn) CloseWrite() error { } return errors.New("half-close unavailable") } + +func sessionInfo(cred *session.Credential) SessionInfo { + info := SessionInfo{Gateways: append([]string(nil), cred.Gateways...), DNS: append([]string(nil), cred.DNS...), Generation: cred.Generation, Username: cred.Username, DisplayName: cred.DisplayName} + for _, r := range cred.Policy.IPRules { + address := "" + switch { + case r.IP != nil: + address = r.IP.String() + case r.Net != nil: + address = r.Net.String() + case r.IPMin != nil: + address = r.IPMin.String() + "-" + r.IPMax.String() + } + info.Resources = append(info.Resources, Resource{Address: address, Protocol: r.Proto, ApplicationID: r.AppID, GatewayGroup: cred.Policy.AppNodeGroups[r.AppID], PortMin: r.Port.Min, PortMax: r.Port.Max}) + } + for _, r := range cred.Policy.DomainRules { + info.Resources = append(info.Resources, Resource{Address: r.Domain, Protocol: r.Proto, ApplicationID: r.AppID, GatewayGroup: cred.Policy.AppNodeGroups[r.AppID], PortMin: r.Port.Min, PortMax: r.Port.Max}) + } + for _, r := range cred.Policy.SuffixRules { + info.Resources = append(info.Resources, Resource{Address: "*" + r.Suffix, Protocol: r.Proto, ApplicationID: r.AppID, GatewayGroup: cred.Policy.AppNodeGroups[r.AppID], PortMin: r.Port.Min, PortMax: r.Port.Max}) + } + return info +} + +func bindSession(ctx context.Context, cred *session.Credential) (context.Context, func()) { + ctx = session.ExpectGeneration(ctx, cred.Generation) + ctx, cancel := context.WithCancel(ctx) + stop := context.AfterFunc(cred.Lifetime, cancel) + return ctx, func() { stop(); cancel() } +} diff --git a/internal/runtime/status.go b/internal/runtime/status.go index 8bf03ab..69d3a95 100644 --- a/internal/runtime/status.go +++ b/internal/runtime/status.go @@ -7,12 +7,10 @@ import ( "encoding/json" "errors" "github.com/ShanghaitechGeekPie/geektrust/auth" - "github.com/ShanghaitechGeekPie/geektrust/deployment" + "github.com/ShanghaitechGeekPie/geektrust/compatibility" "github.com/ShanghaitechGeekPie/geektrust/internal/resolver" "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" "github.com/ShanghaitechGeekPie/geektrust/internal/session" - "net" - "sync" "time" ) @@ -28,12 +26,12 @@ const ( ) type Status struct { - Revision uint64 - Generation uint64 - State SessionState - Deployment deployment.Profile - Session *SessionInfo - LastError *ErrorInfo + Revision uint64 + Generation uint64 + State SessionState + Compatibility compatibility.Profile + Session *SessionInfo + LastError *ErrorInfo } type ErrorKind string @@ -177,8 +175,12 @@ func (c *Runtime) prepare(ctx context.Context) error { if c.isClosed() { return ErrClosed } - c.identityMu.Lock() - defer c.identityMu.Unlock() + select { + case c.identityGate <- struct{}{}: + defer func() { <-c.identityGate }() + case <-ctx.Done(): + return ctx.Err() + } info, e := c.identity.Info(ctx) if e != nil { return e @@ -209,10 +211,7 @@ func (c *Runtime) start() { func (c *Runtime) Status() Status { c.mu.Lock(); defer c.mu.Unlock(); return cloneStatus(c.status) } func cloneStatus(s Status) Status { if s.Session != nil { - v := *s.Session - v.Gateways = append([]string(nil), v.Gateways...) - v.DNS = append([]string(nil), v.DNS...) - v.Resources = append([]Resource(nil), v.Resources...) + v := cloneSession(*s.Session) s.Session = &v } if s.LastError != nil { @@ -250,10 +249,10 @@ func (c *Runtime) Subscribe(ctx context.Context) <-chan Event { } func (c *Runtime) publishLocked() { c.status.Revision++ - c.status.Generation = c.generation - c.status.Deployment = c.profile - ev := Event{Time: time.Now(), Status: cloneStatus(c.status)} + c.status.Compatibility = c.profile + now := time.Now() for _, ch := range c.subscribers { + ev := Event{Time: now, Status: cloneStatus(c.status)} select { case ch <- ev: default: @@ -266,7 +265,9 @@ func (c *Runtime) publishLocked() { } } func (c *Runtime) Shutdown(ctx context.Context) error { - c.Close() + // Closing a socket can wait for a protocol close write. The caller's + // deadline bounds the wait while cleanup continues to completion. + go c.Close() select { case <-ctx.Done(): return ctx.Err() @@ -280,18 +281,28 @@ func (c *Runtime) ForgetSession(parent context.Context) error { if e := c.prepare(ctx); e != nil { return e } - c.provider.Invalidate() - c.resetConnections() + if err := c.cache.lock(ctx); err != nil { + return err + } + defer c.cache.unlock() c.mu.Lock() + if err := ctx.Err(); err != nil { + c.mu.Unlock() + return err + } c.forgotten = true c.mu.Unlock() - store := c.providerStore() - if store == nil { + c.provider.Invalidate() + c.resetConnections() + if c.cache.store == nil { return nil } - return store.Delete(ctx, c.scope) + if err := c.cache.store.Delete(ctx, c.scope); err != nil { + return &Error{Info: ErrorInfo{Kind: ErrorStorage, Op: "forget_session", Message: "session storage delete failed"}, cause: sanitizedCause{err}} + } + return nil } -func (c *Runtime) providerStore() SessionStore { return c.store } + func (c *Runtime) resetConnections() { c.mu.Lock() conns := make([]*ownedConn, 0, len(c.conns)) @@ -316,9 +327,14 @@ func (o clientObserver) OnSessionEvent(e session.Event) { return } current := c.provider.Current() - if current != nil && (e.Kind == session.EventLoginStart || e.Kind == session.EventLoginFailed || e.Kind == session.EventInvalidated) { + if current != nil && (e.Kind == session.EventLoginStart || e.Kind == session.EventLoginFailed || e.Kind == session.EventInteractionRequired || e.Kind == session.EventInvalidated) { return } + if e.Kind == session.EventLoginSuccess || e.Kind == session.EventRestoreOK { + if e.Session == nil || current == nil || e.Session.Generation != current.Generation { + return + } + } if e.Session != nil && current != nil && e.Session.Generation != current.Generation { return } @@ -330,14 +346,8 @@ func (o clientObserver) OnSessionEvent(e session.Event) { c.status.State = Authenticating case session.EventLoginSuccess, session.EventRestoreOK: c.status.State = Ready - c.generation = e.Session.Generation - v := SessionInfo{Generation: c.generation} - if e.Session != nil { - v.Username = e.Session.Username - v.DisplayName = e.Session.DisplayName - v.Gateways = append([]string(nil), e.Session.Gateways...) - v.DNS = append([]string(nil), e.Session.DNS...) - } + c.status.Generation = current.Generation + v := sessionInfo(current) c.status.Session = &v c.status.LastError = nil case session.EventInteractionRequired: @@ -349,6 +359,7 @@ func (o clientObserver) OnSessionEvent(e session.Event) { case session.EventInvalidated: c.status.State = Idle c.status.Session = nil + c.status.LastError = nil default: return } @@ -356,12 +367,16 @@ func (o clientObserver) OnSessionEvent(e session.Event) { } type stateStore struct { + gate chan struct{} store SessionStore client *Runtime - mu sync.Mutex } func (s *stateStore) Load(ctx context.Context) (*session.State, error) { + if err := s.lock(ctx); err != nil { + return nil, err + } + defer s.unlock() if s.store == nil { return nil, nil } @@ -391,6 +406,13 @@ func (s *stateStore) Load(ctx context.Context) (*session.State, error) { return &st, nil } func (s *stateStore) Save(ctx context.Context, st *session.State) error { + if err := s.lock(ctx); err != nil { + return err + } + defer s.unlock() + if err := s.client.provider.CheckAcquisition(ctx); err != nil { + return err + } if s.store == nil { return nil } @@ -401,6 +423,9 @@ func (s *stateStore) Save(ctx context.Context, st *session.State) error { if e = s.store.Save(ctx, s.client.scope, b); e != nil { return &Error{Info: ErrorInfo{Kind: ErrorStorage, Message: "session storage save failed"}, cause: sanitizedCause{e}} } + if err := s.client.provider.CheckAcquisition(ctx); err != nil { + return err + } s.client.mu.Lock() s.client.forgotten = false s.client.mu.Unlock() @@ -411,28 +436,14 @@ func (s *stateStore) Save(ctx context.Context, st *session.State) error { type pinAdapter struct { store GatewayPinStore controller string - template *tls.Config } -func (p pinAdapter) LoadPin(ctx context.Context, a string) ([]byte, error) { return nil, nil } -func (p pinAdapter) SavePin(ctx context.Context, a string, b []byte) error { - var pin [32]byte - copy(pin[:], b) - name := "" - if p.template != nil { - name = p.template.ServerName - } - if name == "" { - name, _, _ = net.SplitHostPort(a) - } - ok, e := p.store.CheckOrEnroll(ctx, GatewayIdentity{ControllerURL: p.controller, Address: a, ServerName: name}, pin) - if e != nil { - return &Error{Info: ErrorInfo{Kind: ErrorStorage, Message: "gateway pin storage failed"}} +func (p pinAdapter) CheckOrEnroll(ctx context.Context, address, serverName string, pin [32]byte) (bool, error) { + ok, err := p.store.CheckOrEnroll(ctx, GatewayIdentity{ControllerURL: p.controller, Address: address, ServerName: serverName}, pin) + if err != nil { + return false, &Error{Info: ErrorInfo{Kind: ErrorStorage, Message: "gateway pin storage failed"}, cause: sanitizedCause{err}} } - if !ok { - return errors.New("gateway public key changed") - } - return nil + return ok, nil } func PublicError(op string, e error) error { return safeError(op, e) } @@ -448,3 +459,20 @@ func ConfigError(e error) error { } return &Error{Info: ErrorInfo{Kind: ErrorConfig, Op: "new", Message: e.Error()}} } + +func cloneSession(s SessionInfo) SessionInfo { + s.Gateways = append([]string(nil), s.Gateways...) + s.DNS = append([]string(nil), s.DNS...) + s.Resources = append([]Resource(nil), s.Resources...) + return s +} + +func (s *stateStore) lock(ctx context.Context) error { + select { + case s.gate <- struct{}{}: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} +func (s *stateStore) unlock() { <-s.gate } diff --git a/internal/runtime/target_test.go b/internal/runtime/target_test.go index 0073643..05ee942 100644 --- a/internal/runtime/target_test.go +++ b/internal/runtime/target_test.go @@ -3,10 +3,7 @@ package runtime import ( "context" "errors" - "github.com/ShanghaitechGeekPie/geektrust/internal/config" - "github.com/ShanghaitechGeekPie/geektrust/internal/settings" "net" - "net/http" "net/netip" "testing" ) @@ -14,39 +11,34 @@ import ( func TestTargetFilterRejectsBeforeGatewayDial(t *testing.T) { rejected := errors.New("route excludes destination") var seen []netip.Addr - c, err := newLegacy(legacyOptions{ - Compatibility: settings.Compatibility{FallbackAppID: "app"}, - ControllerURL: config.DefaultBaseURL, DeviceID: "0123456789ABCDEF0123456789ABCDEF", - Gateways: []string{"gateway.example:441"}, Transport: compatibilityTransport{}, - SessionStore: compatibilityStore(`{"sid":"synthetic","device_id":"0123456789ABCDEF0123456789ABCDEF","client_type":"browser","cookies":[{"name":"sid","value":"synthetic"}]}`), - Authenticator: AuthenticatorFunc(func(context.Context, *http.Client) (string, error) { return "", errors.New("unexpected login") }), - CheckTarget: func(ip netip.Addr) error { seen = append(seen, ip); return rejected }, - DialContext: func(context.Context, string, string) (net.Conn, error) { - t.Error("excluded target opened transport") - return nil, errors.New("unexpected dial") - }, - }) - if err != nil { - t.Fatal(err) + o := contractOptions(&contractIdentity{subject: "account"}, &contractStore{state: validState()}) + o.CheckTarget = func(_ context.Context, t Target) error { seen = append(seen, t.IP); return rejected } + o.Network.DialContext = func(context.Context, string, string) (net.Conn, error) { + t.Error("rejected target opened a socket") + return nil, errors.New("unexpected dial") + } + c, e := New(o) + if e != nil { + t.Fatal(e) } defer c.Close() - for _, network := range []string{"tcp", "udp"} { - if _, err := c.DialContext(context.Background(), network, "192.0.2.1:443"); !errors.Is(err, rejected) { - t.Fatalf("%s target filter: %v", network, err) + for _, n := range []string{"tcp", "udp"} { + if _, e = c.DialContext(context.Background(), n, "192.0.2.1:443"); !errors.Is(e, rejected) { + t.Fatal(e) } } packet := make([]byte, 28) packet[0] = 0x45 copy(packet[16:20], []byte{192, 0, 2, 1}) - if _, err := c.ExchangeICMPEcho(context.Background(), packet); !errors.Is(err, rejected) { - t.Fatalf("ICMP target filter: %v", err) + if _, e = c.ExchangeICMPEcho(context.Background(), packet); !errors.Is(e, rejected) { + t.Fatal(e) } if len(seen) != 3 { - t.Fatalf("checked %d targets", len(seen)) + t.Fatal("missing protocol target check") } - for _, ip := range seen { - if ip != netip.MustParseAddr("192.0.2.1") { - t.Fatal("wrong resolved destination") + for _, a := range seen { + if a != netip.MustParseAddr("192.0.2.1") { + t.Fatal("wrong target address") } } } diff --git a/internal/sdpc/resource.go b/internal/sdpc/resource.go index f9d763d..80e4431 100644 --- a/internal/sdpc/resource.go +++ b/internal/sdpc/resource.go @@ -4,7 +4,7 @@ import ( "bytes" "context" "encoding/binary" - defaults "github.com/ShanghaitechGeekPie/geektrust/internal/deployment" + defaults "github.com/ShanghaitechGeekPie/geektrust/internal/compatibility" "net" "net/url" "strconv" @@ -346,6 +346,9 @@ func (c *Client) parseResource(cr *clientResource) *Resource { res.IPRules = append(res.IPRules, IPRule{ IPMin: min, IPMax: max, AppID: app.ID, Port: port, Proto: proto, }) + } else { + // A hyphen is also valid in an ordinary DNS hostname. + domains = append(domains, hostEntry{host, port, proto}) } default: domains = append(domains, hostEntry{host, port, proto}) diff --git a/internal/sdpc/resource_test.go b/internal/sdpc/resource_test.go index 263f0f5..dd54027 100644 --- a/internal/sdpc/resource_test.go +++ b/internal/sdpc/resource_test.go @@ -331,7 +331,7 @@ func TestExplicitGenericLeavesDomainAddressUninferred(t *testing.T) { v := c.parseResource(&raw) rule, ok := v.MatchDomainProtocol("library.shanghaitech.edu.cn", 443, "tcp") if !ok || rule.IP != "" { - t.Fatal("generic deployment inherited a school IP mapping") + t.Fatal("generic compatibility inherited a school IP mapping") } enabled := true c.DomainMapping = &enabled @@ -341,3 +341,30 @@ func TestExplicitGenericLeavesDomainAddressUninferred(t *testing.T) { t.Fatal("verified school mapping lost") } } + +func TestResourceKeepsHyphenatedDomainsAndIPRanges(t *testing.T) { + var raw clientResource + data := `{"appList":{"data":{"appInfo":[{"apps":[{"id":"resource","addressList":[{"host":"research-data.example.edu.cn","port":"443","protocol":"tcp"},{"host":"10.0.0.10-10.0.0.20","port":"443","protocol":"tcp"},{"host":"10.0.0.9","port":"443","protocol":"tcp"}]}]}]}}}` + if err := json.Unmarshal([]byte(data), &raw); err != nil { + t.Fatal(err) + } + for _, controller := range []string{"https://vpn.example.edu.cn", "https://vpn.shanghaitech.edu.cn"} { + t.Run(controller, func(t *testing.T) { + res := (&Client{BaseURL: controller}).parseResource(&raw) + rule, ok := res.MatchDomain("RESEARCH-DATA.example.edu.cn.", 443) + if !ok || rule.AppID != "resource" { + t.Fatalf("hyphenated domain lost: %+v, %v", rule, ok) + } + if _, ok := res.MatchDomain("research-data.example.edu.cn", 80); ok { + t.Fatal("domain port authorization widened") + } + if _, ok := res.MatchDomainProtocol("research-data.example.edu.cn", 443, "udp"); ok { + t.Fatal("domain protocol authorization widened") + } + ip, ok := res.MatchIP(net.ParseIP("10.0.0.15"), 443) + if !ok || ip.IPMin == nil || ip.IPMax == nil { + t.Fatal("IPv4 range no longer matched") + } + }) + } +} diff --git a/internal/session/events_test.go b/internal/session/events_test.go index 5da1b47..a82dc82 100644 --- a/internal/session/events_test.go +++ b/internal/session/events_test.go @@ -3,6 +3,7 @@ package session import ( "context" "encoding/json" + "errors" "io" "log/slog" "net/http" @@ -14,8 +15,8 @@ import ( "testing" "time" - "github.com/ShanghaitechGeekPie/geektrust/internal/config" "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" + "github.com/ShanghaitechGeekPie/geektrust/internal/settings" ) // recordObserver collects events and lets tests hook individual kinds. @@ -68,15 +69,11 @@ const testDeviceID = "0123456789ABCDEF0123456789ABCDEF" func failingProvider(t *testing.T) *Provider { t.Helper() - dir := t.TempDir() - return NewProvider(&config.Config{ - Keystore: filepath.Join(dir, "missing.keystore"), - DeviceID: testDeviceID, - BaseURL: "http://127.0.0.1:1", - Platform: "Mac", - ClientType: "browser", - StateFile: filepath.Join(dir, "state.enc"), - }, testLogger(), nil) + p := NewProvider(settings.Session{DeviceID: testDeviceID, BaseURL: "http://127.0.0.1:1", Platform: "Mac", ClientType: "browser"}, testLogger(), nil) + p.Authenticate = func(context.Context, *http.Client) (string, error) { + return "", errors.New("fixture authentication failed") + } + return p } func TestSanitizeErrorText(t *testing.T) { @@ -187,15 +184,12 @@ func newRestoreFixture(t *testing.T, handler http.HandlerFunc) *Provider { }); err != nil { t.Fatal(err) } - return NewProvider(&config.Config{ - Keystore: filepath.Join(dir, "missing.keystore"), - DeviceID: testDeviceID, - BaseURL: srv.URL, - Platform: "Mac", - ClientType: "browser", - StateFile: statePath, - Gateways: []string{"192.0.2.1:441"}, - }, testLogger(), nil) + p := NewProvider(settings.Session{DeviceID: testDeviceID, BaseURL: srv.URL, Platform: "Mac", ClientType: "browser", Gateways: []string{"192.0.2.1:441"}, LegacyGatewayOverride: true}, testLogger(), nil) + p.SetStore(NewStore(statePath)) + p.Authenticate = func(context.Context, *http.Client) (string, error) { + return "", errors.New("fixture full login disabled") + } + return p } func TestRestoreSuccessEmitsSessionInfo(t *testing.T) { @@ -204,7 +198,8 @@ func TestRestoreSuccessEmitsSessionInfo(t *testing.T) { obs := &recordObserver{hook: func(ev Event) { if ev.Kind == EventRestoreOK { // The credential must be published before the event is queued. - activeDuringEvent <- p.ActiveSDPC() != nil + _, sc := p.ActiveSession() + activeDuringEvent <- sc != nil } }} p.AddObserver(obs) @@ -216,7 +211,7 @@ func TestRestoreSuccessEmitsSessionInfo(t *testing.T) { select { case ok := <-activeDuringEvent: if !ok { - t.Error("ActiveSDPC returned nil inside restore_success callback") + t.Error("ActiveSession returned nil inside restore_success callback") } case <-time.After(time.Second): t.Fatal("restore_success hook did not run") @@ -450,7 +445,8 @@ func TestFinishRefreshPublishesLoginSuccess(t *testing.T) { active := make(chan bool, 1) obs := &recordObserver{hook: func(ev Event) { if ev.Kind == EventLoginSuccess { - active <- p.ActiveSDPC() != nil + _, sc := p.ActiveSession() + active <- sc != nil } }} p.AddObserver(obs) @@ -458,10 +454,9 @@ func TestFinishRefreshPublishesLoginSuccess(t *testing.T) { call := &refreshCall{done: make(chan struct{})} p.mu.Lock() p.refreshing = call - p.sdpc = &sdpc.Client{} p.mu.Unlock() - cred := &Credential{SID: "sid", DeviceID: testDeviceID, Gateways: []string{"g1"}} + cred := &Credential{controller: &sdpc.Client{}, SID: "sid", DeviceID: testDeviceID, Gateways: []string{"g1"}} session := &SessionInfo{Username: "u1", DisplayName: "测试用户", DeviceID: testDeviceID} // A waiter joins the reserved slot and must receive the published result. @@ -484,7 +479,7 @@ func TestFinishRefreshPublishesLoginSuccess(t *testing.T) { select { case ok := <-active: if !ok { - t.Error("ActiveSDPC returned nil inside login_success callback") + t.Error("ActiveSession returned nil inside login_success callback") } case <-time.After(time.Second): t.Fatal("login_success hook did not run") @@ -510,3 +505,27 @@ func TestSessionInfoCopiesSlices(t *testing.T) { t.Error("SessionInfo aliases credential gateways") } } + +func TestInvalidationRejectsInFlightRestore(t *testing.T) { + entered, release := make(chan struct{}), make(chan struct{}) + p := newRestoreFixture(t, func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/controller/v1/user/clientResource" { + close(entered) + <-release + } + restoreHandler(w, r) + }) + defer p.Close() + result := make(chan error, 1) + go func() { _, err := p.Credential(context.Background()); result <- err }() + <-entered + p.Invalidate() + close(release) + if err := <-result; !errors.Is(err, ErrSessionReplaced) { + t.Fatalf("stale restore = %v, want session replaced", err) + } + cred, sc := p.ActiveSession() + if cred != nil || sc != nil { + t.Fatal("invalidated acquisition published a controller or credential") + } +} diff --git a/internal/session/force_login_regression_test.go b/internal/session/force_login_regression_test.go new file mode 100644 index 0000000..77cdd41 --- /dev/null +++ b/internal/session/force_login_regression_test.go @@ -0,0 +1,119 @@ +package session + +import ( + "context" + "errors" + "net/http" + "sync/atomic" + "testing" + "time" +) + +func TestCancelledForceLoginKeepsCurrentSession(t *testing.T) { + p := failingProvider(t) + current := &Credential{SID: "existing"} + p.cur = current + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := p.ForceLogin(ctx); !errors.Is(err, context.Canceled) { + t.Fatalf("cancelled force login = %v", err) + } + if p.Current() != current { + t.Fatal("a cancelled operation invalidated the current session") + } +} + +func TestConcurrentForceLoginSharesAuthentication(t *testing.T) { + p := failingProvider(t) + entered, release := make(chan struct{}), make(chan struct{}) + var calls atomic.Int32 + rejected := errors.New("fixture authentication rejected") + p.Authenticate = func(context.Context, *http.Client) (string, error) { + if calls.Add(1) == 1 { + close(entered) + } + <-release + return "", rejected + } + first, second := make(chan error, 1), make(chan error, 1) + go func() { _, err := p.ForceLogin(context.Background()); first <- err }() + <-entered + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + joined := signalJoin(ctx) + go func() { _, err := p.ForceLogin(joined); second <- err }() + waitForJoiner(t, joined) + close(release) + for _, result := range []<-chan error{first, second} { + if err := <-result; !errors.Is(err, rejected) { + t.Fatalf("force login result = %v", err) + } + } + if calls.Load() != 1 { + t.Fatalf("concurrent force login made %d authentication attempts, want 1", calls.Load()) + } +} + +func TestForceLoginWaitsForRestoreThenAuthenticates(t *testing.T) { + entered, release := make(chan struct{}), make(chan struct{}) + p := newRestoreFixture(t, func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/passport/v1/user/onlineInfo" { + close(entered) + <-release + } + restoreHandler(w, r) + }) + rejected := errors.New("forced authentication reached") + p.Authenticate = func(context.Context, *http.Client) (string, error) { return "", rejected } + ordinary := make(chan error, 1) + go func() { _, err := p.Credential(context.Background()); ordinary <- err }() + <-entered + forced := make(chan error, 1) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + joined := signalJoin(ctx) + go func() { _, err := p.ForceLogin(joined); forced <- err }() + waitForJoiner(t, joined) + close(release) + if err := <-ordinary; err != nil { + t.Fatal(err) + } + if err := <-forced; !errors.Is(err, rejected) { + t.Fatalf("forced login reused a restore: %v", err) + } +} + +func TestForcedJoinerRetriesCancelledLeader(t *testing.T) { + p := failingProvider(t) + entered := make(chan struct{}) + var calls atomic.Int32 + rejected := errors.New("live caller authenticated") + p.Authenticate = func(ctx context.Context, _ *http.Client) (string, error) { + if calls.Add(1) == 1 { + close(entered) + <-ctx.Done() + return "", ctx.Err() + } + return "", rejected + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + first, second := make(chan error, 1), make(chan error, 1) + go func() { _, err := p.ForceLogin(ctx); first <- err }() + <-entered + live, stop := context.WithTimeout(context.Background(), 3*time.Second) + defer stop() + joined := signalJoin(live) + go func() { _, err := p.ForceLogin(joined); second <- err }() + waitForJoiner(t, joined) + cancel() + if err := <-first; !errors.Is(err, context.Canceled) { + t.Fatalf("leader = %v", err) + } + if err := <-second; !errors.Is(err, rejected) { + t.Fatalf("live joiner = %v", err) + } + if calls.Load() != 2 { + t.Fatalf("authentication attempts = %d", calls.Load()) + } +} diff --git a/internal/session/force_queue_regression_test.go b/internal/session/force_queue_regression_test.go new file mode 100644 index 0000000..e22e104 --- /dev/null +++ b/internal/session/force_queue_regression_test.go @@ -0,0 +1,49 @@ +package session + +import ( + "context" + "errors" + "sync" + "testing" +) + +type checkedContext struct { + context.Context + checked chan struct{} + once sync.Once +} + +func (c *checkedContext) Err() error { + err := c.Context.Err() + c.once.Do(func() { close(c.checked) }) + return err +} + +func TestQueuedAcquisitionCancellationKeepsSession(t *testing.T) { + for _, forced := range []bool{false, true} { + t.Run(map[bool]string{false: "credential", true: "forced"}[forced], func(t *testing.T) { + p := failingProvider(t) + current := &Credential{SID: "existing"} + p.mu.Lock() + p.cur = current + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + checked := &checkedContext{Context: ctx, checked: make(chan struct{})} + result := make(chan error, 1) + acquire := p.Credential + if forced { + acquire = p.ForceLogin + } + go func() { _, err := acquire(checked); result <- err }() + <-checked.checked + cancel() + p.mu.Unlock() + if err := <-result; !errors.Is(err, context.Canceled) { + t.Fatalf("cancelled queued acquisition = %v", err) + } + if p.Current() != current { + t.Fatal("cancellation while waiting for the lock invalidated the session") + } + }) + } +} diff --git a/internal/session/interaction.go b/internal/session/interaction.go index 54452a0..95ca485 100644 --- a/internal/session/interaction.go +++ b/internal/session/interaction.go @@ -4,6 +4,7 @@ import ( "context" "errors" "github.com/ShanghaitechGeekPie/geektrust/auth" + "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" "time" ) @@ -42,6 +43,11 @@ func (p *Provider) Current() *Credential { p.mu.Lock(); defer p.mu.Unlock(); ret func (p *Provider) Close() { p.mu.Lock() p.closed = true + p.revision++ + if p.cancelSession != nil { + p.cancelSession() + p.cancelSession = nil + } p.cur = nil p.mu.Unlock() p.CloseObservers() @@ -54,3 +60,37 @@ var ErrSessionReplaced = errors.New("session replaced") func ExpectGeneration(ctx context.Context, g uint64) context.Context { return context.WithValue(ctx, expectedGenerationKey{}, g) } + +type acquisitionKey struct{} + +func withAcquisition(ctx context.Context, revision uint64) context.Context { + return context.WithValue(ctx, acquisitionKey{}, revision) +} +func (p *Provider) CheckAcquisition(ctx context.Context) error { + p.mu.Lock() + defer p.mu.Unlock() + return p.checkAcquisitionLocked(ctx) +} + +func (p *Provider) checkAcquisitionLocked(ctx context.Context) error { + if err := ctx.Err(); err != nil { + return err + } + if p.closed { + return context.Canceled + } + if revision, ok := ctx.Value(acquisitionKey{}).(uint64); ok && revision != p.revision { + return ErrSessionReplaced + } + return nil +} + +// ActiveSession returns the credential and controller from one acquisition. +func (p *Provider) ActiveSession() (*Credential, *sdpc.Client) { + p.mu.Lock() + defer p.mu.Unlock() + if p.cur == nil { + return nil, nil + } + return p.cur, p.cur.controller +} diff --git a/internal/session/live_test.go b/internal/session/live_test.go index 8da2e1e..440bd47 100644 --- a/internal/session/live_test.go +++ b/internal/session/live_test.go @@ -2,8 +2,11 @@ package session import ( "context" + "github.com/ShanghaitechGeekPie/geektrust/auth" + "github.com/ShanghaitechGeekPie/geektrust/internal/storage" "io" "log/slog" + "net/http" "os" "testing" "time" @@ -11,11 +14,6 @@ import ( "github.com/ShanghaitechGeekPie/geektrust/internal/config" ) -type ephemeralStore struct{} - -func (ephemeralStore) Load(context.Context) (*State, error) { return nil, nil } -func (ephemeralStore) Save(context.Context, *State) error { return nil } - func TestECNULiveSession(t *testing.T) { if os.Getenv("GEEKTRUST_LIVE_TESTS") != "1" { t.Skip("online tests require explicit GEEKTRUST_LIVE_TESTS=1") @@ -29,8 +27,14 @@ func TestECNULiveSession(t *testing.T) { t.Fatal(err) } cfg := &config.Config{Keystore: path, BaseURL: "https://vpn.ecnu.edu.cn", Platform: "Mac", ClientType: "browser", DeviceID: device} - p := NewProvider(cfg, slog.New(slog.NewTextHandler(io.Discard, nil)), nil) - p.SetStore(ephemeralStore{}) + p := NewProvider(cfg.SessionOptions(), slog.New(slog.NewTextHandler(io.Discard, nil)), nil) + identity, err := auth.NewPasskey(storage.CredentialFile(path)) + if err != nil { + t.Fatal(err) + } + p.Authenticate = func(ctx context.Context, h *http.Client) (string, error) { + return "", identity.Authenticate(ctx, h, auth.IdentityRequest{AllowInteraction: true}) + } ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second) defer cancel() cred, err := p.Credential(ctx) diff --git a/internal/session/provider.go b/internal/session/provider.go index 2b066ee..6f6c095 100644 --- a/internal/session/provider.go +++ b/internal/session/provider.go @@ -12,7 +12,7 @@ import ( "time" "github.com/ShanghaitechGeekPie/geektrust/auth" - "github.com/ShanghaitechGeekPie/geektrust/internal/idsauth" + "github.com/ShanghaitechGeekPie/geektrust/compatibility" "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" "github.com/ShanghaitechGeekPie/geektrust/internal/settings" ) @@ -28,9 +28,11 @@ var errSMSAuthSessionExpired = errors.New("SMS authentication session expired") // Credential is everything the tunnel and resolver need from a live session. type Credential struct { + controller *sdpc.Client + Lifetime context.Context Generation uint64 LegacyGatewayOverride bool - ProcessIdentity *settings.ProcessIdentity + ProcessIdentity *compatibility.ProcessMetadata // AppID is the legacy fallback; matched resource rules always take priority. AppID string MissingGatewayGroupFallback bool @@ -82,13 +84,14 @@ type Provider struct { Transport http.RoundTripper HTTPTimeout time.Duration - mu sync.Mutex - cur *Credential - sdpc *sdpc.Client // last client, for liveness checks - refreshing *refreshCall - generation uint64 - closed bool - forceLogin bool // set by Invalidate; skips restore on the next refresh + mu sync.Mutex + cur *Credential + refreshing *refreshCall + generation uint64 + revision uint64 + cancelSession context.CancelFunc + closed bool + forceLogin bool // set by Invalidate; skips restore on the next refresh dispMu sync.Mutex dispCond *sync.Cond // lazily created on first AddObserver @@ -102,47 +105,32 @@ type Provider struct { // refreshCall is one in-flight restore/login shared by every concurrent // caller: all waiters block on done and then read the same result. type refreshCall struct { - done chan struct{} // closed once cred/err are populated - cred *Credential - err error - leader context.Context + revision uint64 + forced bool + done chan struct{} // closed once cred/err are populated + cred *Credential + err error + leader context.Context } // NewProvider builds a credential provider. prompt may be nil; a login that // requires SMS then returns an error. -func NewProvider(source interface{ SessionOptions() settings.Session }, logger *slog.Logger, prompt SMSPrompter) *Provider { - normalized := source.SessionOptions() - normalized.Compatibility = normalized.Compatibility.Clone() +func NewProvider(normalized settings.Session, logger *slog.Logger, prompt SMSPrompter) *Provider { + normalized.Gateways = append([]string(nil), normalized.Gateways...) + normalized.DNS = append([]string(nil), normalized.DNS...) + normalized.Fallbacks.Gateways = append([]string(nil), normalized.Fallbacks.Gateways...) + if normalized.Process != nil { + value := *normalized.Process + normalized.Process = &value + } cfg := &normalized return &Provider{ cfg: cfg, logger: logger, prompt: prompt, - store: NewStore(cfg.StateFile), } } -// SDPCClient returns the controller client from the last successful login, -// or nil if no session has been established. Callers must not cache it: a -// re-login may replace it at any time. -func (p *Provider) SDPCClient() *sdpc.Client { - p.mu.Lock() - defer p.mu.Unlock() - return p.sdpc -} - -// ActiveSDPC returns the controller client only while a credential is -// active. Invalidate clears cur but keeps the last client, so SDPCClient -// can be stale; this method cannot. -func (p *Provider) ActiveSDPC() *sdpc.Client { - p.mu.Lock() - defer p.mu.Unlock() - if p.cur == nil { - return nil - } - return p.sdpc -} - // SetSMSHandler replaces the simple SMSPrompter with a resend-capable // handler. Called during web wiring, before the first Credential. func (p *Provider) SetSMSHandler(h SMSHandler) { p.smsHandler = h } @@ -216,6 +204,10 @@ func (p *Provider) Credential(ctx context.Context) (*Credential, error) { return nil, err } p.mu.Lock() + if err := ctx.Err(); err != nil { + p.mu.Unlock() + return nil, err + } if p.closed { p.mu.Unlock() return nil, context.Canceled @@ -235,13 +227,13 @@ func (p *Provider) Credential(ctx context.Context) (*Credential, error) { } call := p.refreshing if call == nil { - call = &refreshCall{done: make(chan struct{}), leader: ctx} + call = &refreshCall{done: make(chan struct{}), leader: ctx, revision: p.revision} p.refreshing = call p.mu.Unlock() + ctx = withAcquisition(ctx, call.revision) cred, session, restored, err := p.acquire(ctx, false) - p.finishRefresh(call, cred, session, restored, err) - return cred, err + return p.finishRefresh(call, cred, session, restored, err) } p.mu.Unlock() select { @@ -266,8 +258,12 @@ func (p *Provider) Credential(ctx context.Context) (*Credential, error) { // queues the lifecycle event, so observers can never see "online" while // ActiveSDPC still returns nil. Events are queued under the lock (emit // never callbacks), then waiters are released. -func (p *Provider) finishRefresh(call *refreshCall, cred *Credential, session *SessionInfo, restored bool, err error) { +func (p *Provider) finishRefresh(call *refreshCall, cred *Credential, session *SessionInfo, restored bool, err error) (*Credential, error) { p.mu.Lock() + active := call.revision == p.revision && !p.closed + if call.revision != p.revision { + err = ErrSessionReplaced + } if p.closed { err = context.Canceled } @@ -275,6 +271,10 @@ func (p *Provider) finishRefresh(call *refreshCall, cred *Credential, session *S err = call.leader.Err() } if err == nil { + if p.cancelSession != nil { + p.cancelSession() + } + cred.Lifetime, p.cancelSession = context.WithCancel(context.Background()) p.generation++ cred.Generation = p.generation session.Generation = p.generation @@ -284,7 +284,7 @@ func (p *Provider) finishRefresh(call *refreshCall, cred *Credential, session *S } else { p.emit(Event{Kind: EventLoginSuccess, Session: session, Message: "会话已建立:" + session.DisplayName}) } - } else { + } else if active { kind := EventLoginFailed if errors.Is(err, auth.ErrInteractionRequired) { kind = EventInteractionRequired @@ -293,29 +293,57 @@ func (p *Provider) finishRefresh(call *refreshCall, cred *Credential, session *S } p.refreshing = nil p.mu.Unlock() + if err != nil { + cred = nil + } call.cred, call.err = cred, err close(call.done) + return cred, err } // ForceLogin performs a full login, bypassing any persisted session (used by -// the `login -fresh` command). It waits out any in-flight refresh first so -// the forced acquisition cannot be shadowed by a stale restore. +// the `login -fresh` command). Concurrent forced logins share one acquisition; +// an ordinary restore must finish before a forced acquisition starts. func (p *Provider) ForceLogin(ctx context.Context) (*Credential, error) { for { + if err := ctx.Err(); err != nil { + return nil, err + } p.mu.Lock() + if err := ctx.Err(); err != nil { + p.mu.Unlock() + return nil, err + } + if p.closed { + p.mu.Unlock() + return nil, context.Canceled + } call := p.refreshing - p.mu.Unlock() if call == nil { - break + p.invalidateLocked() + call = &refreshCall{done: make(chan struct{}), leader: ctx, revision: p.revision, forced: true} + p.refreshing = call + p.mu.Unlock() + ctx = withAcquisition(ctx, call.revision) + cred, session, _, err := p.acquire(ctx, true) + return p.finishRefresh(call, cred, session, false, err) } + p.mu.Unlock() select { case <-call.done: + if err := ctx.Err(); err != nil { + return nil, err + } + if call.forced { + if call.err != nil && call.leader != nil && call.leader.Err() != nil && errors.Is(call.err, call.leader.Err()) { + continue + } + return call.cred, call.err + } case <-ctx.Done(): return nil, ctx.Err() } } - p.Invalidate() - return p.Credential(ctx) } // Invalidate drops the cached credential and marks the persisted session as @@ -344,6 +372,11 @@ func (p *Provider) InvalidateIfCurrent(expected *Credential) bool { // clearSessionLocked drops the current credential and queues the // invalidated event without touching forceLogin. Callers must hold p.mu. func (p *Provider) clearSessionLocked() { + p.revision++ + if p.cancelSession != nil { + p.cancelSession() + p.cancelSession = nil + } p.cur = nil p.emit(Event{Kind: EventInvalidated, Message: "会话已失效"}) } @@ -369,12 +402,14 @@ func (p *Provider) TryForceRelogin() (run func(context.Context), ok bool) { if p.closed || p.refreshing != nil { return nil, false } - call := &refreshCall{done: make(chan struct{})} + p.clearSessionLocked() + call := &refreshCall{done: make(chan struct{}), revision: p.revision, forced: true} p.refreshing = call - if p.cur != nil { - p.clearSessionLocked() - } return func(ctx context.Context) { + p.mu.Lock() + call.leader = ctx + p.mu.Unlock() + ctx = withAcquisition(ctx, call.revision) cred, session, _, err := p.acquire(ctx, true) p.finishRefresh(call, cred, session, false, err) }, true @@ -394,9 +429,7 @@ func (p *Provider) CheckLoop(ctx context.Context, interval time.Duration) { return case <-ticker.C: } - p.mu.Lock() - cred, sc := p.cur, p.sdpc - p.mu.Unlock() + cred, sc := p.ActiveSession() if cred == nil || sc == nil { continue } @@ -439,6 +472,10 @@ func (p *Provider) acquire(ctx context.Context, force bool) (*Credential, *Sessi return nil, nil, false, err } p.mu.Lock() + if err := p.checkAcquisitionLocked(ctx); err != nil { + p.mu.Unlock() + return nil, nil, false, err + } skipRestore := force || p.forceLogin p.forceLogin = false p.mu.Unlock() @@ -448,7 +485,7 @@ func (p *Provider) acquire(ctx context.Context, force bool) (*Credential, *Sessi if ctx.Err() != nil { return nil, nil, false, ctx.Err() } - if p.cfg.StrictStorage && errors.Is(err, ErrStateStorage) { + if errors.Is(err, ErrStateStorage) { return nil, nil, false, err } p.logger.Warn("restoring persisted session failed; performing full login", "err", err) @@ -460,7 +497,15 @@ func (p *Provider) acquire(ctx context.Context, force bool) (*Credential, *Sessi if err := ctx.Err(); err != nil { return nil, nil, false, err } - p.emit(Event{Kind: EventLoginStart, Message: "开始完整登录"}) + p.mu.Lock() + err := p.checkAcquisitionLocked(ctx) + if err == nil { + p.emit(Event{Kind: EventLoginStart, Message: "开始完整登录"}) + } + p.mu.Unlock() + if err != nil { + return nil, nil, false, err + } cred, session, err := p.login(ctx) return cred, session, false, err } @@ -468,6 +513,9 @@ func (p *Provider) acquire(ctx context.Context, force bool) (*Credential, *Sessi // restore validates the persisted state via onlineInfo and rebuilds the // routing policy. Returns (nil, nil, nil) when there is nothing to restore. func (p *Provider) restore(ctx context.Context) (*Credential, *SessionInfo, error) { + if p.store == nil { + return nil, nil, nil + } st, err := p.store.Load(ctx) if err != nil { return nil, nil, fmt.Errorf("%w: %w", ErrStateStorage, err) @@ -564,16 +612,7 @@ func (p *Provider) loginOnce(ctx context.Context) (*Credential, *SessionInfo, er hc := &http.Client{Jar: jar, Timeout: p.httpTimeout(), Transport: p.Transport} authenticate := p.Authenticate if authenticate == nil { - authenticate = func(ctx context.Context, hc *http.Client) (string, error) { - ks, err := idsauth.LoadKeystore(p.cfg.Keystore) - if err != nil { - return "", err - } - if err = idsauth.NewClient(ks, hc).Login(ctx); err != nil { - return "", err - } - return ks.Username(), nil - } + return nil, nil, errors.New("identity authenticator required") } if _, err := authenticate(ctx, hc); err != nil { return nil, nil, fmt.Errorf("%w: %w", ErrIdentityAuthentication, err) @@ -695,7 +734,7 @@ func (p *Provider) finishLogin(ctx context.Context, sc *sdpc.Client, username st gateways = res.Gateways } if len(gateways) == 0 && !p.cfg.GatewayFilter { - gateways = append([]string(nil), p.cfg.Compatibility.FallbackGateways...) + gateways = append([]string(nil), p.cfg.Fallbacks.Gateways...) } if len(gateways) == 0 { return nil, fmt.Errorf("controller supplied no gateway addresses") @@ -703,7 +742,7 @@ func (p *Provider) finishLogin(ctx context.Context, sc *sdpc.Client, username st if p.cfg.GatewayFilter { candidates := res.Gateways if len(candidates) == 0 { - candidates = p.cfg.Compatibility.FallbackGateways + candidates = p.cfg.Fallbacks.Gateways } gateways = nil for _, candidate := range candidates { @@ -715,17 +754,21 @@ func (p *Provider) finishLogin(ctx context.Context, sc *sdpc.Client, username st } } } + if len(gateways) == 0 { + return nil, errors.New("no usable gateway remains after filtering") + } dns := p.cfg.DNS if !p.cfg.DNSConfigured && len(dns) == 0 { dns = res.DNS } cred := &Credential{ + controller: sc, LegacyGatewayOverride: p.cfg.LegacyGatewayOverride, - ProcessIdentity: p.cfg.Compatibility.ProcessIdentity, - AppID: p.cfg.Compatibility.FallbackAppID, - MissingGatewayGroupFallback: p.cfg.Compatibility.MissingGatewayGroupFallback, - AllowTCPFallback: p.cfg.Compatibility.TCPToL3Fallback, + ProcessIdentity: p.cfg.Process, + AppID: p.cfg.Fallbacks.ApplicationID, + MissingGatewayGroupFallback: p.cfg.Fallbacks.MissingGatewayGroup, + AllowTCPFallback: p.cfg.Fallbacks.StreamToL3, GatewayOverride: p.cfg.GatewayFilter, SID: sc.SID(), DeviceID: p.cfg.DeviceID, @@ -742,25 +785,23 @@ func (p *Provider) finishLogin(ctx context.Context, sc *sdpc.Client, username st for _, ck := range cred.Cookies { records = append(records, CookieRecord{Name: ck.Name, Value: ck.Value}) } - if err := p.store.Save(ctx, &State{ - Version: 1, ControllerURL: p.cfg.BaseURL, IdentityIssuer: p.cfg.IdentityIssuer, IdentitySubject: p.cfg.IdentitySubject, IdentityKind: p.cfg.IdentityKind, LoginDomain: p.cfg.LoginDomain, Username: username, - SID: cred.SID, - DeviceID: cred.DeviceID, - CsrfToken: cred.CsrfToken, - Cookies: records, - Gateways: cred.Gateways, - ClientType: p.cfg.ClientType, - }); err != nil { - if p.cfg.StrictStorage { - return nil, err + if p.store != nil { + if err := p.store.Save(ctx, &State{ + SavedAt: time.Now(), Version: 1, ControllerURL: p.cfg.BaseURL, IdentityIssuer: p.cfg.IdentityIssuer, IdentitySubject: p.cfg.IdentitySubject, IdentityKind: p.cfg.IdentityKind, LoginDomain: p.cfg.LoginDomain, Username: username, + SID: cred.SID, + DeviceID: cred.DeviceID, + CsrfToken: cred.CsrfToken, + Cookies: records, + Gateways: cred.Gateways, + ClientType: p.cfg.ClientType, + }); err != nil { + return nil, fmt.Errorf("%w: %w", ErrStateStorage, err) } - // Legacy callers retain their persistence behavior. - p.logger.Error("failed to persist session state", "err", err) } - p.mu.Lock() - p.sdpc = sc - p.mu.Unlock() + if err := p.CheckAcquisition(ctx); err != nil { + return nil, err + } return cred, nil } diff --git a/internal/session/provider_test.go b/internal/session/provider_test.go index c55a253..10fd8d9 100644 --- a/internal/session/provider_test.go +++ b/internal/session/provider_test.go @@ -81,10 +81,11 @@ func TestRestoreSkipsDifferentClientType(t *testing.T) { store := NewStore(statePath) const deviceID = "0123456789ABCDEF0123456789ABCDEF" if err := store.Save(context.Background(), &State{ - SID: "synthetic-session", - DeviceID: deviceID, - Cookies: []CookieRecord{{Name: "sid", Value: "synthetic-session"}}, - ClientType: tt.stateType, + ControllerURL: "http://127.0.0.1:1", + SID: "synthetic-session", + DeviceID: deviceID, + Cookies: []CookieRecord{{Name: "sid", Value: "synthetic-session"}}, + ClientType: tt.stateType, }); err != nil { t.Fatal(err) } diff --git a/internal/session/store.go b/internal/session/store.go index 06f0e18..e64ea63 100644 --- a/internal/session/store.go +++ b/internal/session/store.go @@ -188,12 +188,6 @@ func decrypt(key, sealed []byte) ([]byte, error) { return gcm.Open(nil, nonce, ct, nil) } -// writeFileAtomic writes via temp file + rename so secrets are never left -// half-written. -func writeFileAtomic(path string, data []byte, perm os.FileMode) error { - return storage.WriteAtomic(path, data, perm) -} - // StateStore persists session state; embedding applications can supply protected storage. type StateStore interface { Load(context.Context) (*State, error) diff --git a/internal/settings/compatibility.go b/internal/settings/compatibility.go deleted file mode 100644 index 704858c..0000000 --- a/internal/settings/compatibility.go +++ /dev/null @@ -1,73 +0,0 @@ -// LegacyCompatibility is the version-1 file representation. -package settings - -import ( - "fmt" - "net" - "strconv" - "strings" - "unicode" -) - -// Compatibility is opt-in. Its zero value uses controller policy without -// deployment-specific fallbacks. These settings never override a server denial. -type Compatibility struct { - ProcessIdentity *ProcessIdentity `toml:"process_identity" json:"process_identity,omitempty"` - FallbackAppID string `toml:"fallback_app_id" json:"fallback_app_id,omitempty"` - FallbackGateways []string `toml:"fallback_gateways" json:"fallback_gateways,omitempty"` - GatewayServerName string `toml:"gateway_server_name" json:"gateway_server_name,omitempty"` - MissingGatewayGroupFallback bool `toml:"missing_gateway_group_fallback" json:"missing_gateway_group_fallback,omitempty"` - TCPToL3Fallback bool `toml:"tcp_to_l3_fallback" json:"tcp_to_l3_fallback,omitempty"` -} - -// Clone separates an active client's settings from caller-owned configuration. -func (c Compatibility) Clone() Compatibility { - if c.ProcessIdentity != nil { - identity := *c.ProcessIdentity - c.ProcessIdentity = &identity - } - c.FallbackGateways = append([]string(nil), c.FallbackGateways...) - return c -} - -func (c Compatibility) Validate() error { - if c.ProcessIdentity != nil { - if err := c.ProcessIdentity.Validate(); err != nil { - return err - } - } - if len(c.FallbackAppID) > 256 || strings.IndexFunc(c.FallbackAppID, unicode.IsControl) >= 0 { - return fmt.Errorf("compatibility.fallback_app_id must be at most 256 characters without control characters") - } - if c.GatewayServerName != "" { - name := c.GatewayServerName - if len(name) > 253 || strings.ContainsAny(name, "/\\:@?# \t\r\n") || strings.IndexFunc(name, unicode.IsControl) >= 0 { - return fmt.Errorf("compatibility.gateway_server_name must be a TLS hostname without a port") - } - } - for _, address := range c.FallbackGateways { - host, port, err := net.SplitHostPort(address) - number, portErr := strconv.Atoi(port) - if err != nil || host == "" || portErr != nil || number < 1 || number > 65535 || strings.ContainsAny(host, "/\\@?# \t\r\n") { - return fmt.Errorf("compatibility.fallback_gateways entries must be host:port with port 1-65535") - } - } - return nil -} - -// ProcessIdentity overrides the process metadata sent to the gateway. It is -// protocol metadata, not a claim about a locally running or verified process. -type ProcessIdentity struct { - Name string `toml:"name" json:"name"` - Platform string `toml:"platform" json:"platform"` - Path string `toml:"path" json:"path"` -} - -func (p ProcessIdentity) Validate() error { - for _, value := range []string{p.Name, p.Platform, p.Path} { - if strings.TrimSpace(value) == "" || len(value) > 4096 || strings.IndexFunc(value, unicode.IsControl) >= 0 { - return fmt.Errorf("compatibility.process_identity requires name, platform and path without control characters (max 4096 bytes each)") - } - } - return nil -} diff --git a/internal/settings/session.go b/internal/settings/session.go index 7676211..ad28809 100644 --- a/internal/settings/session.go +++ b/internal/settings/session.go @@ -1,17 +1,16 @@ // Package settings contains normalized runtime values, independent of file formats. package settings +import "github.com/ShanghaitechGeekPie/geektrust/compatibility" + type Session struct { DomainMapping *bool BaseURL, DeviceID, Platform, ClientType, LoginDomain string - Keystore, StateFile string Gateways, DNS []string - Compatibility Compatibility + Fallbacks compatibility.Fallbacks + Process *compatibility.ProcessMetadata IdentityIssuer, IdentitySubject, IdentityKind string LegacyGatewayOverride bool DNSConfigured bool - StrictStorage bool GatewayFilter bool } - -func (s Session) SessionOptions() Session { return s } diff --git a/internal/tunnel/line_test.go b/internal/tunnel/line_test.go index 140894c..3f03f41 100644 --- a/internal/tunnel/line_test.go +++ b/internal/tunnel/line_test.go @@ -2,6 +2,7 @@ package tunnel import ( "bufio" + "bytes" "context" "crypto/tls" "crypto/x509" @@ -71,16 +72,14 @@ type testPinStore struct { pins map[string][]byte } -func (s *testPinStore) LoadPin(_ context.Context, addr string) ([]byte, error) { +func (s *testPinStore) CheckOrEnroll(_ context.Context, addr, _ string, pin [32]byte) (bool, error) { s.mu.Lock() defer s.mu.Unlock() - return append([]byte(nil), s.pins[addr]...), nil -} -func (s *testPinStore) SavePin(_ context.Context, addr string, pin []byte) error { - s.mu.Lock() - defer s.mu.Unlock() - s.pins[addr] = append([]byte(nil), pin...) - return nil + if stored, ok := s.pins[addr]; ok { + return bytes.Equal(stored, pin[:]), nil + } + s.pins[addr] = append([]byte(nil), pin[:]...) + return true, nil } func TestGatewayTrustOnFirstUsePinsPublicKey(t *testing.T) { @@ -94,13 +93,18 @@ func TestGatewayTrustOnFirstUsePinsPublicKey(t *testing.T) { if _, err := newLines().bestForTest(ctx); err != nil { t.Fatal(err) } - if pin, _ := store.LoadPin(ctx, addr); len(pin) != 32 { + store.mu.Lock() + length := len(store.pins[addr]) + store.mu.Unlock() + if length != 32 { t.Fatal("gateway public key was not persisted") } if _, err := newLines().bestForTest(ctx); err != nil { t.Fatalf("matching gateway pin rejected: %v", err) } - store.SavePin(ctx, addr, make([]byte, 32)) + store.mu.Lock() + store.pins[addr] = make([]byte, 32) + store.mu.Unlock() if _, err := newLines().bestForTest(ctx); err == nil || !strings.Contains(err.Error(), "public key changed") { t.Fatalf("changed gateway key accepted: %v", err) } diff --git a/internal/tunnel/reset.go b/internal/tunnel/reset.go index 47f6ef0..39dd3f8 100644 --- a/internal/tunnel/reset.go +++ b/internal/tunnel/reset.go @@ -1,7 +1,18 @@ package tunnel +import "context" + func (m *Manager) Reset() { m.mu.Lock() + if call := m.connecting; call != nil { + m.connecting = nil + call.cancel() + if !call.finished { + call.err = context.Canceled + call.finished = true + close(call.done) + } + } if m.cur != nil { m.cur.Close() m.cur = nil diff --git a/internal/tunnel/tcp.go b/internal/tunnel/tcp.go index dd72c9a..cd8cb39 100644 --- a/internal/tunnel/tcp.go +++ b/internal/tunnel/tcp.go @@ -9,6 +9,7 @@ import ( "encoding/json" "errors" "fmt" + "github.com/ShanghaitechGeekPie/geektrust/compatibility" "io" "net" "strconv" @@ -283,7 +284,7 @@ func buildTCPRequest(cred *session.Credential, ip string, port int, appID, domai } processPlatform := "Linux" if identity := cred.ProcessIdentity; identity != nil { - if err := identity.Validate(); err != nil { + if err := (compatibility.Options{Protocol: compatibility.ProtocolOptions{Process: identity}}).Validate(); err != nil { return nil, err } processName, processPath, processPlatform = identity.Name, identity.Path, identity.Platform diff --git a/internal/tunnel/tcp_test.go b/internal/tunnel/tcp_test.go index 21918db..f39d839 100644 --- a/internal/tunnel/tcp_test.go +++ b/internal/tunnel/tcp_test.go @@ -13,9 +13,9 @@ import ( "syscall" "testing" + "github.com/ShanghaitechGeekPie/geektrust/compatibility" "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" "github.com/ShanghaitechGeekPie/geektrust/internal/session" - "github.com/ShanghaitechGeekPie/geektrust/internal/settings" ) func TestBuildTCPRequestCombinesAuthAndDestination(t *testing.T) { @@ -226,7 +226,7 @@ func TestTCPAuthenticationDenialNeverFallsBack(t *testing.T) { } func TestTCPConfiguredProcessIdentity(t *testing.T) { - identity := &settings.ProcessIdentity{Name: "custom-client", Platform: "Windows", Path: "custom-client.exe"} + identity := &compatibility.ProcessMetadata{Name: "custom-client", Platform: "Windows", Path: "custom-client.exe"} packet, err := buildTCPRequest(&session.Credential{ProcessIdentity: identity}, "192.0.2.1", 22, "app", "") if err != nil { t.Fatal(err) diff --git a/internal/tunnel/tls_callback_regression_test.go b/internal/tunnel/tls_callback_regression_test.go new file mode 100644 index 0000000..f0921ab --- /dev/null +++ b/internal/tunnel/tls_callback_regression_test.go @@ -0,0 +1,138 @@ +package tunnel + +import ( + "context" + "crypto/tls" + "crypto/x509" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestCAOrTOFUCallbacksReceiveVerifiedChains(t *testing.T) { + server := httptest.NewTLSServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + defer server.Close() + roots := x509.NewCertPool() + roots.AddCert(server.Certificate()) + addr := strings.TrimPrefix(server.URL, "https://") + for _, kind := range []string{"peer", "connection"} { + t.Run(kind, func(t *testing.T) { + config := &tls.Config{RootCAs: roots} + called := false + if kind == "peer" { + config.VerifyPeerCertificate = func(_ [][]byte, chains [][]*x509.Certificate) error { + called = true + if len(chains) == 0 { + return errors.New("missing verified certificate chain") + } + return nil + } + } else { + config.VerifyConnection = func(state tls.ConnectionState) error { + called = true + if len(state.VerifiedChains) == 0 { + return errors.New("missing verified certificate chain") + } + return nil + } + } + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + pins := &testPinStore{pins: map[string][]byte{}} + conn, err := probeGatewayTLSWithDialer(ctx, addr, nil, config, pins) + if err != nil { + t.Fatal(err) + } + conn.Close() + if !called { + t.Fatal("custom certificate check was skipped") + } + if len(pins.pins) != 0 { + t.Fatal("CA-verified connection should not enroll a fallback pin") + } + }) + } +} + +func TestCallbackRejectionDoesNotEnrollGatewayPin(t *testing.T) { + server := httptest.NewTLSServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + defer server.Close() + rejected := errors.New("caller rejected certificate") + config := &tls.Config{VerifyConnection: func(tls.ConnectionState) error { return rejected }} + pins := &testPinStore{pins: map[string][]byte{}} + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + if conn, err := probeGatewayTLSWithDialer(ctx, strings.TrimPrefix(server.URL, "https://"), nil, config, pins); err == nil { + conn.Close() + t.Fatal("caller rejection was ignored") + } else if !errors.Is(err, rejected) { + t.Fatalf("callback error = %v", err) + } + if len(pins.pins) != 0 { + t.Fatal("a caller-rejected certificate was enrolled") + } +} + +func TestCAOrTOFUResumptionKeepsCallbackSemantics(t *testing.T) { + server := httptest.NewUnstartedServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + server.TLS = &tls.Config{MaxVersion: tls.VersionTLS12} + server.StartTLS() + defer server.Close() + roots := x509.NewCertPool() + roots.AddCert(server.Certificate()) + peerCalls, connectionCalls := 0, 0 + resumed := false + config := &tls.Config{RootCAs: roots, ClientSessionCache: tls.NewLRUClientSessionCache(1), + VerifyPeerCertificate: func(_ [][]byte, chains [][]*x509.Certificate) error { + peerCalls++ + if len(chains) == 0 { + return errors.New("missing verified chain") + } + return nil + }, + VerifyConnection: func(state tls.ConnectionState) error { + connectionCalls++ + resumed = state.DidResume + if len(state.VerifiedChains) == 0 { + return errors.New("missing verified chain") + } + return nil + }, + } + pins := &testPinStore{pins: map[string][]byte{}} + for range 2 { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + conn, err := probeGatewayTLSWithDialer(ctx, strings.TrimPrefix(server.URL, "https://"), nil, config, pins) + cancel() + if err != nil { + t.Fatal(err) + } + conn.Close() + } + if !resumed || peerCalls != 1 || connectionCalls != 2 { + t.Fatalf("resumed=%v, peer calls=%d, connection calls=%d", resumed, peerCalls, connectionCalls) + } +} + +func TestCAOrTOFUHonorsConfiguredClock(t *testing.T) { + server := httptest.NewTLSServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + defer server.Close() + roots := x509.NewCertPool() + roots.AddCert(server.Certificate()) + future := server.Certificate().NotAfter.Add(time.Hour) + config := &tls.Config{RootCAs: roots, Time: func() time.Time { return future }} + pins := &testPinStore{pins: map[string][]byte{}} + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + conn, err := probeGatewayTLSWithDialer(ctx, strings.TrimPrefix(server.URL, "https://"), nil, config, pins) + if err == nil { + conn.Close() + t.Fatal("expired certificate was accepted under the configured clock") + } + if len(pins.pins) != 0 { + t.Fatal("expired certificate enrolled a fallback pin") + } +} diff --git a/internal/tunnel/tunnel.go b/internal/tunnel/tunnel.go index 76b2d9b..9edd641 100644 --- a/internal/tunnel/tunnel.go +++ b/internal/tunnel/tunnel.go @@ -7,7 +7,6 @@ import ( "bufio" "context" "crypto/sha256" - "crypto/subtle" "crypto/tls" "crypto/x509" "encoding/binary" @@ -133,8 +132,7 @@ func gatewayTLSConfigWithTemplate(addr string, template *tls.Config) *tls.Config } type GatewayTrustStore interface { - LoadPin(context.Context, string) ([]byte, error) - SavePin(context.Context, string, []byte) error + CheckOrEnroll(context.Context, string, string, [32]byte) (bool, error) } func gatewayTLSConfigWithTrust(ctx context.Context, addr string, template *tls.Config, trust GatewayTrustStore) *tls.Config { @@ -143,26 +141,24 @@ func gatewayTLSConfigWithTrust(ctx context.Context, addr string, template *tls.C return cfg } previous := cfg.VerifyConnection - cfg.InsecureSkipVerify = true // verification is performed below, including system roots + previousPeer := cfg.VerifyPeerCertificate + cfg.VerifyPeerCertificate = nil // run it below, after manual verification + cfg.InsecureSkipVerify = true // verification is performed below, including system roots cfg.VerifyConnection = func(cs tls.ConnectionState) error { if len(cs.PeerCertificates) == 0 { return errors.New("gateway sent no certificate") } - if previous != nil { - if err := previous(cs); err != nil { - return err - } - } intermediates := x509.NewCertPool() for _, cert := range cs.PeerCertificates[1:] { intermediates.AddCert(cert) } - _, verifyErr := cs.PeerCertificates[0].Verify(x509.VerifyOptions{DNSName: cfg.ServerName, Roots: cfg.RootCAs, Intermediates: intermediates}) - if verifyErr == nil { - return nil + now := time.Now() + if cfg.Time != nil { + now = cfg.Time() } + chains, verifyErr := cs.PeerCertificates[0].Verify(x509.VerifyOptions{DNSName: cfg.ServerName, Roots: cfg.RootCAs, Intermediates: intermediates, CurrentTime: now}) var unknown x509.UnknownAuthorityError - if !errors.As(verifyErr, &unknown) { + if verifyErr != nil && !errors.As(verifyErr, &unknown) { return verifyErr } leaf := cs.PeerCertificates[0] @@ -173,22 +169,34 @@ func gatewayTLSConfigWithTrust(ctx context.Context, addr string, template *tls.C return fmt.Errorf("gateway certificate identity: %w", err) } } - now := time.Now() if now.Before(leaf.NotBefore) || now.After(leaf.NotAfter) { return errors.New("gateway certificate expired or not yet valid") } - pin := sha256.Sum256(leaf.RawSubjectPublicKeyInfo) - stored, err := trust.LoadPin(ctx, addr) - if err != nil { - return fmt.Errorf("load trusted gateway pin: %w", err) + // Preserve Go's callback order and full-handshake-only peer callback. + if previousPeer != nil && !cs.DidResume { + raw := make([][]byte, len(cs.PeerCertificates)) + for i, cert := range cs.PeerCertificates { + raw[i] = cert.Raw + } + if err := previousPeer(raw, chains); err != nil { + return err + } } - if len(stored) == 0 { - if err := trust.SavePin(ctx, addr, pin[:]); err != nil { - return fmt.Errorf("save trusted gateway pin: %w", err) + cs.VerifiedChains = chains + if previous != nil { + if err := previous(cs); err != nil { + return err } + } + if verifyErr == nil { return nil } - if len(stored) != len(pin) || subtle.ConstantTimeCompare(stored, pin[:]) != 1 { + pin := sha256.Sum256(leaf.RawSubjectPublicKeyInfo) + ok, err := trust.CheckOrEnroll(ctx, addr, cfg.ServerName, pin) + if err != nil { + return fmt.Errorf("check trusted gateway pin: %w", err) + } + if !ok { return errors.New("gateway public key changed") } return nil diff --git a/internal/webui/server.go b/internal/webui/server.go index a19501b..263577d 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -16,6 +16,7 @@ import ( "time" "github.com/ShanghaitechGeekPie/geektrust/internal/config" + "github.com/ShanghaitechGeekPie/geektrust/internal/runtime" "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" "github.com/ShanghaitechGeekPie/geektrust/internal/session" ) @@ -29,7 +30,7 @@ const placeholderPage = ` geekTrust 面板

geekTrust Web 面板

-

前端资源尚未构建。请安装 Node 20+,在仓库根目录执行 make build 重新构建 geekTrust。

+

前端资源尚未构建。请安装 Node 22.22+,在仓库根目录执行 make build 重新构建 geekTrust。

VPN 和本地代理不受影响,可照常使用。

` @@ -37,7 +38,10 @@ const placeholderPage = ` // ProviderAPI is the narrow provider surface the handlers need; fakes can // implement it for deterministic tests. type ProviderAPI interface { - ActiveSDPC() *sdpc.Client + QueryTrustDevice(context.Context) (*sdpc.TrustDeviceList, error) + TrustDevice(context.Context) error + UntrustDevice(context.Context, []string) error + LogoutTrustDevice(context.Context, string) error TryForceRelogin() (run func(context.Context), ok bool) } @@ -258,22 +262,18 @@ func (s *Server) handleRelogin(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusAccepted, map[string]any{}) } -func (s *Server) activeSC(w http.ResponseWriter) *sdpc.Client { - sc := s.provider.ActiveSDPC() - if sc == nil { - writeError(w, http.StatusServiceUnavailable, "no active session") +func writeDeviceError(w http.ResponseWriter, err error) { + status := http.StatusInternalServerError + if errors.Is(err, runtime.ErrNoSession) || errors.Is(err, session.ErrSessionReplaced) { + status = http.StatusServiceUnavailable } - return sc + writeError(w, status, err.Error()) } func (s *Server) handleTrustList(w http.ResponseWriter, r *http.Request) { - sc := s.activeSC(w) - if sc == nil { - return - } - list, err := sc.QueryTrustDevice(r.Context()) + list, err := s.provider.QueryTrustDevice(r.Context()) if err != nil { - writeError(w, http.StatusInternalServerError, err.Error()) + writeDeviceError(w, err) return } writeJSON(w, http.StatusOK, list) @@ -284,12 +284,8 @@ func (s *Server) handleTrustBind(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusConflict, `trust-device bind requires client authentication mode`) return } - sc := s.activeSC(w) - if sc == nil { - return - } - if err := sc.TrustDevice(r.Context()); err != nil { - writeError(w, http.StatusInternalServerError, err.Error()) + if err := s.provider.TrustDevice(r.Context()); err != nil { + writeDeviceError(w, err) return } writeJSON(w, http.StatusOK, map[string]any{}) @@ -307,12 +303,8 @@ func (s *Server) handleTrustUnbind(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusBadRequest, "ids must not be empty") return } - sc := s.activeSC(w) - if sc == nil { - return - } - if err := sc.UntrustDevice(r.Context(), req.IDs); err != nil { - writeError(w, http.StatusInternalServerError, err.Error()) + if err := s.provider.UntrustDevice(r.Context(), req.IDs); err != nil { + writeDeviceError(w, err) return } writeJSON(w, http.StatusOK, map[string]any{}) @@ -330,12 +322,8 @@ func (s *Server) handleTrustLogout(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusBadRequest, "id must not be empty") return } - sc := s.activeSC(w) - if sc == nil { - return - } - if err := sc.LogoutDevice(r.Context(), req.ID); err != nil { - writeError(w, http.StatusInternalServerError, err.Error()) + if err := s.provider.LogoutTrustDevice(r.Context(), req.ID); err != nil { + writeDeviceError(w, err) return } writeJSON(w, http.StatusOK, map[string]any{}) diff --git a/internal/webui/server_test.go b/internal/webui/server_test.go index a8a8709..c87bbad 100644 --- a/internal/webui/server_test.go +++ b/internal/webui/server_test.go @@ -15,6 +15,7 @@ import ( "testing" "time" + "github.com/ShanghaitechGeekPie/geektrust/internal/runtime" "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" "github.com/ShanghaitechGeekPie/geektrust/internal/session" ) @@ -25,7 +26,30 @@ type fakeProvider struct { runCh chan struct{} } -func (f *fakeProvider) ActiveSDPC() *sdpc.Client { return f.sc } +func (f *fakeProvider) QueryTrustDevice(ctx context.Context) (*sdpc.TrustDeviceList, error) { + if f.sc == nil { + return nil, runtime.ErrNoSession + } + return f.sc.QueryTrustDevice(ctx) +} +func (f *fakeProvider) TrustDevice(ctx context.Context) error { + if f.sc == nil { + return runtime.ErrNoSession + } + return f.sc.TrustDevice(ctx) +} +func (f *fakeProvider) UntrustDevice(ctx context.Context, ids []string) error { + if f.sc == nil { + return runtime.ErrNoSession + } + return f.sc.UntrustDevice(ctx, ids) +} +func (f *fakeProvider) LogoutTrustDevice(ctx context.Context, id string) error { + if f.sc == nil { + return runtime.ErrNoSession + } + return f.sc.LogoutDevice(ctx, id) +} func (f *fakeProvider) TryForceRelogin() (func(context.Context), bool) { if !f.reloginOK.Load() { From c7ad9e41c84855a9c712a0baf1cc64d7fbff3a32 Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Wed, 7 Oct 2026 17:55:58 +0800 Subject: [PATCH 07/28] fix(controller): constrain redirects and validate response envelopes Keep JSON API requests on the controller origin, reject insecure CAS redirects and require the expected shortcut origin. Preserve structured controller errors while rejecting missing status codes and non-success HTTP responses. --- internal/sdpc/cas_origin_regression_test.go | 91 +++++++++++++++++++ internal/sdpc/client.go | 32 +++++-- internal/sdpc/error_response_test.go | 60 +++++++++++++ internal/sdpc/login.go | 7 +- internal/sdpc/redirect_origin_test.go | 97 +++++++++++++++++++++ 5 files changed, 279 insertions(+), 8 deletions(-) create mode 100644 internal/sdpc/cas_origin_regression_test.go create mode 100644 internal/sdpc/error_response_test.go create mode 100644 internal/sdpc/redirect_origin_test.go diff --git a/internal/sdpc/cas_origin_regression_test.go b/internal/sdpc/cas_origin_regression_test.go new file mode 100644 index 0000000..28f1428 --- /dev/null +++ b/internal/sdpc/cas_origin_regression_test.go @@ -0,0 +1,91 @@ +package sdpc + +import ( + "context" + "crypto/tls" + "crypto/x509" + "net/http" + "net/http/httptest" + "net/url" + "sync/atomic" + "testing" +) + +func TestCasTicketRejectsForeignShortcut(t *testing.T) { + for _, status := range []int{http.StatusOK, http.StatusNotFound} { + t.Run(http.StatusText(status), func(t *testing.T) { + foreign := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(status) })) + defer foreign.Close() + controller := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, foreign.URL+"/portal/shortcut.html?data="+url.QueryEscape(`{"ticket":"foreign-ticket"}`), http.StatusFound) + })) + defer controller.Close() + client := NewClient(controller.URL, "Mac", "device", controller.Client()) + client.LoginDomain = "fixture" + if ticket, err := client.CasTicket(context.Background()); err == nil { + t.Fatalf("accepted a foreign shortcut ticket: %q", ticket) + } + }) + } +} + +func TestCasTicketAcceptsControllerShortcutRedirect(t *testing.T) { + controller := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "/portal/shortcut.html?data="+url.QueryEscape(`{"ticket":"controller-ticket"}`), http.StatusFound) + })) + defer controller.Close() + client := NewClient(controller.URL, "Mac", "device", controller.Client()) + client.LoginDomain = "fixture" + ticket, err := client.CasTicket(context.Background()) + if err != nil || ticket != "controller-ticket" { + t.Fatalf("controller shortcut = %q, %v", ticket, err) + } +} + +func TestCasTicketRejectsHTTPSDowngrade(t *testing.T) { + var calls atomic.Int32 + plain := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls.Add(1); w.WriteHeader(http.StatusOK) })) + defer plain.Close() + controller := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, plain.URL+"/login", http.StatusFound) + })) + defer controller.Close() + client := NewClient(controller.URL, "Mac", "device", controller.Client()) + client.LoginDomain = "fixture" + _, err := client.CasTicket(context.Background()) + if err == nil { + t.Fatal("HTTPS downgrade was accepted") + } + if calls.Load() != 0 { + t.Fatal("CAS redirect contacted a plaintext endpoint") + } +} + +func TestCasTicketFollowsHTTPSIdentityProvider(t *testing.T) { + var controllerURL string + identity := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("x-csrf-token") != "" { + t.Error("controller CSRF token reached the identity provider") + } + http.Redirect(w, r, controllerURL+"/portal/shortcut.html?data="+url.QueryEscape(`{"ticket":"controller-ticket"}`), http.StatusFound) + })) + defer identity.Close() + controller := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, identity.URL+"/login", http.StatusFound) + })) + defer controller.Close() + controllerURL = controller.URL + roots := x509.NewCertPool() + roots.AddCert(controller.Certificate()) + roots.AddCert(identity.Certificate()) + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.TLSClientConfig = &tls.Config{RootCAs: roots} + defer transport.CloseIdleConnections() + client := NewClient(controller.URL, "Mac", "device", &http.Client{Transport: transport}) + client.LoginDomain = "fixture" + client.SetCSRF("controller-only") + ticket, err := client.CasTicket(context.Background()) + if err != nil || ticket != "controller-ticket" { + t.Fatalf("HTTPS identity chain = %q, %v", ticket, err) + } +} diff --git a/internal/sdpc/client.go b/internal/sdpc/client.go index e685f59..ac94d08 100644 --- a/internal/sdpc/client.go +++ b/internal/sdpc/client.go @@ -138,7 +138,7 @@ func (c *Client) SID() string { // envelope is the standard controller response wrapper. type envelope struct { - Code int64 `json:"code"` + Code *int64 `json:"code"` Message string `json:"message"` Data json.RawMessage `json:"data"` } @@ -180,7 +180,23 @@ func (c *Client) doJSONWithType(ctx context.Context, method, path, clientType st req.Header.Set("Content-Type", "application/json;charset=utf-8") } - resp, err := c.HTTP.Do(req) + // JSON API calls stay on the controller origin. Cross-origin navigation + // belongs to CasTicket; following it here could forward CSRF or POST data. + hc := *c.HTTP + checkRedirect := hc.CheckRedirect + hc.CheckRedirect = func(r *http.Request, via []*http.Request) error { + if r.URL.Scheme != req.URL.Scheme || r.URL.Host != req.URL.Host { + return errors.New("controller redirect outside origin") + } + if checkRedirect != nil { + return checkRedirect(r, via) + } + if len(via) >= 10 { + return errors.New("controller redirect limit") + } + return nil + } + resp, err := hc.Do(req) if err != nil { return fmt.Errorf("sdpc %s: %w", path, err) } @@ -189,7 +205,11 @@ func (c *Client) doJSONWithType(ctx context.Context, method, path, clientType st if err != nil { return fmt.Errorf("sdpc %s: read response: %w", path, err) } - if resp.StatusCode >= 400 { + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + var apiErr *APIError + if err := parseEnvelopeInto(raw, path, nil); errors.As(err, &apiErr) { + return apiErr + } return fmt.Errorf("sdpc %s: HTTP %d", path, resp.StatusCode) } @@ -204,11 +224,11 @@ func parseEnvelope(raw []byte, out any) error { func parseEnvelopeInto(raw []byte, op string, out any) error { var env envelope - if err := json.Unmarshal(raw, &env); err != nil { + if err := json.Unmarshal(raw, &env); err != nil || env.Code == nil { return fmt.Errorf("sdpc %s: invalid response envelope", op) } - if env.Code != CodeOK { - return &APIError{Op: op, Code: env.Code, Message: env.Message} + if *env.Code != CodeOK { + return &APIError{Op: op, Code: *env.Code, Message: env.Message} } if out != nil && len(env.Data) > 0 && string(env.Data) != "null" { if err := json.Unmarshal(env.Data, out); err != nil { diff --git a/internal/sdpc/error_response_test.go b/internal/sdpc/error_response_test.go new file mode 100644 index 0000000..33d7964 --- /dev/null +++ b/internal/sdpc/error_response_test.go @@ -0,0 +1,60 @@ +package sdpc + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestHTTPErrorPreservesSessionExpiryCode(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusUnauthorized) + fmt.Fprintf(w, `{"code":%d,"message":"expired"}`, CodeSessionMissing) + })) + defer server.Close() + c := NewClient(server.URL, "Mac", "device", server.Client()) + _, err := c.OnlineInfo(context.Background()) + var api *APIError + if !IsSessionExpired(err) || !errors.As(err, &api) || api.Code != CodeSessionMissing { + t.Fatalf("HTTP error lost its controller code: %v", err) + } +} + +func TestHTTPErrorWithoutEnvelopeKeepsStatus(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "unavailable", http.StatusServiceUnavailable) + })) + defer server.Close() + c := NewClient(server.URL, "Mac", "device", server.Client()) + _, err := c.OnlineInfo(context.Background()) + if err == nil || !strings.Contains(err.Error(), "HTTP 503") { + t.Fatalf("unexpected error: %v", err) + } +} + +func TestMissingResponseCodeIsNotSuccess(t *testing.T) { + if err := parseEnvelope([]byte(`{"data":{}}`), nil); err == nil { + t.Fatal("missing controller code treated as success") + } +} + +func TestRedirectStatusIsNotAPISuccess(t *testing.T) { + for _, status := range []int{http.StatusMultipleChoices, http.StatusTemporaryRedirect} { + t.Run(http.StatusText(status), func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(status) + fmt.Fprint(w, `{"code":0}`) + })) + defer server.Close() + client := NewClient(server.URL, "Mac", "device", server.Client()) + err := client.SessionIDExchange(context.Background(), "fixture-ticket") + if err == nil || !strings.Contains(err.Error(), fmt.Sprintf("HTTP %d", status)) { + t.Fatalf("non-success HTTP status was ignored: %v", err) + } + }) + } +} diff --git a/internal/sdpc/login.go b/internal/sdpc/login.go index bcf2ec6..7ba8723 100644 --- a/internal/sdpc/login.go +++ b/internal/sdpc/login.go @@ -47,6 +47,9 @@ func (c *Client) CasTicket(ctx context.Context) (string, error) { var shortcutURL *url.URL noFollow := *c.HTTP noFollow.CheckRedirect = func(r *http.Request, via []*http.Request) error { + if base.Scheme == "https" && r.URL.Scheme != "https" { + return errors.New("cas chain: insecure redirect") + } if r.URL.Host == base.Host && r.URL.Scheme == base.Scheme && r.URL.Path == "/portal/shortcut.html" { shortcutURL = r.URL return http.ErrUseLastResponse @@ -79,8 +82,8 @@ func (c *Client) CasTicket(ctx context.Context) (string, error) { resp.Body.Close() if shortcutURL == nil { - // Some deployments serve shortcut.html directly as the final 200. - if resp.Request != nil && resp.Request.URL.Path == "/portal/shortcut.html" { + // Some controllers serve shortcut.html directly as the final 200. + if resp.StatusCode == http.StatusOK && resp.Request != nil && resp.Request.URL.Host == base.Host && resp.Request.URL.Scheme == base.Scheme && resp.Request.URL.Path == "/portal/shortcut.html" { shortcutURL = resp.Request.URL } } diff --git a/internal/sdpc/redirect_origin_test.go b/internal/sdpc/redirect_origin_test.go new file mode 100644 index 0000000..3968ad9 --- /dev/null +++ b/internal/sdpc/redirect_origin_test.go @@ -0,0 +1,97 @@ +package sdpc + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" +) + +func TestControllerAPIRejectsForeignRedirects(t *testing.T) { + for _, status := range []int{http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect} { + t.Run(http.StatusText(status), func(t *testing.T) { + var foreignCalls atomic.Int32 + foreign := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + foreignCalls.Add(1) + w.Write([]byte(`{"code":0}`)) + })) + defer foreign.Close() + controller := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, foreign.URL+"/collect", status) + })) + defer controller.Close() + client := NewClient(controller.URL, "Mac", "device", controller.Client()) + client.SetCSRF("controller-only") + if err := client.SessionIDExchange(context.Background(), "controller-only-ticket"); err == nil { + t.Error("foreign response was accepted as controller success") + } + if foreignCalls.Load() != 0 { + t.Fatal("controller API contacted a foreign origin") + } + }) + } +} + +func TestControllerAPIRejectsHTTPSDowngrade(t *testing.T) { + var plainCalls atomic.Int32 + plain := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + plainCalls.Add(1) + w.Write([]byte(`{"code":0}`)) + })) + defer plain.Close() + controller := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, plain.URL+"/collect", http.StatusTemporaryRedirect) + })) + defer controller.Close() + client := NewClient(controller.URL, "Mac", "device", controller.Client()) + if err := client.SessionIDExchange(context.Background(), "controller-only-ticket"); err == nil { + t.Error("HTTPS downgrade was accepted") + } + if plainCalls.Load() != 0 { + t.Fatal("controller API contacted a plaintext endpoint") + } +} + +func TestControllerAPIFollowsSameOriginRedirect(t *testing.T) { + controller := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/result" { + http.Redirect(w, r, "/result", http.StatusTemporaryRedirect) + return + } + if r.Method != http.MethodPost || r.Header.Get("x-csrf-token") != "controller-only" { + t.Error("same-origin redirect lost method or CSRF header") + } + w.Write([]byte(`{"code":0}`)) + })) + defer controller.Close() + client := NewClient(controller.URL, "Mac", "device", controller.Client()) + client.SetCSRF("controller-only") + if err := client.SessionIDExchange(context.Background(), "controller-only-ticket"); err != nil { + t.Fatal(err) + } +} + +func TestControllerAPIPreservesCallerRedirectRejection(t *testing.T) { + var finalCalls atomic.Int32 + controller := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/result" { + finalCalls.Add(1) + w.Write([]byte(`{"code":0}`)) + return + } + http.Redirect(w, r, "/result", http.StatusTemporaryRedirect) + })) + defer controller.Close() + rejected := errors.New("caller rejected redirect") + hc := controller.Client() + hc.CheckRedirect = func(*http.Request, []*http.Request) error { return rejected } + client := NewClient(controller.URL, "Mac", "device", hc) + if err := client.SessionIDExchange(context.Background(), "controller-only-ticket"); !errors.Is(err, rejected) { + t.Fatalf("caller rejection lost: %v", err) + } + if finalCalls.Load() != 0 { + t.Fatal("caller-rejected redirect was followed") + } +} From e24a806bc66d2394bfa9d453c953e8fb84b4a3f7 Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Wed, 7 Oct 2026 17:56:17 +0800 Subject: [PATCH 08/28] fix(tunnel): preserve framed TCP reads, writes and close semantics Retain partial headers and payloads across read timeouts, deliver partial application data before truncation errors, and keep remote EOF sticky. Report actual payload bytes on failed writes and unblock blocked writers during Close. --- internal/tunnel/tcp.go | 129 ++++++++----- internal/tunnel/tcp_close_regression_test.go | 74 ++++++++ internal/tunnel/tcp_read_regression_test.go | 181 +++++++++++++++++++ internal/tunnel/tcp_write_regression_test.go | 53 ++++++ 4 files changed, 394 insertions(+), 43 deletions(-) create mode 100644 internal/tunnel/tcp_close_regression_test.go create mode 100644 internal/tunnel/tcp_read_regression_test.go create mode 100644 internal/tunnel/tcp_write_regression_test.go diff --git a/internal/tunnel/tcp.go b/internal/tunnel/tcp.go index cd8cb39..807983c 100644 --- a/internal/tunnel/tcp.go +++ b/internal/tunnel/tcp.go @@ -361,6 +361,10 @@ func readTCPProtocolResponse(reader io.Reader) error { if _, err := io.ReadFull(reader, body); err != nil { return fmt.Errorf("direct TCP protocol response: %w", err) } + return parseTCPProtocolResponse(body) +} + +func parseTCPProtocolResponse(body []byte) error { if string(body) == "OK" { return nil } @@ -416,9 +420,11 @@ type tcpTunnelConn struct { conn net.Conn reader *bufio.Reader - readMu sync.Mutex - readBuf []byte - writeMu sync.Mutex + readMu sync.Mutex + readRemaining int + readControl []byte + readClosed bool + writeMu sync.Mutex // writeClosed is protected by writeMu. The protocol close frame half-closes // the target write direction while the TLS connection remains readable. writeClosed bool @@ -434,48 +440,66 @@ func (c *tcpTunnelConn) Read(p []byte) (int, error) { } c.readMu.Lock() defer c.readMu.Unlock() - if len(c.readBuf) > 0 { - n := copy(p, c.readBuf) - c.readBuf = c.readBuf[n:] - return n, nil + if c.readClosed { + return 0, io.EOF } for { - var header [2]byte - if _, err := io.ReadFull(c.reader, header[:]); err != nil { - return 0, err - } - switch header { - case [2]byte{0x01, 0x00}: - var length [2]byte - if _, err := io.ReadFull(c.reader, length[:]); err != nil { + if c.readControl != nil { + offset := len(c.readControl) - c.readRemaining + n, err := io.ReadFull(c.reader, c.readControl[offset:]) + c.readRemaining -= n + if err != nil { + if err == io.EOF && c.readRemaining > 0 { + err = io.ErrUnexpectedEOF + } return 0, err } - frameLength := int(binary.BigEndian.Uint16(length[:])) - if frameLength == 0 { - continue + err = parseTCPProtocolResponse(c.readControl) + c.readControl = nil + if err != nil { + return 0, err } - if frameLength <= len(p) { - return io.ReadFull(c.reader, p[:frameLength]) + continue + } + if c.readRemaining > 0 { + n, err := c.reader.Read(p[:min(len(p), c.readRemaining)]) + c.readRemaining -= n + if err == io.EOF && c.readRemaining > 0 { + err = io.ErrUnexpectedEOF } - data := make([]byte, frameLength) - if _, err := io.ReadFull(c.reader, data); err != nil { - return 0, err + return n, err + } + // Peek retains a partial header across a retryable read timeout. + header, err := c.reader.Peek(2) + if err != nil { + if err == io.EOF && len(header) > 0 { + err = io.ErrUnexpectedEOF } - n := copy(p, data) - c.readBuf = data[n:] - return n, nil - case [2]byte{0x01, 0x01}: - var trailer [2]byte - if _, err := io.ReadFull(c.reader, trailer[:]); err != nil { - return 0, err + return 0, err + } + kind := [2]byte{header[0], header[1]} + if kind != [2]byte{0x01, 0x00} && kind != [2]byte{0x01, 0x01} && kind != [2]byte{0x53, 0x00} { + return 0, fmt.Errorf("unexpected direct TCP frame 0x%02x 0x%02x", header[0], header[1]) + } + header, err = c.reader.Peek(4) + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF } + return 0, err + } + switch kind { + case [2]byte{0x01, 0x00}: + c.readRemaining = int(binary.BigEndian.Uint16(header[2:4])) + c.reader.Discard(4) + case [2]byte{0x01, 0x01}: + c.reader.Discard(4) + c.readClosed = true return 0, io.EOF case [2]byte{0x53, 0x00}: - if err := readTCPProtocolResponse(c.reader); err != nil { - return 0, err - } - default: - return 0, fmt.Errorf("unexpected direct TCP frame 0x%02x 0x%02x", header[0], header[1]) + c.readRemaining = int(binary.BigEndian.Uint16(header[2:4])) + c.readControl = make([]byte, c.readRemaining) + c.reader.Discard(4) } } } @@ -496,8 +520,12 @@ func (c *tcpTunnelConn) Write(p []byte) (int, error) { frame[0], frame[1] = 0x01, 0x00 binary.BigEndian.PutUint16(frame[2:4], uint16(size)) copy(frame[4:], p[:size]) - if err := writeTCPFrame(c.conn, frame); err != nil { - return written, err + n, err := writeTCPFrame(c.conn, frame) + if err != nil { + // A partial frame cannot be resumed with a new header. + c.writeClosed, c.closeWriteErr = true, err + c.conn.Close() + return written + max(0, n-4), err } written += size p = p[size:] @@ -505,20 +533,22 @@ func (c *tcpTunnelConn) Write(p []byte) (int, error) { return written, nil } -func writeTCPFrame(w io.Writer, frame []byte) error { +func writeTCPFrame(w io.Writer, frame []byte) (int, error) { + written := 0 for len(frame) > 0 { n, err := w.Write(frame) if n > 0 { + written += n frame = frame[n:] } if err != nil { - return err + return written, err } if n == 0 { - return io.ErrNoProgress + return written, io.ErrNoProgress } } - return nil + return written, nil } // CloseWrite sends the stream close frame without closing the TLS socket, so @@ -526,18 +556,31 @@ func writeTCPFrame(w io.Writer, frame []byte) error { func (c *tcpTunnelConn) CloseWrite() error { c.writeMu.Lock() defer c.writeMu.Unlock() + return c.closeWriteLocked() +} + +func (c *tcpTunnelConn) closeWriteLocked() error { if c.writeClosed { return c.closeWriteErr } c.writeClosed = true _ = c.conn.SetWriteDeadline(time.Now().Add(tcpCloseTimeout)) - c.closeWriteErr = writeTCPFrame(c.conn, []byte{0x01, 0x01, 0x00, 0x00}) + _, c.closeWriteErr = writeTCPFrame(c.conn, []byte{0x01, 0x01, 0x00, 0x00}) + if c.closeWriteErr != nil { + c.conn.Close() + } return c.closeWriteErr } func (c *tcpTunnelConn) Close() error { c.closeOnce.Do(func() { - writeErr := c.CloseWrite() + // Close must unblock a Write waiting on the socket. Send a graceful + // close frame only when no writer currently owns the framed stream. + var writeErr error + if c.writeMu.TryLock() { + writeErr = c.closeWriteLocked() + c.writeMu.Unlock() + } closeErr := c.conn.Close() if writeErr != nil { c.closeErr = writeErr diff --git a/internal/tunnel/tcp_close_regression_test.go b/internal/tunnel/tcp_close_regression_test.go new file mode 100644 index 0000000..21bfa72 --- /dev/null +++ b/internal/tunnel/tcp_close_regression_test.go @@ -0,0 +1,74 @@ +package tunnel + +import ( + "bufio" + "bytes" + "io" + "net" + "sync" + "testing" + "time" +) + +type writeStartedConn struct { + net.Conn + started chan struct{} + once sync.Once +} + +func TestTCPStreamCloseSendsGracefulFrame(t *testing.T) { + client, peer := net.Pipe() + defer client.Close() + defer peer.Close() + stream := &tcpTunnelConn{conn: client, reader: bufio.NewReader(client)} + closed := make(chan error, 1) + go func() { closed <- stream.Close() }() + peer.SetReadDeadline(time.Now().Add(time.Second)) + var frame [4]byte + if _, err := io.ReadFull(peer, frame[:]); err != nil { + t.Fatal(err) + } + if !bytes.Equal(frame[:], []byte{0x01, 0x01, 0x00, 0x00}) { + t.Fatal("normal Close omitted the graceful close frame") + } + if err := <-closed; err != nil { + t.Fatal(err) + } + if err := stream.Close(); err != nil { + t.Fatal(err) + } +} + +func (c *writeStartedConn) Write(b []byte) (int, error) { + c.once.Do(func() { close(c.started) }) + return c.Conn.Write(b) +} + +func TestTCPStreamCloseUnblocksStalledWrite(t *testing.T) { + client, peer := net.Pipe() + defer client.Close() + defer peer.Close() + observed := &writeStartedConn{Conn: client, started: make(chan struct{})} + stream := &tcpTunnelConn{conn: observed, reader: bufio.NewReader(observed)} + written := make(chan error, 1) + go func() { _, err := stream.Write([]byte("payload")); written <- err }() + <-observed.started + closed := make(chan error, 1) + go func() { closed <- stream.Close() }() + select { + case err := <-closed: + if err != nil { + t.Fatal(err) + } + case <-time.After(time.Second): + t.Fatal("Close waited on a stalled Write instead of closing the socket") + } + select { + case err := <-written: + if err == nil { + t.Fatal("stalled Write did not fail after Close") + } + case <-time.After(time.Second): + t.Fatal("Close did not unblock Write") + } +} diff --git a/internal/tunnel/tcp_read_regression_test.go b/internal/tunnel/tcp_read_regression_test.go new file mode 100644 index 0000000..3eb1289 --- /dev/null +++ b/internal/tunnel/tcp_read_regression_test.go @@ -0,0 +1,181 @@ +package tunnel + +import ( + "bufio" + "bytes" + "encoding/binary" + "errors" + "io" + "net" + "os" + "strconv" + "strings" + "testing" + "time" +) + +func TestTCPStreamReadKeepsRemoteEOF(t *testing.T) { + client, peer := net.Pipe() + defer client.Close() + defer peer.Close() + stream := &tcpTunnelConn{conn: client, reader: bufio.NewReader(client)} + go peer.Write([]byte{0x01, 0x01, 0, 0}) + if _, err := stream.Read(make([]byte, 1)); !errors.Is(err, io.EOF) { + t.Fatal(err) + } + stream.SetReadDeadline(time.Now().Add(50 * time.Millisecond)) + if _, err := stream.Read(make([]byte, 1)); !errors.Is(err, io.EOF) { + t.Fatalf("second read after remote EOF = %v", err) + } +} + +func TestTCPStreamReadAcrossFrameBoundaries(t *testing.T) { + payload := bytes.Repeat([]byte("stream-data"), 6000) + for _, readSize := range []int{1, 31, 65536} { + t.Run(strconv.Itoa(readSize), func(t *testing.T) { + client, peer := net.Pipe() + defer client.Close() + defer peer.Close() + stream := &tcpTunnelConn{conn: client, reader: bufio.NewReader(client)} + go func() { + // Empty data frames and protocol responses carry no application data. + peer.Write([]byte{0x01, 0x00, 0, 0, 0x53, 0x00, 0, 2, 'O', 'K'}) + for remaining := payload; len(remaining) > 0; { + n := min(len(remaining), 65535) + header := binary.BigEndian.AppendUint16([]byte{0x01, 0x00}, uint16(n)) + peer.Write(append(header, remaining[:n]...)) + remaining = remaining[n:] + } + peer.Write([]byte{0x01, 0x01, 0, 0}) + }() + stream.SetReadDeadline(time.Now().Add(3 * time.Second)) + var got []byte + buffer := make([]byte, readSize) + for { + n, err := stream.Read(buffer) + got = append(got, buffer[:n]...) + if err != nil { + if !errors.Is(err, io.EOF) { + t.Fatal(err) + } + break + } + } + if !bytes.Equal(got, payload) { + t.Fatal("application bytes changed across frame boundaries") + } + }) + } +} + +func TestTCPStreamReadRejectsInvalidHeader(t *testing.T) { + client, peer := net.Pipe() + defer client.Close() + defer peer.Close() + stream := &tcpTunnelConn{conn: client, reader: bufio.NewReader(client)} + go peer.Write([]byte{0xff, 0xff}) + stream.SetReadDeadline(time.Now().Add(time.Second)) + if _, err := stream.Read(make([]byte, 1)); err == nil || !strings.Contains(err.Error(), "unexpected direct TCP frame") { + t.Fatalf("invalid header = %v", err) + } +} + +func TestTCPStreamReadRejectsTruncatedFrame(t *testing.T) { + for _, header := range [][]byte{{0x01}, {0x01, 0x00, 0x00}, {0x53, 0x00, 0x00, 3}, {0x53, 0x00, 0x00, 3, 'O'}} { + client, peer := net.Pipe() + stream := &tcpTunnelConn{conn: client, reader: bufio.NewReader(client)} + go func() { peer.Write(header); peer.Close() }() + _, err := stream.Read(make([]byte, 1)) + client.Close() + if !errors.Is(err, io.ErrUnexpectedEOF) { + t.Fatalf("truncated header = %v", err) + } + } +} + +func TestTCPStreamReadPreservesTruncatedPayload(t *testing.T) { + client, peer := net.Pipe() + defer client.Close() + defer peer.Close() + stream := &tcpTunnelConn{conn: client, reader: bufio.NewReader(client)} + go func() { + peer.Write([]byte{0x01, 0x00, 0, 10, 'h', 'e', 'l', 'l', 'o'}) + peer.Close() + }() + var got []byte + buffer := make([]byte, 2) + for { + n, err := stream.Read(buffer) + got = append(got, buffer[:n]...) + if err != nil { + if !errors.Is(err, io.ErrUnexpectedEOF) { + t.Fatal(err) + } + break + } + } + if string(got) != "hello" { + t.Fatalf("partial stream data lost: %q", got) + } +} + +func TestTCPStreamReadResumesAfterHeaderTimeout(t *testing.T) { + client, peer := net.Pipe() + defer client.Close() + defer peer.Close() + stream := &tcpTunnelConn{conn: client, reader: bufio.NewReader(client)} + go peer.Write([]byte{0x01}) + stream.SetReadDeadline(time.Now().Add(50 * time.Millisecond)) + if _, err := stream.Read(make([]byte, 1)); !errors.Is(err, os.ErrDeadlineExceeded) { + t.Fatal(err) + } + stream.SetReadDeadline(time.Now().Add(time.Second)) + go peer.Write([]byte{0x00, 0, 1, 'x'}) + var payload [1]byte + if _, err := io.ReadFull(stream, payload[:]); err != nil || payload[0] != 'x' { + t.Fatalf("read after header timeout = %q, %v", payload, err) + } +} + +func TestTCPStreamReadResumesAfterPayloadTimeout(t *testing.T) { + client, peer := net.Pipe() + defer client.Close() + defer peer.Close() + stream := &tcpTunnelConn{conn: client, reader: bufio.NewReader(client)} + go peer.Write([]byte{0x01, 0x00, 0, 1}) + stream.SetReadDeadline(time.Now().Add(50 * time.Millisecond)) + if _, err := stream.Read(make([]byte, 1)); !errors.Is(err, os.ErrDeadlineExceeded) { + t.Fatal(err) + } + stream.SetReadDeadline(time.Now().Add(time.Second)) + go peer.Write([]byte{'x'}) + var payload [1]byte + if _, err := io.ReadFull(stream, payload[:]); err != nil || payload[0] != 'x' { + t.Fatalf("read after payload timeout = %q, %v", payload, err) + } +} + +func TestTCPStreamReadResumesControlResponse(t *testing.T) { + client, peer := net.Pipe() + defer client.Close() + defer peer.Close() + stream := &tcpTunnelConn{conn: client, reader: bufio.NewReader(client)} + // A control response can be larger than the reader buffer and interrupted. + control := append([]byte(`{"code":0,"message":"`), make([]byte, 5000)...) + for i := len(`{"code":0,"message":"`); i < len(control); i++ { + control[i] = 'a' + } + control = append(control, []byte(`"}`)...) + header := binary.BigEndian.AppendUint16([]byte{0x53, 0x00}, uint16(len(control))) + go peer.Write(append(header, control[:200]...)) + stream.SetReadDeadline(time.Now().Add(50 * time.Millisecond)) + if _, err := stream.Read(make([]byte, 1)); !errors.Is(err, os.ErrDeadlineExceeded) { + t.Fatal(err) + } + stream.SetReadDeadline(time.Now().Add(time.Second)) + go peer.Write(append(control[200:], 0x01, 0x00, 0, 1, 'x')) + var payload [1]byte + if _, err := io.ReadFull(stream, payload[:]); err != nil || payload[0] != 'x' { + t.Fatalf("read after control timeout = %q, %v", payload, err) + } +} diff --git a/internal/tunnel/tcp_write_regression_test.go b/internal/tunnel/tcp_write_regression_test.go new file mode 100644 index 0000000..4dc11c0 --- /dev/null +++ b/internal/tunnel/tcp_write_regression_test.go @@ -0,0 +1,53 @@ +package tunnel + +import ( + "bufio" + "errors" + "io" + "net" + "os" + "testing" + "time" +) + +type partialFrameConn struct { + net.Conn + failed bool +} + +func (c *partialFrameConn) Write(b []byte) (int, error) { + if !c.failed { + c.failed = true + n, err := c.Conn.Write(b[:min(5, len(b))]) + if err != nil { + return n, err + } + return n, os.ErrDeadlineExceeded + } + return c.Conn.Write(b) +} + +func TestTCPStreamWriteFailureClosesBrokenFrame(t *testing.T) { + client, peer := net.Pipe() + defer client.Close() + defer peer.Close() + raw := &partialFrameConn{Conn: client} + stream := &tcpTunnelConn{conn: raw, reader: bufio.NewReader(raw)} + received := make(chan []byte, 1) + go func() { b, _ := io.ReadAll(peer); received <- b }() + if n, err := stream.Write([]byte("abc")); n != 1 || !errors.Is(err, os.ErrDeadlineExceeded) { + t.Fatalf("partial Write = %d, %v; want the one application byte already sent", n, err) + } + stream.SetWriteDeadline(time.Now().Add(time.Second)) + if _, err := stream.Write([]byte("next")); !errors.Is(err, net.ErrClosed) { + t.Fatalf("new frame accepted after a partial write: %v", err) + } + select { + case b := <-received: + if len(b) != 5 { + t.Fatalf("broken stream received additional bytes: %d", len(b)) + } + case <-time.After(time.Second): + t.Fatal("partial frame failure did not close the socket") + } +} From 802b92070877ba0e49869afa97488556de7dbf8e Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Wed, 7 Oct 2026 17:56:35 +0800 Subject: [PATCH 09/28] feat(web): rebuild panel with shadcn UI and selectable themes Add light, dark and system themes, proxy address copying, compact connection details and trusted device controls. Show ten recent activities with a full history dialog, cover API and interaction regressions, and run panel tests in CI. --- .github/workflows/ci.yml | 4 +- .github/workflows/release.yml | 3 +- README.md | 6 +- docs/WEBUI.md | 17 +- internal/webui/hub.go | 71 +- internal/webui/hub_test.go | 20 + web/components.json | 25 + web/index.html | 16 +- web/package-lock.json | 4207 +++++++++++++++++++-- web/package.json | 23 +- web/src/App.tsx | 173 +- web/src/api.test.tsx | 64 + web/src/api.ts | 16 +- web/src/components/ConfirmDialog.tsx | 54 + web/src/components/CopyButton.tsx | 56 + web/src/components/ErrorText.tsx | 40 +- web/src/components/EventsList.tsx | 150 +- web/src/components/ProxyCards.tsx | 48 + web/src/components/SmsDialog.tsx | 237 +- web/src/components/StatusCard.tsx | 91 +- web/src/components/ThemeProvider.test.tsx | 83 + web/src/components/ThemeProvider.tsx | 54 + web/src/components/ThemeToggle.tsx | 47 + web/src/components/TrustDevices.tsx | 529 ++- web/src/components/UserCard.tsx | 146 +- web/src/components/interactions.test.tsx | 222 ++ web/src/components/ui/alert-dialog.tsx | 199 + web/src/components/ui/button.tsx | 66 + web/src/components/ui/card.tsx | 102 + web/src/components/ui/checkbox.tsx | 31 + web/src/components/ui/dialog.tsx | 165 + web/src/components/ui/dropdown-menu.tsx | 270 ++ web/src/components/ui/input-otp.tsx | 85 + web/src/components/ui/table.tsx | 113 + web/src/lib/utils.ts | 1 + web/src/main.tsx | 5 +- web/src/shadcn.css | 6 + web/src/styles.css | 514 +-- web/src/test/setup.ts | 10 + web/src/types.ts | 1 + web/tsconfig.json | 6 +- web/vite.config.ts | 5 +- web/vitest.config.ts | 12 + 43 files changed, 6832 insertions(+), 1161 deletions(-) create mode 100644 web/components.json create mode 100644 web/src/api.test.tsx create mode 100644 web/src/components/ConfirmDialog.tsx create mode 100644 web/src/components/CopyButton.tsx create mode 100644 web/src/components/ProxyCards.tsx create mode 100644 web/src/components/ThemeProvider.test.tsx create mode 100644 web/src/components/ThemeProvider.tsx create mode 100644 web/src/components/ThemeToggle.tsx create mode 100644 web/src/components/interactions.test.tsx create mode 100644 web/src/components/ui/alert-dialog.tsx create mode 100644 web/src/components/ui/button.tsx create mode 100644 web/src/components/ui/card.tsx create mode 100644 web/src/components/ui/checkbox.tsx create mode 100644 web/src/components/ui/dialog.tsx create mode 100644 web/src/components/ui/dropdown-menu.tsx create mode 100644 web/src/components/ui/input-otp.tsx create mode 100644 web/src/components/ui/table.tsx create mode 100644 web/src/lib/utils.ts create mode 100644 web/src/shadcn.css create mode 100644 web/src/test/setup.ts create mode 100644 web/vitest.config.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e7a1882..70be5af 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,11 +20,13 @@ jobs: cache: true - uses: actions/setup-node@v6 with: - node-version: 20 + node-version: 22 cache: npm cache-dependency-path: web/package-lock.json - name: Build panel run: npm --prefix web ci && npm --prefix web run build + - name: Panel regression tests + run: npm --prefix web test - name: Unit and integration tests run: go test ./... - name: Race detector diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1c78eee..9c24e86 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -33,7 +33,7 @@ jobs: - name: Set up Node.js uses: actions/setup-node@v6 with: - node-version: 20 + node-version: 22 cache: npm cache-dependency-path: web/package-lock.json @@ -47,6 +47,7 @@ jobs: - name: Test run: | + npm --prefix web test go test ./... go vet ./... diff --git a/README.md b/README.md index 3bf6193..6bd624f 100644 --- a/README.md +++ b/README.md @@ -18,13 +18,13 @@ geekTrust 是 aTrust VPN 的纯用户态客户端。它不创建虚拟网卡、 ## 快速开始 -从源码构建需要 Go 1.24+: +从源码构建需要 Go 1.26.8+: ```sh go build -o geektrust ./cmd/geektrust ``` -这样构建的二进制可以正常使用,但 Web 面板只显示构建提示页。需要完整面板时,安装 Node 20+ 后执行: +这样构建的二进制可以正常使用,但 Web 面板只显示构建提示页。需要完整面板时,安装 Node 22.22+ 后执行: ```sh make build @@ -100,7 +100,7 @@ keystore = "./ids-passkey.keystore" 相对路径以配置文件目录为准。设备身份和加密会话放在平台用户持久目录;上科大必需的网关证书域名由程序提供,证书验证继续开启。普通用户无需填写应用 ID、网关 IP 或协议回退开关。 -配置按 `controller`、`auth`、`proxy`、`web`、`dns`、`storage`、`logging` 分组。监听地址省略时采用默认值,空字符串表示禁用。`auth.mode` 支持 `auto`、`client`、`browser`;browser 模式不能绑定授信终端。 +配置按 `controller`、`auth`、`proxy`、`web`、`dns`、`storage`、`logging` 分组。监听地址省略时采用默认值,空字符串表示禁用。`controller.compatibility` 选择 `auto`、`shanghaitech`、`ecnu` 或 `generic`;它用于控制器兼容适配。`auth.mode` 支持 `auto`、`client`、`browser`;browser 模式不能绑定授信终端。 旧格式继续可读,不自动重写。检查和迁移命令: diff --git a/docs/WEBUI.md b/docs/WEBUI.md index 27e377e..5c548be 100644 --- a/docs/WEBUI.md +++ b/docs/WEBUI.md @@ -324,7 +324,7 @@ sessionActive → online | 字段 | 规则 | |---|---| -| `device_id`、`client_type`、`proxy` | 静态配置,始终存在 | +| `device_id`、`client_type`、`controller_host`、`proxy` | 静态配置,始终存在 | | `user`、`gateways`、`dns` | 仅 `sessionActive` 时存在(来自最近一次 `SessionInfo` 的深拷贝);否则 null | | `since` | 最近一次**状态值**变化的时间 | | `last_error` | `login_failed` 设置;`login_start`、`login_success`、`restore_success` 清空 | @@ -341,6 +341,7 @@ sessionActive → online "user": { "username": "2020000000", "display_name": "张三", "client_ip": "10.0.0.2" }, "device_id": "0123456789ABCDEF0123456789ABCDEF", "client_type": "client", + "controller_host": "vpn.shanghaitech.edu.cn", "gateways": ["119.78.254.241:441"], "dns": ["10.15.44.11"], "proxy": { "socks5": "127.0.0.1:1080", "http": "127.0.0.1:8080" }, @@ -476,17 +477,19 @@ web/ src/ main.tsx App.tsx api.ts types.ts errors.ts styles.css components/ - StatusCard.tsx 状态灯 + since + last_error - UserCard.tsx 用户信息 + device_id(复制按钮) + client_type + 代理入口 + StatusCard.tsx 连接状态 + 登录操作 + last_error + UserCard.tsx 账号 + 控制器地址 + 连接详情弹窗 + ProxyCards.tsx SOCKS5/HTTP 地址 + 复制按钮 + ThemeToggle.tsx 图标主题菜单:浅色/深色/跟随系统 SmsDialog.tsx 弹窗:6 位输入、60s 倒计时、重新发送、错误内联 TrustDevices.tsx 表格 + 绑定/取消授信/注销;browser 模式仅禁用「绑定本机」 - EventsList.tsx 最近事件流(新→旧) + EventsList.tsx 最近 10 条活动 + 完整记录弹窗 ErrorText.tsx 错误摘要 + 「详情」展开原始错误链 ``` - `package-lock.json` 提交到 git(`npm ci` 可重现构建)。 - 数据层 `api.ts`:fetch + `EventSource`;单例 store(`useSyncExternalStore`),不引入状态库。 -- 无路由,单页。UI 文案中文。样式手写 CSS,深浅色按 `prefers-color-scheme`。 +- 无路由,单页。UI 文案中文。界面使用 shadcn/ui(Radix)和 Tailwind CSS;图标主题菜单支持浅色、深色、跟随系统,并持久保存选择。 - 短信弹窗:`state === "sms_required"` 时自动弹出、输入框自动聚焦;提交时携带当前 `sms_gen`;提交后进入"验证中"等待状态推送;60 秒倒计时仅作提示(客户端计时)。重发发现认证会话过期时显示正在重建会话,旧代关闭后由新 `sms_gen` 重置表单并接收新验证码。 - 错误展示 `errors.ts`:后端传来的是 Go 错误链(`check sms code: sdpc checkSms: code 75500403: 验证码错误`), 直接渲染会让面板显得像坏了。`friendlyError()` 依次尝试:控制面错误码表(TECHNICAL.md §11.1)→ 网络/TLS 特征 → @@ -494,7 +497,7 @@ web/ 未收录的错误码(如 75500403)不臆造语义,直接采用控制器自己的中文消息。 一次性 API 请求的错误经 `api.ts` 的 `errorText()` 处理:调用处按状态码覆盖 → 面板自身拒绝(400/403/404/405)的中文默认文案 → `friendlyError()` 摘要 → 兜底文案。完全不含中文的错误链不作为摘要显示,改用调用处的中文兜底文案;原文一律放进「详情」。 -- 连接断开时状态灯置灰并停止呼吸动画(`.pill.stale`):快照已不再刷新,绿灯不能继续冒充实时。 +- 面板连接断开时显示离线状态和重连提示,并禁用会改变会话或设备的操作。 - 授信终端在 browser 模式下**不整卡禁用**:服务端只拒绝绑定(`handleTrustBind` 的 `client_type` 前置检查, 对应控制器 75500000),查询/取消授信/注销在任何会话都可用。实测 browser 会话 `GET /api/trust-devices` 返回 200 且 `selfId` 就在列表里——纯 web 登录同样会被记为授信终端。因此只禁用「绑定当前设备」按钮, @@ -548,7 +551,7 @@ build: web ### 9.3 页面布局 -单栏卡片流,最大宽度 960px 居中:顶栏(标题 + 状态灯:绿 online / 黄 connecting、sms_required / 灰 offline)→ `StatusCard`(含 `重新登录` 按钮,二次确认;409 时提示已有登录正在进行)+ `UserCard`(并排,窄屏堆叠)→ `TrustDevices`(browser 模式附说明)→ `EventsList`。`SmsDialog` 全局弹窗,优先级最高。 +单栏卡片流,最大宽度 1160px 居中:顶栏(品牌、面板服务状态、主题菜单)→ `StatusCard`(含 `重新登录` 按钮,二次确认;409 时提示已有登录正在进行)+ `UserCard`(并排,窄屏堆叠)→ `ProxyCards` → `TrustDevices`(browser 模式附说明)→ `EventsList`。`SmsDialog` 全局弹窗,优先级最高。 ## 10. 测试计划 diff --git a/internal/webui/hub.go b/internal/webui/hub.go index 670e985..10c2188 100644 --- a/internal/webui/hub.go +++ b/internal/webui/hub.go @@ -6,6 +6,7 @@ package webui import ( "encoding/json" + "net/url" "sync" "time" @@ -44,30 +45,32 @@ type proxyInfo struct { // snapshot is the /api/status and SSE payload (§6.3). type snapshot struct { - Generation uint64 `json:"generation"` - State string `json:"state"` - Since time.Time `json:"since"` - LastError *string `json:"last_error"` - User *userInfo `json:"user"` - DeviceID string `json:"device_id"` - ClientType string `json:"client_type"` - Gateways []string `json:"gateways"` - DNS []string `json:"dns"` - Proxy proxyInfo `json:"proxy"` - SMSPending bool `json:"sms_pending"` - SMSGen uint64 `json:"sms_gen"` - EventsDropped uint64 `json:"events_dropped"` - Events []HistoryEvent `json:"events"` + Generation uint64 `json:"generation"` + State string `json:"state"` + Since time.Time `json:"since"` + LastError *string `json:"last_error"` + User *userInfo `json:"user"` + DeviceID string `json:"device_id"` + ClientType string `json:"client_type"` + ControllerHost string `json:"controller_host"` + Gateways []string `json:"gateways"` + DNS []string `json:"dns"` + Proxy proxyInfo `json:"proxy"` + SMSPending bool `json:"sms_pending"` + SMSGen uint64 `json:"sms_gen"` + EventsDropped uint64 `json:"events_dropped"` + Events []HistoryEvent `json:"events"` } // Hub keeps the live panel state. All mutations happen under mu; snapshots // are broadcast after the lock is released... except the marshal is cheap // and done under the lock, so subscribers always get a consistent view. type Hub struct { - mu sync.Mutex - deviceID string - clientType string - proxy proxyInfo + mu sync.Mutex + deviceID string + clientType string + controllerHost string + proxy proxyInfo acquiring bool sessionActive bool @@ -97,6 +100,9 @@ func NewHub(cfg *config.Config) *Hub { since: time.Now(), subs: make(map[chan []byte]struct{}), } + if controller, err := url.Parse(cfg.BaseURL); err == nil { + h.controllerHost = controller.Host + } if cfg.Inbound.SOCKS5.Enabled { listen := cfg.Inbound.SOCKS5.Listen h.proxy.SOCKS5 = &listen @@ -217,20 +223,21 @@ func (h *Hub) snapshotLocked() snapshot { events := make([]HistoryEvent, len(h.events)) copy(events, h.events) return snapshot{ - Generation: h.generation, - State: h.state, - Since: h.since, - LastError: h.lastError, - User: h.user, - DeviceID: h.deviceID, - ClientType: h.clientType, - Gateways: h.gateways, - DNS: h.dns, - Proxy: h.proxy, - SMSPending: h.smsPending, - SMSGen: h.smsGen, - EventsDropped: h.dropped, - Events: events, + Generation: h.generation, + State: h.state, + Since: h.since, + LastError: h.lastError, + User: h.user, + DeviceID: h.deviceID, + ClientType: h.clientType, + ControllerHost: h.controllerHost, + Gateways: h.gateways, + DNS: h.dns, + Proxy: h.proxy, + SMSPending: h.smsPending, + SMSGen: h.smsGen, + EventsDropped: h.dropped, + Events: events, } } diff --git a/internal/webui/hub_test.go b/internal/webui/hub_test.go index 49287fd..67ec5de 100644 --- a/internal/webui/hub_test.go +++ b/internal/webui/hub_test.go @@ -163,3 +163,23 @@ func TestHubDropsSlowSubscriber(t *testing.T) { t.Fatal("slow subscriber was not disconnected") } } + +func TestHubControllerHostExcludesCredentialsAndPath(t *testing.T) { + cfg := testConfig("client") + cfg.BaseURL = "https://private:secret@vpn.example.edu.cn:8443/path?ticket=sensitive#fragment" + raw := NewHub(cfg).Snapshot() + var got struct { + ControllerHost string `json:"controller_host"` + } + if err := json.Unmarshal(raw, &got); err != nil { + t.Fatal(err) + } + if got.ControllerHost != "vpn.example.edu.cn:8443" { + t.Fatalf("controller host = %q", got.ControllerHost) + } + for _, secret := range []string{"private", "secret", "sensitive", "fragment", "/path"} { + if strings.Contains(string(raw), secret) { + t.Fatalf("snapshot leaked %q", secret) + } + } +} diff --git a/web/components.json b/web/components.json new file mode 100644 index 0000000..da40af9 --- /dev/null +++ b/web/components.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "radix-nova", + "rsc": false, + "tsx": true, + "tailwind": { + "config": "", + "css": "src/styles.css", + "baseColor": "neutral", + "cssVariables": true, + "prefix": "" + }, + "iconLibrary": "lucide", + "rtl": false, + "aliases": { + "components": "@/components", + "utils": "@/lib/utils", + "ui": "@/components/ui", + "lib": "@/lib", + "hooks": "@/hooks" + }, + "menuColor": "default", + "menuAccent": "subtle", + "registries": {} +} diff --git a/web/index.html b/web/index.html index 5b6f35c..3fdc3c7 100644 --- a/web/index.html +++ b/web/index.html @@ -8,7 +8,21 @@ rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%232563eb'/%3E%3Ccircle cx='8' cy='8' r='3' fill='%23ffffff'/%3E%3C/svg%3E" /> - geekTrust 面板 + geekTrust · 本地控制台 +
diff --git a/web/package-lock.json b/web/package-lock.json index 298a66c..a5f2ce0 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -8,16 +8,83 @@ "name": "geektrust-web", "version": "0.0.0", "dependencies": { + "@fontsource-variable/geist": "^5.3.0", + "@fontsource-variable/geist-mono": "^5.3.0", + "@fontsource-variable/noto-sans-sc": "^5.3.0", + "class-variance-authority": "^0.7.1", + "cn": "^0.4.0", + "input-otp": "^1.5.0", + "lucide-react": "^1.52.0", + "radix-ui": "^1.7.0", "react": "^18.3.1", - "react-dom": "^18.3.1" + "react-dom": "^18.3.1", + "tw-animate-css": "^1.4.0" }, "devDependencies": { + "@tailwindcss/vite": "^4.3.3", + "@testing-library/react": "^16.3.3", "@types/node": "^22.10.2", "@types/react": "^18.3.12", "@types/react-dom": "^18.3.1", - "@vitejs/plugin-react": "^4.3.4", + "@vitejs/plugin-react": "^4.7.0", + "jsdom": "^30.1.2", + "tailwindcss": "^4.3.3", "typescript": "^5.6.3", - "vite": "^5.4.11" + "vite": "^6.4.3", + "vitest": "^5.0.3" + } + }, + "node_modules/@asamuzakjp/css-color": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-7.1.3.tgz", + "integrity": "sha512-1t1U8Cm3RBl9vh3RAZhjkPaduzLSvQJRToRrxpGR/eDRW99mOREleuu+mWfiFa795bUzjwht7NgphCKTs2ianQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^3.4.2", + "@csstools/css-color-parser": "^4.2.5", + "@csstools/css-parser-algorithms": "^4.0.2", + "@csstools/css-tokenizer": "^4.0.2", + "lru-cache": "^11.5.3" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@asamuzakjp/css-color/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@asamuzakjp/dom-selector": { + "version": "9.2.4", + "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-9.2.4.tgz", + "integrity": "sha512-YnVzxDxLaqL0t7Q4wfcgHZjg55Wm6y5EaO7Bhu3q9J7wq/8iw3PhsnWiOQhYekx4VexnbkgWpTT6n+QIV7kczw==", + "dev": true, + "license": "MIT", + "dependencies": { + "bidi-js": "^1.1.0", + "css-tree": "^3.2.1", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.5.3" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@asamuzakjp/dom-selector/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" } }, "node_modules/@babel/code-frame": { @@ -254,6 +321,16 @@ "@babel/core": "^7.0.0-0" } }, + "node_modules/@babel/runtime": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz", + "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, "node_modules/@babel/template": { "version": "7.29.7", "resolved": "https://mirrors.huaweicloud.com/repository/npm/@babel/template/-/template-7.29.7.tgz", @@ -302,10 +379,163 @@ "node": ">=6.9.0" } }, + "node_modules/@bramus/specificity": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.3.tgz", + "integrity": "sha512-0GEz8qJWokkUVYQYRukmkSHIFNoBH8QTreeHrAFbvz1XFYc3Y+puhMs8PQ5x8GNugiC2l5jvDBXKLbBIByeSBw==", + "dev": true, + "license": "MIT", + "dependencies": { + "css-tree": "^3.2.1" + }, + "bin": { + "specificity": "bin/cli.js" + } + }, + "node_modules/@csstools/color-helpers": { + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.2.tgz", + "integrity": "sha512-grhRy3OKmniaAEKXMjua5z/EODX0MSqBGjunw8+j/3HQjOnahs2AGhvEOIYVUWcU6ScApbhLhVrQTX8XqrMrow==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/@csstools/css-calc": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.4.3.tgz", + "integrity": "sha512-iex20d8CHVkyvg6B7UKV7uHnI2Bqo9g+EFfT9E0y+GvTvhZ/DwONJ+9aKb1dlqm0ZiGsL5RXjp0fCoJYnkeDjA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.2", + "@csstools/css-tokenizer": "^4.0.2" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "4.2.6", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.6.tgz", + "integrity": "sha512-iiPQ3iRWwnJkeEn6RIu6SJPr7hYrLz6XZ9s/QZl+2/LI5KQVjpl2fdmDSZKuD4xP6GMmMPgHFFXg6k1Wkz0Trg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^6.1.2", + "@csstools/css-calc": "^3.4.3" + }, + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.2", + "@csstools/css-tokenizer": "^4.0.2" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.2.tgz", + "integrity": "sha512-40cSKyMvK+tq4qz6Awrlye2WGuOKt3FwPgtGg6KTfbHOWNw+Rk1rzbAtZnZ6IBhsY491HLRnDXwoyBAijmmILA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^4.0.2" + } + }, + "node_modules/@csstools/css-syntax-patches-for-csstree": { + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.15.tgz", + "integrity": "sha512-J0u7HkVl2nzSlhsiTOp4AmwcUQ3D+mGEEKfBy/7To5/y7F2OHwyLrXfrhR0SMgr4p5Lo+eaMVSeai24zUcBIxA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "peerDependencies": { + "css-tree": "^3.2.1" + }, + "peerDependenciesMeta": { + "css-tree": { + "optional": true + } + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.2.tgz", + "integrity": "sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + } + }, "node_modules/@esbuild/aix-ppc64": { - "version": "0.21.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz", - "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", "cpu": [ "ppc64" ], @@ -316,13 +546,13 @@ "aix" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/android-arm": { - "version": "0.21.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@esbuild/android-arm/-/android-arm-0.21.5.tgz", - "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", "cpu": [ "arm" ], @@ -333,13 +563,13 @@ "android" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/android-arm64": { - "version": "0.21.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz", - "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", "cpu": [ "arm64" ], @@ -350,13 +580,13 @@ "android" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/android-x64": { - "version": "0.21.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@esbuild/android-x64/-/android-x64-0.21.5.tgz", - "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", "cpu": [ "x64" ], @@ -367,13 +597,13 @@ "android" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/darwin-arm64": { - "version": "0.21.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz", - "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", "cpu": [ "arm64" ], @@ -384,13 +614,13 @@ "darwin" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/darwin-x64": { - "version": "0.21.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz", - "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", "cpu": [ "x64" ], @@ -401,13 +631,13 @@ "darwin" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/freebsd-arm64": { - "version": "0.21.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz", - "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", "cpu": [ "arm64" ], @@ -418,13 +648,13 @@ "freebsd" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/freebsd-x64": { - "version": "0.21.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz", - "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", "cpu": [ "x64" ], @@ -435,13 +665,13 @@ "freebsd" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-arm": { - "version": "0.21.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz", - "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", "cpu": [ "arm" ], @@ -452,13 +682,13 @@ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-arm64": { - "version": "0.21.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz", - "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", "cpu": [ "arm64" ], @@ -469,13 +699,13 @@ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-ia32": { - "version": "0.21.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz", - "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", "cpu": [ "ia32" ], @@ -486,13 +716,13 @@ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-loong64": { - "version": "0.21.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz", - "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", "cpu": [ "loong64" ], @@ -503,13 +733,13 @@ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-mips64el": { - "version": "0.21.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz", - "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", "cpu": [ "mips64el" ], @@ -520,13 +750,13 @@ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-ppc64": { - "version": "0.21.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz", - "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", "cpu": [ "ppc64" ], @@ -537,13 +767,13 @@ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-riscv64": { - "version": "0.21.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz", - "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", "cpu": [ "riscv64" ], @@ -554,13 +784,13 @@ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-s390x": { - "version": "0.21.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz", - "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", "cpu": [ "s390x" ], @@ -571,13 +801,13 @@ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-x64": { - "version": "0.21.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz", - "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", "cpu": [ "x64" ], @@ -588,13 +818,30 @@ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" } }, "node_modules/@esbuild/netbsd-x64": { - "version": "0.21.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz", - "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", "cpu": [ "x64" ], @@ -605,13 +852,30 @@ "netbsd" ], "engines": { - "node": ">=12" + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" } }, "node_modules/@esbuild/openbsd-x64": { - "version": "0.21.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz", - "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", "cpu": [ "x64" ], @@ -622,13 +886,30 @@ "openbsd" ], "engines": { - "node": ">=12" + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" } }, "node_modules/@esbuild/sunos-x64": { - "version": "0.21.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz", - "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", "cpu": [ "x64" ], @@ -639,13 +920,13 @@ "sunos" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/win32-arm64": { - "version": "0.21.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz", - "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", "cpu": [ "arm64" ], @@ -656,13 +937,13 @@ "win32" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/win32-ia32": { - "version": "0.21.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz", - "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", "cpu": [ "ia32" ], @@ -673,13 +954,13 @@ "win32" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/win32-x64": { - "version": "0.21.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz", - "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", "cpu": [ "x64" ], @@ -690,7 +971,90 @@ "win32" ], "engines": { - "node": ">=12" + "node": ">=18" + } + }, + "node_modules/@exodus/bytes": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz", + "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@noble/hashes": "^1.8.0 || ^2.0.0" + }, + "peerDependenciesMeta": { + "@noble/hashes": { + "optional": true + } + } + }, + "node_modules/@floating-ui/core": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz", + "integrity": "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==", + "license": "MIT", + "dependencies": { + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/dom": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.8.0.tgz", + "integrity": "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==", + "license": "MIT", + "dependencies": { + "@floating-ui/core": "^1.8.0", + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/react-dom": { + "version": "2.1.9", + "resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.9.tgz", + "integrity": "sha512-JDjEFGCpImxDCA7JJKviA0M9+RtmJdj0m/NVU5IMgBK+AmZouAQQ7/+2GLH0GXXY0YMw9oXPB8hKdbPYg5QLYg==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.8.0" + }, + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, + "node_modules/@floating-ui/utils": { + "version": "0.2.12", + "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.12.tgz", + "integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==", + "license": "MIT" + }, + "node_modules/@fontsource-variable/geist": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource-variable/geist/-/geist-5.3.0.tgz", + "integrity": "sha512-j0m+vLQuG5XAYoHtGCVu0spvlGreR3EzpECUVzkFmI1mTVnAO38l/NEPDCFgZ177JxzYJCLSmTQibIiYPilGrA==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource-variable/geist-mono": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource-variable/geist-mono/-/geist-mono-5.3.0.tgz", + "integrity": "sha512-vBbuwDEo9AkrqADMXOrlAR3DFcJi4/JxeuU43FoiQERnNwsfXNnvxvReZG02cQKmyk4DZkZdBZX3oTDvy2zBAw==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource-variable/noto-sans-sc": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource-variable/noto-sans-sc/-/noto-sans-sc-5.3.0.tgz", + "integrity": "sha512-lNar1dF7Ik/lHNPo/7JWG0TolXY29LtsqYgMvEysooZ5bsO9uH4shJmRrwyJ3PjyTPljhpMJEK0jDuLSU4vJ1w==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" } }, "node_modules/@jridgewell/gen-mapping": { @@ -726,9 +1090,9 @@ } }, "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", - "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", "dev": true, "license": "MIT" }, @@ -743,19 +1107,1519 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, - "node_modules/@rolldown/pluginutils": { - "version": "1.0.0-beta.27", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz", - "integrity": "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==", - "dev": true, + "node_modules/@radix-ui/number": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.3.tgz", + "integrity": "sha512-Road2bidD0uu/1BGDOWNdPI06g0lIRy6IF9GZcIrDK2KGItfor8IQwQa+yM2ERgHM1MmHxaxpTzk0/Jp42lNfA==", "license": "MIT" }, - "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.62.2", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.2.tgz", - "integrity": "sha512-6o7ZLZK+BeenkZCFNDXqpbjw9bD6nuWonvS/lwQJp7NoVVxm6p3qE7qQ5jGuBjiFsgvqjD8mZAU5oWxTmbOeOg==", - "cpu": [ - "arm" + "node_modules/@radix-ui/primitive": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.7.tgz", + "integrity": "sha512-rqWnm76nYT8HoNNqEjpgJ7Pw/DrBj5iBTrmEPo6HTX5+VJyBNOqTdv4g89G63HuR5g0AaENoAcH7Is5fF2kZ8Q==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-accessible-icon": { + "version": "1.1.16", + "resolved": "https://registry.npmjs.org/@radix-ui/react-accessible-icon/-/react-accessible-icon-1.1.16.tgz", + "integrity": "sha512-I+T/Hc6SY3WbFVZ9Ne1o0DJbpjQpTpLIBZcVzYiHCQ9z1yGUd/G88u5SKyM6eJ223txAOS7bp7bb9k0Ocfkjwg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-visually-hidden": "1.2.12" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-accordion": { + "version": "1.2.21", + "resolved": "https://registry.npmjs.org/@radix-ui/react-accordion/-/react-accordion-1.2.21.tgz", + "integrity": "sha512-2fmc6COuKLq2k3P7JZrOt9Zf8HT9nTQhHN5V+A3ih7ftqoyDcoEUrPoLq8ngr7QwTd7hpQ2xoUKWtvy1Xw9RAQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-collapsible": "1.1.21", + "@radix-ui/react-collection": "1.1.16", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-direction": "1.1.5", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-use-controllable-state": "1.2.6" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-alert-dialog": { + "version": "1.1.24", + "resolved": "https://registry.npmjs.org/@radix-ui/react-alert-dialog/-/react-alert-dialog-1.1.24.tgz", + "integrity": "sha512-dRvB59HhcjIWcCPKzK5Px1yQ8pIULQQrxqgyepCqin7tNXi/xvmC86WkyMOKhuCbjz3+v9Q6oE7/tUN5NQ9dCg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-dialog": "1.2.0", + "@radix-ui/react-primitive": "2.1.11" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-arrow": { + "version": "1.1.16", + "resolved": "https://registry.npmjs.org/@radix-ui/react-arrow/-/react-arrow-1.1.16.tgz", + "integrity": "sha512-nXPI1tzJsnQw8oXvB2r49rO9TIbbJ8VFeaWDiBsqY8+iwO5xb7WjUsrXDagjAgPKTdhW8WODQnAltUhBx8I+sg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.1.11" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-aspect-ratio": { + "version": "1.1.16", + "resolved": "https://registry.npmjs.org/@radix-ui/react-aspect-ratio/-/react-aspect-ratio-1.1.16.tgz", + "integrity": "sha512-w2u6oiTzb7WkWwV3ZClX/llYYlTbilUOkHIKkwb+PWWytQ/IdEVRNLIChjbcXy/mkqcKKM3wEhrOilJW+uPHDg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.1.11" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-avatar": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@radix-ui/react-avatar/-/react-avatar-1.2.7.tgz", + "integrity": "sha512-6AizCpbU3Zngojp9vQak8Lt4AXwdKJ2lkRYAfpoETraT+qKVNeRqytiADzneHetFEB0Wu4+qeSfmZEq0PiVDmQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-use-callback-ref": "1.1.4", + "@radix-ui/react-use-is-hydrated": "0.1.3", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-checkbox": { + "version": "1.3.12", + "resolved": "https://registry.npmjs.org/@radix-ui/react-checkbox/-/react-checkbox-1.3.12.tgz", + "integrity": "sha512-gNOS2lLrpQxNLWHhCX0sayfVRiyB5gQp7nQIzpl+PM1Hkab52utsKtD27alAr78uqhpvX51kwqDp71hM5hNSwg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-use-controllable-state": "1.2.6", + "@radix-ui/react-use-size": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-collapsible": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/@radix-ui/react-collapsible/-/react-collapsible-1.1.21.tgz", + "integrity": "sha512-IzkusZHCZBnED5skW+b+syl8d+e3+zelvxZ2Ed9lfawqEBfa5osPj53sTJ+q/uNmGAj9e7wMYgyzwPu/luWJ4Q==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-use-controllable-state": "1.2.6", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-collection": { + "version": "1.1.16", + "resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.1.16.tgz", + "integrity": "sha512-yEQrjfI5eBbeYEJXOASpm+gs9eNHY8+UjkZ81GzcuwdLrSMOlEM8jnGoGdeGo92oiBMkuwZUhHTsnsrDiJLcyA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-slot": "1.4.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-context": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.2.2.tgz", + "integrity": "sha512-RHCUGwKHDr0hDGg4X7ma4JG4/+12qxw8rkh5QKdDldlCvtja6nUx1Ef/8HVrJze81lEsgLQlqjzjGNHantgnQA==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-context-menu": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/@radix-ui/react-context-menu/-/react-context-menu-2.3.8.tgz", + "integrity": "sha512-s8ABBkEuAOyhDub0Y99f8lVRlVsd28mUnOHtuqGg8LuHnefkmPN5rYzA2g8MAPLjAZMisnDHhN4dBHUM7ZF7Rg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-menu": "2.1.25", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-use-controllable-state": "1.2.6" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-dialog": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dialog/-/react-dialog-1.2.0.tgz", + "integrity": "sha512-l5CX8HdNL+9cc4s7HkNyplumSA3FIx68sg9dttBHKr286fRBwq1MBniDVTeI/tkof92/APntMQvC1YG1Khb0Cg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-dismissable-layer": "1.1.20", + "@radix-ui/react-focus-guards": "1.1.6", + "@radix-ui/react-focus-scope": "1.2.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-portal": "1.1.18", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-slot": "1.4.0", + "@radix-ui/react-use-controllable-state": "1.2.6", + "@radix-ui/react-use-layout-effect": "1.1.4", + "aria-hidden": "^1.2.4", + "react-remove-scroll": "^2.7.2" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-direction": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.1.5.tgz", + "integrity": "sha512-/NlO/rOqQabmg+GGr86vCmbJVhqTv85NfM9g6Gknf/JVygXeZ6e6HM/RW1omerW9HsFtecwNqgEAKV6UqDsvpA==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-dismissable-layer": { + "version": "1.1.20", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dismissable-layer/-/react-dismissable-layer-1.1.20.tgz", + "integrity": "sha512-35WHRrycfnj2m4LvPiKMKHGLM3Y2WvUA744CkRdxjs1BGDX1c8PVMfmiSGTUwnHRbqdtIoxveYTXvcJSt7VfgQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-use-callback-ref": "1.1.4", + "@radix-ui/react-use-effect-event": "0.0.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-dropdown-menu": { + "version": "2.1.25", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dropdown-menu/-/react-dropdown-menu-2.1.25.tgz", + "integrity": "sha512-45QO76jn/a+cRl6OPgZKCKnIMdfYZaOa6SuAJeKHFiM3orX6bnscuFQJDx3qS4Agp/RE+eKv+9gmUL8t3Ma7bw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-menu": "2.1.25", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-use-controllable-state": "1.2.6" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-focus-guards": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-guards/-/react-focus-guards-1.1.6.tgz", + "integrity": "sha512-RNOJjfZMTyBM6xYmV3IVGXkPjIhcBAuv48POevAXwrGJhkWZ9p1rFoIS1JFooPuT193AZmRsCPhpoVJxx6OPoQ==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-focus-scope": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-scope/-/react-focus-scope-1.2.0.tgz", + "integrity": "sha512-I5S7vsAOozx2lWSBAyuXjWIJ/A8qx4fjbv6115WoaRYQSb1yZDaeNHonUAQzXyE8oD+0whJHbQRl4HIE2gQ0Xw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-use-callback-ref": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-form": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-form/-/react-form-0.2.0.tgz", + "integrity": "sha512-5ELeC+bQUHXEjU51svw11DynjGFlaUjo5QOUCr5hptvLLtBiqWtva2O3IWdjrFWQwitw6k6KpHHEyI61/kCVeg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-label": "2.1.16", + "@radix-ui/react-primitive": "2.1.11" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-hover-card": { + "version": "1.1.24", + "resolved": "https://registry.npmjs.org/@radix-ui/react-hover-card/-/react-hover-card-1.1.24.tgz", + "integrity": "sha512-0w/tZHRo1fv4WsfcyaOdi5eDftFA8wQkr8WCOOuxw7fx9S2ERfshQioM269aFZsmyAHd0X1LWoZ2BQTlA/JYUw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-dismissable-layer": "1.1.20", + "@radix-ui/react-focus-scope": "1.2.0", + "@radix-ui/react-popper": "1.3.8", + "@radix-ui/react-portal": "1.1.18", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-use-controllable-state": "1.2.6" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-id": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-id/-/react-id-1.1.4.tgz", + "integrity": "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-label": { + "version": "2.1.16", + "resolved": "https://registry.npmjs.org/@radix-ui/react-label/-/react-label-2.1.16.tgz", + "integrity": "sha512-2vTQj72YFmeoTxWKJEMbO/9uQt6zzLgbzi0+nWBffq49oo6KhIDP/D+fA2im0wsxBCAX7QfaF3xgsYBVdDbNFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.1.11" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-menu": { + "version": "2.1.25", + "resolved": "https://registry.npmjs.org/@radix-ui/react-menu/-/react-menu-2.1.25.tgz", + "integrity": "sha512-e8JaQc0ijBbTx37YVI09Nfq8ThUWJ4L1rvZ3Hvaufehco9/ug9+U3PHz9ue6w3gKd91UcKf9fgDWejeSO+VSKQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-collection": "1.1.16", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-direction": "1.1.5", + "@radix-ui/react-dismissable-layer": "1.1.20", + "@radix-ui/react-focus-guards": "1.1.6", + "@radix-ui/react-focus-scope": "1.2.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-popper": "1.3.8", + "@radix-ui/react-portal": "1.1.18", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-roving-focus": "1.1.20", + "@radix-ui/react-slot": "1.4.0", + "@radix-ui/react-use-callback-ref": "1.1.4", + "aria-hidden": "^1.2.4", + "react-remove-scroll": "^2.7.2" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-menubar": { + "version": "1.1.25", + "resolved": "https://registry.npmjs.org/@radix-ui/react-menubar/-/react-menubar-1.1.25.tgz", + "integrity": "sha512-JIQiKcXsgl6BtwcMe7BMLvCGH2p9Czgcmxl6Ie9Zoi+MW1mmitkcm5We01m/ndLYVI8PpRJnM/RcLV0eOCxaJQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-collection": "1.1.16", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-direction": "1.1.5", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-menu": "2.1.25", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-roving-focus": "1.1.20", + "@radix-ui/react-use-controllable-state": "1.2.6" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-navigation-menu": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-navigation-menu/-/react-navigation-menu-1.3.0.tgz", + "integrity": "sha512-hZqTqDwc8Z5aI4rGIyPqCSJ2JoSNorqX/F1/gqNHkZzWJO6JuYzL7hn5sWOZJjpkfT+cbxWWRbKVU/IeiOM9ag==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-collection": "1.1.16", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-direction": "1.1.5", + "@radix-ui/react-dismissable-layer": "1.1.20", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-slot": "1.4.0", + "@radix-ui/react-use-callback-ref": "1.1.4", + "@radix-ui/react-use-controllable-state": "1.2.6", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-use-previous": "1.1.4", + "@radix-ui/react-visually-hidden": "1.2.12" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-one-time-password-field": { + "version": "0.1.17", + "resolved": "https://registry.npmjs.org/@radix-ui/react-one-time-password-field/-/react-one-time-password-field-0.1.17.tgz", + "integrity": "sha512-+6jmOqjSNBr7F1uSc7HSDqD3XL54A2qA99I9rIH4JoOD/jDScw8tUmDz6HCAkjytbrE/cdL66i+QkeDyZ0WNyw==", + "license": "MIT", + "dependencies": { + "@radix-ui/number": "1.1.3", + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-collection": "1.1.16", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-direction": "1.1.5", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-roving-focus": "1.1.20", + "@radix-ui/react-use-controllable-state": "1.2.6", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-is-hydrated": "0.1.3", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-password-toggle-field": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/@radix-ui/react-password-toggle-field/-/react-password-toggle-field-0.1.12.tgz", + "integrity": "sha512-+SWSgf3HRpE4zUira+p6t5KUR473PSqewtQgj9qzl3znZPRWPCGycwXNTfHwkiRTD3tEXwNIXJg0i1NTteiULw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-use-controllable-state": "1.2.6", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-is-hydrated": "0.1.3" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-popover": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-popover/-/react-popover-1.2.0.tgz", + "integrity": "sha512-e70Nh+0iQ+hRAIM2nAGib5BhaDL2Rjlzxw9kIzsU2nz+t3/t82Z5qtPhY5nTnfj8FbmrU6RRIKH8RF3ynCe+vw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-dismissable-layer": "1.1.20", + "@radix-ui/react-focus-guards": "1.1.6", + "@radix-ui/react-focus-scope": "1.2.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-popper": "1.3.8", + "@radix-ui/react-portal": "1.1.18", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-slot": "1.4.0", + "@radix-ui/react-use-controllable-state": "1.2.6", + "@radix-ui/react-use-layout-effect": "1.1.4", + "aria-hidden": "^1.2.4", + "react-remove-scroll": "^2.7.2" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-popper": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/@radix-ui/react-popper/-/react-popper-1.3.8.tgz", + "integrity": "sha512-y92/9iIdG1FyNvow0Y0qP5WJZ7oRTAKDVKCy9kJnhZfItwIKYtt0KKQeOhBKfXz0ETizduKwDRbrQHrTQScs5A==", + "license": "MIT", + "dependencies": { + "@floating-ui/react-dom": "^2.0.0", + "@radix-ui/react-arrow": "1.1.16", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-use-callback-ref": "1.1.4", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-use-rect": "1.1.4", + "@radix-ui/react-use-size": "1.1.5", + "@radix-ui/rect": "1.1.3" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-portal": { + "version": "1.1.18", + "resolved": "https://registry.npmjs.org/@radix-ui/react-portal/-/react-portal-1.1.18.tgz", + "integrity": "sha512-ygFIJ+QXNKf72AAq8x3hd22+ws7pYpmc1S0E4kW0Je+qD4qEb3FvxeKVQRGrVDMOkQaYfsB+Qs+KDh81a1gAOw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-presence": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.11.tgz", + "integrity": "sha512-Z7/atlkab36Z8hm+V8zYc79r0W+tiOB1o0tun1By94JyadkekLQmtEAnBSP9XKXBNQsStoStS4+gX10JpS5akA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-primitive": { + "version": "2.1.11", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.11.tgz", + "integrity": "sha512-RzcaSw5aKl0OPhBJ1wbolKSF6nVvN+0o/QLeIVq+09npiPdnCkPggy2k6gI6yetxl4ZyrlBPYFgCB8BQJZwXcQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.4.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-progress": { + "version": "1.1.17", + "resolved": "https://registry.npmjs.org/@radix-ui/react-progress/-/react-progress-1.1.17.tgz", + "integrity": "sha512-A+RfMARd9u+UaVbLQDmysGlAGuaFQrF+uxF3v+7+xU8tkKoYxtCSs+6HHnIKJVgam2sGZ7c0hLRPWSnmnFyGJQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-primitive": "2.1.11" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group": { + "version": "1.4.8", + "resolved": "https://registry.npmjs.org/@radix-ui/react-radio-group/-/react-radio-group-1.4.8.tgz", + "integrity": "sha512-MaOOZ1TlaYoOeSDnHeVIONss0rp5ngOTY5HJY+Xkq16PAopnj21iU9r9m0O/77cBYu8Ksaq3BcjlaOdpbfbzzg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-direction": "1.1.5", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-roving-focus": "1.1.20", + "@radix-ui/react-use-controllable-state": "1.2.6", + "@radix-ui/react-use-size": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-roving-focus": { + "version": "1.1.20", + "resolved": "https://registry.npmjs.org/@radix-ui/react-roving-focus/-/react-roving-focus-1.1.20.tgz", + "integrity": "sha512-+ZjbkU21fTSJdn4nq/IFKUdKS+JSZHORBZ8ma1f6YpOMNzRt0xf3sVAWVK/+ktHCajPy4HYDsyHXZIZmOMxzIA==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-collection": "1.1.16", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-direction": "1.1.5", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-use-callback-ref": "1.1.4", + "@radix-ui/react-use-controllable-state": "1.2.6", + "@radix-ui/react-use-is-hydrated": "0.1.3", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-scroll-area": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-scroll-area/-/react-scroll-area-1.3.0.tgz", + "integrity": "sha512-1WSuAXaahfeLmFX/dfYo/ftg1filMfaWjVye2d40VlgtWMMq/NOVocfukZEXkG+dwrAoNI+qpo9bjhNSJ/XC8g==", + "license": "MIT", + "dependencies": { + "@radix-ui/number": "1.1.3", + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-direction": "1.1.5", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-slot": "1.4.0", + "@radix-ui/react-use-callback-ref": "1.1.4", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-select": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/@radix-ui/react-select/-/react-select-2.3.8.tgz", + "integrity": "sha512-Tz9xOpV9Rbca5WTk7pzmfAECV3zb++uScT9mP3Px7ziAhH7SlK53b0uwMw8VubPhRK4x7uDKCy5fwevT8I0fAg==", + "license": "MIT", + "dependencies": { + "@radix-ui/number": "1.1.3", + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-collection": "1.1.16", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-direction": "1.1.5", + "@radix-ui/react-dismissable-layer": "1.1.20", + "@radix-ui/react-focus-guards": "1.1.6", + "@radix-ui/react-focus-scope": "1.2.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-popper": "1.3.8", + "@radix-ui/react-portal": "1.1.18", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-slot": "1.4.0", + "@radix-ui/react-use-callback-ref": "1.1.4", + "@radix-ui/react-use-controllable-state": "1.2.6", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-use-previous": "1.1.4", + "@radix-ui/react-visually-hidden": "1.2.12", + "aria-hidden": "^1.2.4", + "react-remove-scroll": "^2.7.2" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-separator": { + "version": "1.1.16", + "resolved": "https://registry.npmjs.org/@radix-ui/react-separator/-/react-separator-1.1.16.tgz", + "integrity": "sha512-vugPjGQBXbJVVkftKqv/BVeZ108SyRGT3FR1oa14az6qyLgX8jPhnZYHgdSB7Gw8UJusqwb9eaK6mluOnsn/Vg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.1.11" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slider": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slider/-/react-slider-1.5.0.tgz", + "integrity": "sha512-ZOBLK7KZvGL02V+4VwVbj8NYM4vPrAtyZdrgHSv+AMS9VL+5yAdnQF3DZT4Y8cbCp1Yn4xdp92orvez8fJa77w==", + "license": "MIT", + "dependencies": { + "@radix-ui/number": "1.1.3", + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-collection": "1.1.16", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-direction": "1.1.5", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-use-controllable-state": "1.2.6", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-use-previous": "1.1.4", + "@radix-ui/react-use-size": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slot": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.4.0.tgz", + "integrity": "sha512-IuMVHZ+Ah5fkctu3X3qeFrV/ZrBcuWuDTFUUPfS/L5hvoTjzhp/HdWGE14CsQombPdEidsa33HVlYZXi49PZ1Q==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-switch": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/@radix-ui/react-switch/-/react-switch-1.3.8.tgz", + "integrity": "sha512-rr+zuoAeHWK3m6H4HgjOUiu3VsrQ/9JkjwY/uMnTgHJGPe9WNzDP/MOuIV7S+65p42DIxjGL0hAHktqBq82+2A==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-use-controllable-state": "1.2.6", + "@radix-ui/react-use-size": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tabs": { + "version": "1.1.22", + "resolved": "https://registry.npmjs.org/@radix-ui/react-tabs/-/react-tabs-1.1.22.tgz", + "integrity": "sha512-GmVH+P3wx1ZPMuH7WajQzygZIbqgnsb5h8z4Ow3sQMuDqgcqISSBNom6MLVNJvfrkuJTtqfXc3ZolHjX+w0CHg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-direction": "1.1.5", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-roving-focus": "1.1.20", + "@radix-ui/react-use-controllable-state": "1.2.6" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-toast": { + "version": "1.2.24", + "resolved": "https://registry.npmjs.org/@radix-ui/react-toast/-/react-toast-1.2.24.tgz", + "integrity": "sha512-XR9pDEz9CH0ez98zPXQZOpF46anvbarkoOpjXpPSX7gm21vEl5Tzoe1PSQd3EY1OTOHac4lNq+TPx/2Z7jObdQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-collection": "1.1.16", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-dismissable-layer": "1.1.20", + "@radix-ui/react-portal": "1.1.18", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-use-callback-ref": "1.1.4", + "@radix-ui/react-use-controllable-state": "1.2.6", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-visually-hidden": "1.2.12" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-toggle": { + "version": "1.1.19", + "resolved": "https://registry.npmjs.org/@radix-ui/react-toggle/-/react-toggle-1.1.19.tgz", + "integrity": "sha512-l7FQHtuZjUJ0vKLdhKu5LzZ8Jw6K60QEC1tC22QNLuXN2PkydSoqEhKTCqwxBFZJ52NTCjzudDvl9sUsZeUbPw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-use-controllable-state": "1.2.6" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-toggle-group": { + "version": "1.1.20", + "resolved": "https://registry.npmjs.org/@radix-ui/react-toggle-group/-/react-toggle-group-1.1.20.tgz", + "integrity": "sha512-O+Sjiv64DfnByHYtnKEXmn63uUskU/X61vjf69X1v8JFn/ZvuNNLdJTBfYurVTSDv4/RJnJGtGgb/uvuS/rRJw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-direction": "1.1.5", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-roving-focus": "1.1.20", + "@radix-ui/react-toggle": "1.1.19", + "@radix-ui/react-use-controllable-state": "1.2.6" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-toolbar": { + "version": "1.1.20", + "resolved": "https://registry.npmjs.org/@radix-ui/react-toolbar/-/react-toolbar-1.1.20.tgz", + "integrity": "sha512-5gyzL6B5/zjBwU3ATBWAVZ4xXQC5F8E9CB4BmYC1UvZ08pN2OJQoooeIwJtZZ/2rz4sTiQmbGfdDvmU73wRJCQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-direction": "1.1.5", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-roving-focus": "1.1.20", + "@radix-ui/react-separator": "1.1.16", + "@radix-ui/react-toggle-group": "1.1.20" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-tooltip/-/react-tooltip-1.3.0.tgz", + "integrity": "sha512-4HM4b1Cft1CBXCGDRDG3S/fh8GedBuVOMNh145wMIfTbVqcuv+tyj03nZqYgFevWJMYo58H0s+8P6s6NaUHWtA==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-dismissable-layer": "1.1.20", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-popper": "1.3.8", + "@radix-ui/react-portal": "1.1.18", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-slot": "1.4.0", + "@radix-ui/react-use-controllable-state": "1.2.6", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-visually-hidden": "1.2.12" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-callback-ref": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.4.tgz", + "integrity": "sha512-R6OUY2e2fA6Yn6s+VSx5KBV6Nx8LQEhu+cz7LCej18rQ1HLyg9PSC9jP/ZNx0o6FAIK9c0F1kHylzSxKsdlkrQ==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.2.6.tgz", + "integrity": "sha512-uEQJGT97ZA/TgP/Hydw47lHu+/vQj6z/0jA+WeTbK1o9Rx45GImjpD0tc3W5ad3D6XTSR6e1yEO0FvGq6WQfVQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-escape-keydown": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-escape-keydown/-/react-use-escape-keydown-1.1.5.tgz", + "integrity": "sha512-ge3ipobwSXTj4JyVtswQ7qZj0ZHdtbGuOno/LrgAAeSxtsJ6Vs4Gz5IkPH2bmqpjcLUFoqGhA/mueuIf63UXlA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-callback-ref": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-is-hydrated": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-is-hydrated/-/react-use-is-hydrated-0.1.3.tgz", + "integrity": "sha512-umO/aJ+82CpOnhDZUTbILCQf7kU/g0iv+oGs/Q8jw7IkhWBzaEP4sA268PhFAJTFetbwp3ICc6ktpI4TqtxcIw==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-previous": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-previous/-/react-use-previous-1.1.4.tgz", + "integrity": "sha512-XoSLhbRbqxFtgJoi2fNHA3C6pDlY34x508vUpUGoFZfvePfHXHbE1lC4FYFMnJWgiCRroSTw6fOsXQoVS9RwZg==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-rect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-rect/-/react-use-rect-1.1.4.tgz", + "integrity": "sha512-cSOCh6JlkmfjLyNcLiu2nB4v+nm+dkZ+Q5KHWk/soo4U7ZLiEQFKHK9/YmtBHjfCEaU43IBKQOc4/uJmCaiCTQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/rect": "1.1.3" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-size": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-size/-/react-use-size-1.1.5.tgz", + "integrity": "sha512-V1McDQkMGzgivwqdu7u96APs7oi0Jvj9LTzgq3WWrDZqxWdAqU9yZnZQqk5OizGFR8badUQwZsrlao7MOlWYOA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-visually-hidden": { + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@radix-ui/react-visually-hidden/-/react-visually-hidden-1.2.12.tgz", + "integrity": "sha512-/iPLVHRBzKWvekN+5xaDmXw80f+nleYYceomVORrGjuJe0LF2SCbSH4f/LG4hu32q92QSuPZx4hmSACYBVBfzQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.1.11" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/rect": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@radix-ui/rect/-/rect-1.1.3.tgz", + "integrity": "sha512-JtyZR+mqgBibTo8xea3B6ZRmzZiM/YeVBtUkas6zMuXjAlfIFIW2FgqeM9eLyvEaYX66vr6DJMK+4U6LV0KhNw==", + "license": "MIT" + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.0-beta.27", + "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz", + "integrity": "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.62.2", + "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.2.tgz", + "integrity": "sha512-6o7ZLZK+BeenkZCFNDXqpbjw9bD6nuWonvS/lwQJp7NoVVxm6p3qE7qQ5jGuBjiFsgvqjD8mZAU5oWxTmbOeOg==", + "cpu": [ + "arm" ], "dev": true, "license": "MIT", @@ -904,108 +2768,365 @@ "linux" ] }, - "node_modules/@rollup/rollup-linux-loong64-musl": { - "version": "4.62.2", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.62.2.tgz", - "integrity": "sha512-IxKLoxCQ2IWi6bT2akyDUBGsOImDKB+sPp4EsTmwFQ/fMwpCKm8uLSSgP/Kx/QYUgKis6SEZ5/Nlhup0DIA0PQ==", + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.62.2", + "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.62.2.tgz", + "integrity": "sha512-IxKLoxCQ2IWi6bT2akyDUBGsOImDKB+sPp4EsTmwFQ/fMwpCKm8uLSSgP/Kx/QYUgKis6SEZ5/Nlhup0DIA0PQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.62.2", + "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.62.2.tgz", + "integrity": "sha512-Mk5ha2RQSgyFfmYYLkBpPnUk8D8FriBxesO1u9O75X0mHgXL1UQcH5Itl2lurWL2tj0RxV9b9tJgipac0hRY9A==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.62.2", + "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.62.2.tgz", + "integrity": "sha512-CjvEnqJL/0/TQ3TXX3OPIJ/kmBellrWd4heXUmHeJlTnmwjKpSJzoehLaL6Xk0ZnMHBu9dZuFADNOrtjF4v+2w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.62.2", + "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.62.2.tgz", + "integrity": "sha512-1SiZbzwdkaDURsew/tSOrooKiYy7EQGT6m8ufavAi9NEyQb/6VuIxFXAL1fqa4iZe3g4NbNk4P7J32z2tw5Mgg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.62.2", + "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.62.2.tgz", + "integrity": "sha512-nQts12zJ3NQRoE6uYljOH89v7szzLDvG2JD/vsX+vGXU8w/At1GowTZ5/7qeFQ8m7L55rpR8Okugnuo5bgjy2Q==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.62.2", + "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.62.2.tgz", + "integrity": "sha512-E9/ll019jhPIJgpzfZoIkBGhcz+kKNgVWYRY0zr9srBdPPFVpvOKW8VaJKUbeK+eZXyQF9ltME+Kk6affeaPgg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.62.2", + "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.62.2.tgz", + "integrity": "sha512-5BqxR/pshjey51iliyzTD5Xi3EN0aLmQ2lZ3lvefVV9c82BvrLo2/6OT55iifpWBufs6kdwWbuOKS841DrmK9A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.62.2", + "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.62.2.tgz", + "integrity": "sha512-uNN83XxQrRAh/w0/pmAfibcwyb6YWt4gP+dpnQKPVJshAloQ785ii8CT8ZCIxkGg9opVsvAlGhFitSm6D1Jjpg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.62.2", + "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.62.2.tgz", + "integrity": "sha512-srjEIxSH3LRnJN6THczDHWQplqEMFiAJrTab0msUryh9kwNpkICf3Ea6q6MN/2cZwRFUNx5w+h6Hpi4QuHS6Zg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.62.2", + "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.62.2.tgz", + "integrity": "sha512-8hOJnxgbyObnCm5AlRA3A931xX19xq80RjVTKgJOvEKWqJruP/Uf12IbAOaDjjEXYRewwHLfmF0YRIdK3OwKWA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.62.2", + "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.62.2.tgz", + "integrity": "sha512-mmF4AY1i0hG/bLWUctUq59gtmgaSIRa3cu/A3JFRp/sCNEme2bgDEiDS22P9FbnJB8NJNF4jPJiSP5RHQpUTDg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.62.2", + "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.62.2.tgz", + "integrity": "sha512-DZgkknc6jhHrk46V25vbAM0zZkyP0nSDkJB8/dRkLTxv470dOmWDqGoEJl/9A0dFfS7yE3REOwNDxpHwSLSt0Q==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.62.2", + "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.62.2.tgz", + "integrity": "sha512-T6xr6ucWSFto+VGajA8YH26LdpHRuP4YLHEKAtCWvJDOlnmWcDZVCI2Jmjr+IFHDlt2zRaTAKE4tfjTaWLgJBg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.62.2", + "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.62.2.tgz", + "integrity": "sha512-BfzEnDJOt9T8M989/lA37EcJgat01wLRnoi5dQf3QzOH7jzpqTAzdDbVfRljVr5r+jzKqpbHeyOfAaXxAd0PAA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@tailwindcss/node": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.3.tgz", + "integrity": "sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "enhanced-resolve": "^5.24.1", + "jiti": "^2.7.0", + "lightningcss": "1.32.0", + "magic-string": "^0.30.21", + "source-map-js": "^1.2.1", + "tailwindcss": "4.3.3" + } + }, + "node_modules/@tailwindcss/oxide": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.3.3.tgz", + "integrity": "sha512-krXjAikiaFSPaK/FkAQT5UTx3VormQaiZ5hBFlJZ9UFQGB/rwg1MZIhHAG9smMQRTdyJxP6Qt5MwMtdyU5FWrA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "optionalDependencies": { + "@tailwindcss/oxide-android-arm64": "4.3.3", + "@tailwindcss/oxide-darwin-arm64": "4.3.3", + "@tailwindcss/oxide-darwin-x64": "4.3.3", + "@tailwindcss/oxide-freebsd-x64": "4.3.3", + "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.3", + "@tailwindcss/oxide-linux-arm64-gnu": "4.3.3", + "@tailwindcss/oxide-linux-arm64-musl": "4.3.3", + "@tailwindcss/oxide-linux-x64-gnu": "4.3.3", + "@tailwindcss/oxide-linux-x64-musl": "4.3.3", + "@tailwindcss/oxide-wasm32-wasi": "4.3.3", + "@tailwindcss/oxide-win32-arm64-msvc": "4.3.3", + "@tailwindcss/oxide-win32-x64-msvc": "4.3.3" + } + }, + "node_modules/@tailwindcss/oxide-android-arm64": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.3.3.tgz", + "integrity": "sha512-Y85A2gmPSkl5Ve5qR86GL4HT509cFqQh1aes9p3sSkyTPwt0Pppf3GkwGe4JPACcRYjgJIEhQgM6dBClnr0NYw==", "cpu": [ - "loong64" + "arm64" ], "dev": true, "license": "MIT", "optional": true, "os": [ - "linux" - ] + "android" + ], + "engines": { + "node": ">= 20" + } }, - "node_modules/@rollup/rollup-linux-ppc64-gnu": { - "version": "4.62.2", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.62.2.tgz", - "integrity": "sha512-Mk5ha2RQSgyFfmYYLkBpPnUk8D8FriBxesO1u9O75X0mHgXL1UQcH5Itl2lurWL2tj0RxV9b9tJgipac0hRY9A==", + "node_modules/@tailwindcss/oxide-darwin-arm64": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.3.3.tgz", + "integrity": "sha512-BiaWatpBcERQFDlOjRDpIVXuFK5PJez5SA4JMg6VYZdBYU+qKfV/vqjcIs+IYmtitf1xYQZTwXvU/8y4lfZUGw==", "cpu": [ - "ppc64" + "arm64" ], "dev": true, "license": "MIT", "optional": true, "os": [ - "linux" - ] + "darwin" + ], + "engines": { + "node": ">= 20" + } }, - "node_modules/@rollup/rollup-linux-ppc64-musl": { - "version": "4.62.2", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.62.2.tgz", - "integrity": "sha512-CjvEnqJL/0/TQ3TXX3OPIJ/kmBellrWd4heXUmHeJlTnmwjKpSJzoehLaL6Xk0ZnMHBu9dZuFADNOrtjF4v+2w==", + "node_modules/@tailwindcss/oxide-darwin-x64": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.3.3.tgz", + "integrity": "sha512-fAeUqfV5ndhxRwai8cXGzdLvul9utWOmeTkv69unv4ZXixjn61Z+p9lCWdwOwA3TYboG3BwdVuN/RDjhBRl0mw==", "cpu": [ - "ppc64" + "x64" ], "dev": true, "license": "MIT", "optional": true, "os": [ - "linux" - ] + "darwin" + ], + "engines": { + "node": ">= 20" + } }, - "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.62.2", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.62.2.tgz", - "integrity": "sha512-1SiZbzwdkaDURsew/tSOrooKiYy7EQGT6m8ufavAi9NEyQb/6VuIxFXAL1fqa4iZe3g4NbNk4P7J32z2tw5Mgg==", + "node_modules/@tailwindcss/oxide-freebsd-x64": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.3.3.tgz", + "integrity": "sha512-iyf5bV6+wnAlflVeEy7R25dupxTNECZN5QMI0qNT6eT+EgaGdZcKhGkr5SdoaWiLJ3spLqIY9VCeSGrwmtg4kw==", "cpu": [ - "riscv64" + "x64" ], "dev": true, "license": "MIT", "optional": true, "os": [ - "linux" - ] + "freebsd" + ], + "engines": { + "node": ">= 20" + } }, - "node_modules/@rollup/rollup-linux-riscv64-musl": { - "version": "4.62.2", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.62.2.tgz", - "integrity": "sha512-nQts12zJ3NQRoE6uYljOH89v7szzLDvG2JD/vsX+vGXU8w/At1GowTZ5/7qeFQ8m7L55rpR8Okugnuo5bgjy2Q==", + "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.3.tgz", + "integrity": "sha512-aAYUprJAJQWWbRrPvtjdroZ56Md+JM8pMiopS6xGEwDfLhqj+2ver2p4nU4Mb3CRqcMmNBjo8KkUgcxhkzVQGQ==", "cpu": [ - "riscv64" + "arm" ], "dev": true, "license": "MIT", "optional": true, "os": [ "linux" - ] + ], + "engines": { + "node": ">= 20" + } }, - "node_modules/@rollup/rollup-linux-s390x-gnu": { - "version": "4.62.2", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.62.2.tgz", - "integrity": "sha512-E9/ll019jhPIJgpzfZoIkBGhcz+kKNgVWYRY0zr9srBdPPFVpvOKW8VaJKUbeK+eZXyQF9ltME+Kk6affeaPgg==", + "node_modules/@tailwindcss/oxide-linux-arm64-gnu": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.3.3.tgz", + "integrity": "sha512-nDxldcEENOxZRzC2uu9jrutZdAAQtb+8WWDCSnWL1zvBk1+FN+x6MtDViPB5AJMfttVCUhehGWus3XBPgatM/w==", "cpu": [ - "s390x" + "arm64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "linux" - ] + ], + "engines": { + "node": ">= 20" + } }, - "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.62.2", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.62.2.tgz", - "integrity": "sha512-5BqxR/pshjey51iliyzTD5Xi3EN0aLmQ2lZ3lvefVV9c82BvrLo2/6OT55iifpWBufs6kdwWbuOKS841DrmK9A==", + "node_modules/@tailwindcss/oxide-linux-arm64-musl": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.3.3.tgz", + "integrity": "sha512-Md44bD6veX/PC5iyF8cDVnw4HBIANZepRZZ7a8DQOvkfo5WUBwcp6iAuCUz23u+4SUkhJlD3eL7hNdW8ezd/kA==", "cpu": [ - "x64" + "arm64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "linux" - ] + ], + "engines": { + "node": ">= 20" + } }, - "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.62.2", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.62.2.tgz", - "integrity": "sha512-uNN83XxQrRAh/w0/pmAfibcwyb6YWt4gP+dpnQKPVJshAloQ785ii8CT8ZCIxkGg9opVsvAlGhFitSm6D1Jjpg==", + "node_modules/@tailwindcss/oxide-linux-x64-gnu": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.3.tgz", + "integrity": "sha512-tx7us1muwOKAKWao2v/GaafFeQboE6aj88vC6ziN2NCGcRm8gWUhwjzg+YdVB1e4boAtdtma4L43onunI6NS4w==", "cpu": [ "x64" ], @@ -1014,12 +3135,15 @@ "optional": true, "os": [ "linux" - ] + ], + "engines": { + "node": ">= 20" + } }, - "node_modules/@rollup/rollup-openbsd-x64": { - "version": "4.62.2", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.62.2.tgz", - "integrity": "sha512-srjEIxSH3LRnJN6THczDHWQplqEMFiAJrTab0msUryh9kwNpkICf3Ea6q6MN/2cZwRFUNx5w+h6Hpi4QuHS6Zg==", + "node_modules/@tailwindcss/oxide-linux-x64-musl": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.3.3.tgz", + "integrity": "sha512-SJxX60smvHgasZoBy11dX6YRjXJFovwWBoedhbQPOBzgFWBHGB+TVPWB9BxzR7TTxU8FQZAI2AyiNCMzFm8Img==", "cpu": [ "x64" ], @@ -1027,27 +3151,46 @@ "license": "MIT", "optional": true, "os": [ - "openbsd" - ] + "linux" + ], + "engines": { + "node": ">= 20" + } }, - "node_modules/@rollup/rollup-openharmony-arm64": { - "version": "4.62.2", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.62.2.tgz", - "integrity": "sha512-8hOJnxgbyObnCm5AlRA3A931xX19xq80RjVTKgJOvEKWqJruP/Uf12IbAOaDjjEXYRewwHLfmF0YRIdK3OwKWA==", + "node_modules/@tailwindcss/oxide-wasm32-wasi": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.3.tgz", + "integrity": "sha512-jx1+rPhY/5Ympkktd656HBWEBLxP7dH06losBLjjf5vgCODXvi9KhtftWcMIwTFIDqBr7cRnQkdLnAG+IOlGvQ==", + "bundleDependencies": [ + "@napi-rs/wasm-runtime", + "@emnapi/core", + "@emnapi/runtime", + "@tybys/wasm-util", + "@emnapi/wasi-threads", + "tslib" + ], "cpu": [ - "arm64" + "wasm32" ], "dev": true, "license": "MIT", "optional": true, - "os": [ - "openharmony" - ] + "dependencies": { + "@emnapi/core": "^1.11.1", + "@emnapi/runtime": "^1.11.1", + "@emnapi/wasi-threads": "^1.2.2", + "@napi-rs/wasm-runtime": "^1.1.4", + "@tybys/wasm-util": "^0.10.2", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14.0.0" + } }, - "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.62.2", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.62.2.tgz", - "integrity": "sha512-mmF4AY1i0hG/bLWUctUq59gtmgaSIRa3cu/A3JFRp/sCNEme2bgDEiDS22P9FbnJB8NJNF4jPJiSP5RHQpUTDg==", + "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.3.tgz", + "integrity": "sha512-3rc292Ca2ceK6Ulcc/bAVnTs/3nDtoPhyEKlgPv+yQJQi/JS/AMJlqzxvlDacL1nekbrcf6bTqp/jV4qgnPxNQ==", "cpu": [ "arm64" ], @@ -1056,49 +3199,99 @@ "optional": true, "os": [ "win32" - ] + ], + "engines": { + "node": ">= 20" + } }, - "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.62.2", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.62.2.tgz", - "integrity": "sha512-DZgkknc6jhHrk46V25vbAM0zZkyP0nSDkJB8/dRkLTxv470dOmWDqGoEJl/9A0dFfS7yE3REOwNDxpHwSLSt0Q==", + "node_modules/@tailwindcss/oxide-win32-x64-msvc": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.3.3.tgz", + "integrity": "sha512-yJ0pwIVc/nYeGoV02WtsN8KYyLQv7kyI2wDnkezyJlGGjkd4QLwDGAwl47YpPJeuI0M0ObaXGSPjvWDPeTPggw==", "cpu": [ - "ia32" + "x64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "win32" - ] - }, - "node_modules/@rollup/rollup-win32-x64-gnu": { - "version": "4.62.2", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.62.2.tgz", - "integrity": "sha512-T6xr6ucWSFto+VGajA8YH26LdpHRuP4YLHEKAtCWvJDOlnmWcDZVCI2Jmjr+IFHDlt2zRaTAKE4tfjTaWLgJBg==", - "cpu": [ - "x64" ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/vite": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/vite/-/vite-4.3.3.tgz", + "integrity": "sha512-yYU8cogLeSh/ms2jh8Fj7jaba/EWa7Ja6GoUqYZaraEuCI5YS6ms6ObZgjjedm+jm6XZjdNRWBpPP6Z86oOxcw==", "dev": true, "license": "MIT", - "optional": true, - "os": [ - "win32" - ] + "dependencies": { + "@tailwindcss/node": "4.3.3", + "@tailwindcss/oxide": "4.3.3", + "tailwindcss": "4.3.3" + }, + "peerDependencies": { + "vite": "^5.2.0 || ^6 || ^7 || ^8" + } }, - "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.62.2", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.62.2.tgz", - "integrity": "sha512-BfzEnDJOt9T8M989/lA37EcJgat01wLRnoi5dQf3QzOH7jzpqTAzdDbVfRljVr5r+jzKqpbHeyOfAaXxAd0PAA==", - "cpu": [ - "x64" - ], + "node_modules/@testing-library/dom": { + "version": "10.4.2", + "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.2.tgz", + "integrity": "sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q==", "dev": true, "license": "MIT", - "optional": true, - "os": [ - "win32" - ] + "peer": true, + "dependencies": { + "@babel/code-frame": "^7.10.4", + "@babel/runtime": "^7.12.5", + "@types/aria-query": "^5.0.1", + "aria-query": "5.3.0", + "dom-accessibility-api": "^0.5.9", + "lz-string": "^1.5.0", + "picocolors": "1.1.1", + "pretty-format": "^27.0.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@testing-library/react": { + "version": "16.3.3", + "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-16.3.3.tgz", + "integrity": "sha512-Uo193NgQbPMz6lrrhtRQQFcMC6Re/ELLFbbuVL30WDlZxlpZf9/lMHTAVxPRLw1q1iu9OJmR1c2BLiENRstdBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.12.5" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@testing-library/dom": "^10.0.0", + "@types/react": "^18.0.0 || ^19.0.0", + "@types/react-dom": "^18.0.0 || ^19.0.0", + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@types/aria-query": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz", + "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==", + "dev": true, + "license": "MIT", + "peer": true }, "node_modules/@types/babel__core": { "version": "7.20.5", @@ -1145,6 +3338,24 @@ "@babel/types": "^7.28.2" } }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/estree": { "version": "1.0.9", "resolved": "https://mirrors.huaweicloud.com/repository/npm/@types/estree/-/estree-1.0.9.tgz", @@ -1166,14 +3377,14 @@ "version": "15.7.15", "resolved": "https://mirrors.huaweicloud.com/repository/npm/@types/prop-types/-/prop-types-15.7.15.tgz", "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==", - "dev": true, + "devOptional": true, "license": "MIT" }, "node_modules/@types/react": { "version": "18.3.31", "resolved": "https://mirrors.huaweicloud.com/repository/npm/@types/react/-/react-18.3.31.tgz", "integrity": "sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@types/prop-types": "*", @@ -1184,31 +3395,137 @@ "version": "18.3.7", "resolved": "https://mirrors.huaweicloud.com/repository/npm/@types/react-dom/-/react-dom-18.3.7.tgz", "integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==", - "dev": true, + "devOptional": true, "license": "MIT", "peerDependencies": { "@types/react": "^18.0.0" } }, - "node_modules/@vitejs/plugin-react": { - "version": "4.7.0", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz", - "integrity": "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==", + "node_modules/@vitejs/plugin-react": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz", + "integrity": "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.28.0", + "@babel/plugin-transform-react-jsx-self": "^7.27.1", + "@babel/plugin-transform-react-jsx-source": "^7.27.1", + "@rolldown/pluginutils": "1.0.0-beta.27", + "@types/babel__core": "^7.20.5", + "react-refresh": "^0.17.0" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "peerDependencies": { + "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" + } + }, + "node_modules/@vitest/mocker": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.3.tgz", + "integrity": "sha512-T8sWAIbkSyAjkwTcaEc3Iu0o9A27X1/kdXrizhZkGuSKScRQtRzclfAMpOTcGdXCsqxeWlpGy3XjqaW8CpLORg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.0.3", + "estree-walker": "^3.0.3", + "magic-string": "^1.2.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/mocker/node_modules/magic-string": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.3.tgz", + "integrity": "sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/@vitest/spy": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.3.tgz", + "integrity": "sha512-XhFysQTB8AZ+P4gMi+Lpo99vg2AZi0qKpaB9yXQl37+CaMEAPO3iH/wGVnSyL5MPERiLezpqTVtrR6UZH5GCXg==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/aria-hidden": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/aria-hidden/-/aria-hidden-1.2.6.tgz", + "integrity": "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/aria-query": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz", + "integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==", + "dev": true, + "license": "Apache-2.0", + "peer": true, + "dependencies": { + "dequal": "^2.0.3" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", "dev": true, "license": "MIT", - "dependencies": { - "@babel/core": "^7.28.0", - "@babel/plugin-transform-react-jsx-self": "^7.27.1", - "@babel/plugin-transform-react-jsx-source": "^7.27.1", - "@rolldown/pluginutils": "1.0.0-beta.27", - "@types/babel__core": "^7.20.5", - "react-refresh": "^0.17.0" - }, "engines": { - "node": "^14.18.0 || >=16.0.0" - }, - "peerDependencies": { - "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" + "node": ">=12" } }, "node_modules/baseline-browser-mapping": { @@ -1224,6 +3541,16 @@ "node": ">=6.0.0" } }, + "node_modules/bidi-js": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.1.0.tgz", + "integrity": "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==", + "dev": true, + "license": "MIT", + "dependencies": { + "require-from-string": "^2.0.2" + } + }, "node_modules/browserslist": { "version": "4.28.7", "resolved": "https://mirrors.huaweicloud.com/repository/npm/browserslist/-/browserslist-4.28.7.tgz", @@ -1279,6 +3606,49 @@ ], "license": "CC-BY-4.0" }, + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/class-variance-authority": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/class-variance-authority/-/class-variance-authority-0.7.1.tgz", + "integrity": "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==", + "license": "Apache-2.0", + "dependencies": { + "clsx": "^2.1.1" + }, + "funding": { + "url": "https://polar.sh/cva" + } + }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/cn": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/cn/-/cn-0.4.0.tgz", + "integrity": "sha512-qOAeUhPwPzBxx6jaeQdo646XIKliKHc2j1ZF7Ngb1o0pJZKH5gq8FkA0aVdUdPFUDXNXyUCXpCtoJISo6dhizg==", + "license": "MIT", + "bin": { + "cn": "bin/cn.mjs" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -1286,142 +3656,654 @@ "dev": true, "license": "MIT" }, + "node_modules/css-tree": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", + "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "mdn-data": "2.27.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, "node_modules/csstype": { "version": "3.2.3", "resolved": "https://mirrors.huaweicloud.com/repository/npm/csstype/-/csstype-3.2.3.tgz", "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/data-urls": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-8.0.0.tgz", + "integrity": "sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.1.2" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://mirrors.huaweicloud.com/repository/npm/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/detect-node-es": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/detect-node-es/-/detect-node-es-1.1.0.tgz", + "integrity": "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==", + "license": "MIT" + }, + "node_modules/dom-accessibility-api": { + "version": "0.5.16", + "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", + "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/electron-to-chromium": { + "version": "1.5.396", + "resolved": "https://mirrors.huaweicloud.com/repository/npm/electron-to-chromium/-/electron-to-chromium-1.5.396.tgz", + "integrity": "sha512-yHiw2Y3C3H9U6TMbOfoWK/BPreiOPXRfTWPBwQBoZG6/8TB6eOPnsy5oaRYuatR7Fw2SJ4kKforgufeo7fq0EQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/enhanced-resolve": { + "version": "5.26.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.26.0.tgz", + "integrity": "sha512-9vhedylFonb2YGogzUKX6+Ja72gOJbN1QHAqdrvqLwhdl/QWbKopzoUC9EbQNVsAns/bx/4uyqalrQAoy1IByw==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.3.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/entities": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz", + "integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://mirrors.huaweicloud.com/repository/npm/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://mirrors.huaweicloud.com/repository/npm/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://mirrors.huaweicloud.com/repository/npm/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/get-nonce": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-nonce/-/get-nonce-1.0.1.tgz", + "integrity": "sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/html-encoding-sniffer": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-7.0.0.tgz", + "integrity": "sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.15.1" + }, + "engines": { + "node": "^22.13.0 || >=24.0.0" + } + }, + "node_modules/input-otp": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/input-otp/-/input-otp-1.5.0.tgz", + "integrity": "sha512-3AcfdW1sNG0FmSA5hHMBXG7jNW5CdcdKs8ln8JOmn6S2SRkoXoJx+2UwC+ZvjflfnOdHJx0SfQ9/YjlxVYLtGQ==", + "license": "MIT", + "peerDependencies": { + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc" + } + }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/jiti": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", + "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", + "dev": true, + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://mirrors.huaweicloud.com/repository/npm/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "license": "MIT" + }, + "node_modules/jsdom": { + "version": "30.1.2", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-30.1.2.tgz", + "integrity": "sha512-0FFE/jE1rppmVfUrJUgxqXjcwolZYIGtAgj1pTussMhNZxIxi7W/PvfWaMNroGi2B36X1IKHbexpZ9DhkoOPiQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^7.1.3", + "@asamuzakjp/dom-selector": "^9.2.4", + "@bramus/specificity": "^2.4.2", + "@csstools/css-syntax-patches-for-csstree": "^1.1.15", + "@exodus/bytes": "^1.16.0", + "css-tree": "^3.2.1", + "data-urls": "^8.0.0", + "decimal.js": "^10.6.0", + "html-encoding-sniffer": "^7.0.0", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.5.3", + "parse5": "^8.0.1", + "saxes": "^6.0.0", + "tough-cookie": "^6.0.2", + "undici": "^8.11.2", + "w3c-xmlserializer": "^6.0.0", + "webidl-conversions": "^8.0.1", + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.2.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "peerDependencies": { + "canvas": "^3.2.3" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/jsdom/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://mirrors.huaweicloud.com/repository/npm/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://mirrors.huaweicloud.com/repository/npm/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", "dev": true, - "license": "MIT" + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } }, - "node_modules/debug": { - "version": "4.4.3", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "node_modules/lightningcss": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", + "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==", "dev": true, - "license": "MIT", + "license": "MPL-2.0", "dependencies": { - "ms": "^2.1.3" + "detect-libc": "^2.0.3" }, "engines": { - "node": ">=6.0" + "node": ">= 12.0.0" }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.32.0", + "lightningcss-darwin-arm64": "1.32.0", + "lightningcss-darwin-x64": "1.32.0", + "lightningcss-freebsd-x64": "1.32.0", + "lightningcss-linux-arm-gnueabihf": "1.32.0", + "lightningcss-linux-arm64-gnu": "1.32.0", + "lightningcss-linux-arm64-musl": "1.32.0", + "lightningcss-linux-x64-gnu": "1.32.0", + "lightningcss-linux-x64-musl": "1.32.0", + "lightningcss-win32-arm64-msvc": "1.32.0", + "lightningcss-win32-x64-msvc": "1.32.0" } }, - "node_modules/electron-to-chromium": { - "version": "1.5.396", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/electron-to-chromium/-/electron-to-chromium-1.5.396.tgz", - "integrity": "sha512-yHiw2Y3C3H9U6TMbOfoWK/BPreiOPXRfTWPBwQBoZG6/8TB6eOPnsy5oaRYuatR7Fw2SJ4kKforgufeo7fq0EQ==", + "node_modules/lightningcss-android-arm64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz", + "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==", + "cpu": [ + "arm64" + ], "dev": true, - "license": "ISC" + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } }, - "node_modules/esbuild": { - "version": "0.21.5", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/esbuild/-/esbuild-0.21.5.tgz", - "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", + "node_modules/lightningcss-darwin-arm64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz", + "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==", + "cpu": [ + "arm64" + ], "dev": true, - "hasInstallScript": true, - "license": "MIT", - "bin": { - "esbuild": "bin/esbuild" + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz", + "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], "engines": { - "node": ">=12" + "node": ">= 12.0.0" }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.21.5", - "@esbuild/android-arm": "0.21.5", - "@esbuild/android-arm64": "0.21.5", - "@esbuild/android-x64": "0.21.5", - "@esbuild/darwin-arm64": "0.21.5", - "@esbuild/darwin-x64": "0.21.5", - "@esbuild/freebsd-arm64": "0.21.5", - "@esbuild/freebsd-x64": "0.21.5", - "@esbuild/linux-arm": "0.21.5", - "@esbuild/linux-arm64": "0.21.5", - "@esbuild/linux-ia32": "0.21.5", - "@esbuild/linux-loong64": "0.21.5", - "@esbuild/linux-mips64el": "0.21.5", - "@esbuild/linux-ppc64": "0.21.5", - "@esbuild/linux-riscv64": "0.21.5", - "@esbuild/linux-s390x": "0.21.5", - "@esbuild/linux-x64": "0.21.5", - "@esbuild/netbsd-x64": "0.21.5", - "@esbuild/openbsd-x64": "0.21.5", - "@esbuild/sunos-x64": "0.21.5", - "@esbuild/win32-arm64": "0.21.5", - "@esbuild/win32-ia32": "0.21.5", - "@esbuild/win32-x64": "0.21.5" + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "node_modules/escalade": { - "version": "3.2.0", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/escalade/-/escalade-3.2.0.tgz", - "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "node_modules/lightningcss-freebsd-x64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz", + "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==", + "cpu": [ + "x64" + ], "dev": true, - "license": "MIT", + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], "engines": { - "node": ">=6" + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz", + "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==", + "cpu": [ + "arm" + ], "dev": true, - "hasInstallScript": true, - "license": "MIT", + "license": "MPL-2.0", "optional": true, "os": [ - "darwin" + "linux" ], "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "node_modules/gensync": { - "version": "1.0.0-beta.2", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/gensync/-/gensync-1.0.0-beta.2.tgz", - "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz", + "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==", + "cpu": [ + "arm64" + ], "dev": true, - "license": "MIT", + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": ">=6.9.0" + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "node_modules/js-tokens": { - "version": "4.0.0", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "license": "MIT" + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz", + "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } }, - "node_modules/jsesc": { - "version": "3.1.0", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/jsesc/-/jsesc-3.1.0.tgz", - "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz", + "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==", + "cpu": [ + "x64" + ], "dev": true, - "license": "MIT", - "bin": { - "jsesc": "bin/jsesc" + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz", + "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": ">=6" + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "node_modules/json5": { - "version": "2.2.3", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/json5/-/json5-2.2.3.tgz", - "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz", + "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==", + "cpu": [ + "arm64" + ], "dev": true, - "license": "MIT", - "bin": { - "json5": "lib/cli.js" + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz", + "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], "engines": { - "node": ">=6" + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, "node_modules/loose-envify": { @@ -1446,6 +4328,49 @@ "yallist": "^3.0.2" } }, + "node_modules/lucide-react": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.52.0.tgz", + "integrity": "sha512-TUgPtl5ZI9WgxOcbu4ckaC5B3l1qxPQrCMgb6OfUB9owx/OvSJfcf93SMgUWAxRw5/1XDfh9uI5F5iNGXCcGDQ==", + "license": "ISC", + "peerDependencies": { + "@types/react": "*", + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/lz-string": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz", + "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==", + "dev": true, + "license": "MIT", + "peer": true, + "bin": { + "lz-string": "bin/bin.js" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/mdn-data": { + "version": "2.27.1", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", + "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", + "dev": true, + "license": "CC0-1.0" + }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://mirrors.huaweicloud.com/repository/npm/ms/-/ms-2.1.3.tgz", @@ -1454,9 +4379,9 @@ "license": "MIT" }, "node_modules/nanoid": { - "version": "3.3.16", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/nanoid/-/nanoid-3.3.16.tgz", - "integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==", + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", "dev": true, "funding": [ { @@ -1482,6 +4407,33 @@ "node": ">=18" } }, + "node_modules/obug": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.2.1.tgz", + "integrity": "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/parse5": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz", + "integrity": "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^8.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://mirrors.huaweicloud.com/repository/npm/picocolors/-/picocolors-1.1.1.tgz", @@ -1489,6 +4441,19 @@ "dev": true, "license": "ISC" }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, "node_modules/postcss": { "version": "8.5.23", "resolved": "https://mirrors.huaweicloud.com/repository/npm/postcss/-/postcss-8.5.23.tgz", @@ -1510,12 +4475,115 @@ ], "license": "MIT", "dependencies": { - "nanoid": "^3.3.16", - "picocolors": "^1.1.1", - "source-map-js": "^1.2.1" + "nanoid": "^3.3.16", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/pretty-format": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz", + "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "ansi-regex": "^5.0.1", + "ansi-styles": "^5.0.0", + "react-is": "^17.0.1" + }, + "engines": { + "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/radix-ui": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/radix-ui/-/radix-ui-1.7.0.tgz", + "integrity": "sha512-x+z5TV2v6u0QpAQ4dQfNMcvtIdSQ1Op2oqBEyfDXjNldRZbMTP+hcjr5Iie31bep81Axeioa+70Ww7pZDzTEQQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.7", + "@radix-ui/react-accessible-icon": "1.1.16", + "@radix-ui/react-accordion": "1.2.21", + "@radix-ui/react-alert-dialog": "1.1.24", + "@radix-ui/react-arrow": "1.1.16", + "@radix-ui/react-aspect-ratio": "1.1.16", + "@radix-ui/react-avatar": "1.2.7", + "@radix-ui/react-checkbox": "1.3.12", + "@radix-ui/react-collapsible": "1.1.21", + "@radix-ui/react-collection": "1.1.16", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.2.2", + "@radix-ui/react-context-menu": "2.3.8", + "@radix-ui/react-dialog": "1.2.0", + "@radix-ui/react-direction": "1.1.5", + "@radix-ui/react-dismissable-layer": "1.1.20", + "@radix-ui/react-dropdown-menu": "2.1.25", + "@radix-ui/react-focus-guards": "1.1.6", + "@radix-ui/react-focus-scope": "1.2.0", + "@radix-ui/react-form": "0.2.0", + "@radix-ui/react-hover-card": "1.1.24", + "@radix-ui/react-label": "2.1.16", + "@radix-ui/react-menu": "2.1.25", + "@radix-ui/react-menubar": "1.1.25", + "@radix-ui/react-navigation-menu": "1.3.0", + "@radix-ui/react-one-time-password-field": "0.1.17", + "@radix-ui/react-password-toggle-field": "0.1.12", + "@radix-ui/react-popover": "1.2.0", + "@radix-ui/react-popper": "1.3.8", + "@radix-ui/react-portal": "1.1.18", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.1.11", + "@radix-ui/react-progress": "1.1.17", + "@radix-ui/react-radio-group": "1.4.8", + "@radix-ui/react-roving-focus": "1.1.20", + "@radix-ui/react-scroll-area": "1.3.0", + "@radix-ui/react-select": "2.3.8", + "@radix-ui/react-separator": "1.1.16", + "@radix-ui/react-slider": "1.5.0", + "@radix-ui/react-slot": "1.4.0", + "@radix-ui/react-switch": "1.3.8", + "@radix-ui/react-tabs": "1.1.22", + "@radix-ui/react-toast": "1.2.24", + "@radix-ui/react-toggle": "1.1.19", + "@radix-ui/react-toggle-group": "1.1.20", + "@radix-ui/react-toolbar": "1.1.20", + "@radix-ui/react-tooltip": "1.3.0", + "@radix-ui/react-use-callback-ref": "1.1.4", + "@radix-ui/react-use-controllable-state": "1.2.6", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-escape-keydown": "1.1.5", + "@radix-ui/react-use-is-hydrated": "0.1.3", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-use-size": "1.1.5", + "@radix-ui/react-visually-hidden": "1.2.12" }, - "engines": { - "node": "^10 || ^12 || >=14" + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } } }, "node_modules/react": { @@ -1543,6 +4611,14 @@ "react": "^18.3.1" } }, + "node_modules/react-is": { + "version": "17.0.2", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", + "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", + "dev": true, + "license": "MIT", + "peer": true + }, "node_modules/react-refresh": { "version": "0.17.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/react-refresh/-/react-refresh-0.17.0.tgz", @@ -1553,6 +4629,85 @@ "node": ">=0.10.0" } }, + "node_modules/react-remove-scroll": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.7.2.tgz", + "integrity": "sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q==", + "license": "MIT", + "dependencies": { + "react-remove-scroll-bar": "^2.3.7", + "react-style-singleton": "^2.2.3", + "tslib": "^2.1.0", + "use-callback-ref": "^1.3.3", + "use-sidecar": "^1.1.3" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/react-remove-scroll-bar": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/react-remove-scroll-bar/-/react-remove-scroll-bar-2.3.8.tgz", + "integrity": "sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q==", + "license": "MIT", + "dependencies": { + "react-style-singleton": "^2.2.2", + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/react-style-singleton": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/react-style-singleton/-/react-style-singleton-2.2.3.tgz", + "integrity": "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ==", + "license": "MIT", + "dependencies": { + "get-nonce": "^1.0.0", + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/rollup": { "version": "4.62.2", "resolved": "https://mirrors.huaweicloud.com/repository/npm/rollup/-/rollup-4.62.2.tgz", @@ -1598,6 +4753,19 @@ "fsevents": "~2.3.2" } }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, "node_modules/scheduler": { "version": "0.23.2", "resolved": "https://mirrors.huaweicloud.com/repository/npm/scheduler/-/scheduler-0.23.2.tgz", @@ -1618,15 +4786,141 @@ } }, "node_modules/source-map-js": { - "version": "1.2.1", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", "dev": true, "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" } }, + "node_modules/std-env": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", + "dev": true, + "license": "MIT" + }, + "node_modules/tailwindcss": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.3.tgz", + "integrity": "sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/tapable": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.3.tgz", + "integrity": "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/tinybench": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.0.tgz", + "integrity": "sha512-78U2TlB2CnVenajOFzf3BKSm0J6oz5L0NV7g32LCPccvYc0lbWvys4d3uUUCS2B1N8PAf2+aekR8i1KbC3HO7Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tldts": { + "version": "7.4.16", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.16.tgz", + "integrity": "sha512-QwBER5KMR86IIjpIiO7H/Z3IMJPsZ1A6RKPAqzTTgOyUQUSt9FdnKcqhTaJmkY6HVrgouZHZR0ncK5QxvmnQeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^7.4.16" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "7.4.16", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.16.tgz", + "integrity": "sha512-MDolfaSJtlSK5Y0A1xl3277ekubZwobpBjugknDizI9O5Rm60a1m8k4ICK+MRsCDzPygT81mp3BBf5RKDlFRfA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tough-cookie": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz", + "integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^7.0.5" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-7.0.0.tgz", + "integrity": "sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/tw-animate-css": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/tw-animate-css/-/tw-animate-css-1.4.0.tgz", + "integrity": "sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/Wombosvideo" + } + }, "node_modules/typescript": { "version": "5.9.3", "resolved": "https://mirrors.huaweicloud.com/repository/npm/typescript/-/typescript-5.9.3.tgz", @@ -1641,6 +4935,16 @@ "node": ">=14.17" } }, + "node_modules/undici": { + "version": "8.11.2", + "resolved": "https://registry.npmjs.org/undici/-/undici-8.11.2.tgz", + "integrity": "sha512-u4UB2/IrKdU6lFxumHmmo1a3fCQO5tzQllRorfoRS63txhrB7xTpSn1PftwC4qEHkOaqP95fCWW4lJzwErwzhQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22.19.0" + } + }, "node_modules/undici-types": { "version": "6.21.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/undici-types/-/undici-types-6.21.0.tgz", @@ -1679,22 +4983,68 @@ "browserslist": ">= 4.21.0" } }, + "node_modules/use-callback-ref": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/use-callback-ref/-/use-callback-ref-1.3.3.tgz", + "integrity": "sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/use-sidecar": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/use-sidecar/-/use-sidecar-1.1.3.tgz", + "integrity": "sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ==", + "license": "MIT", + "dependencies": { + "detect-node-es": "^1.1.0", + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, "node_modules/vite": { - "version": "5.4.21", - "resolved": "https://mirrors.huaweicloud.com/repository/npm/vite/-/vite-5.4.21.tgz", - "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==", + "version": "6.4.3", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz", + "integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==", "dev": true, "license": "MIT", "dependencies": { - "esbuild": "^0.21.3", - "postcss": "^8.4.43", - "rollup": "^4.20.0" + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" }, "bin": { "vite": "bin/vite.js" }, "engines": { - "node": "^18.0.0 || >=20.0.0" + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" }, "funding": { "url": "https://github.com/vitejs/vite?sponsor=1" @@ -1703,19 +5053,25 @@ "fsevents": "~2.3.3" }, "peerDependencies": { - "@types/node": "^18.0.0 || >=20.0.0", + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", - "terser": "^5.4.0" + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" }, "peerDependenciesMeta": { "@types/node": { "optional": true }, + "jiti": { + "optional": true + }, "less": { "optional": true }, @@ -1736,9 +5092,186 @@ }, "terser": { "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.3.tgz", + "integrity": "sha512-xMw97S3rjdtj5dkVat7jCsqWBpvchs3RlpQctUqwJD0KkERk40vz2fJ77lDwW/Vzh/pk18eItYAzkodhSes3jQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.0.3", + "chai": "^6.2.2", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.2.3", + "obug": "^2.1.4", + "picomatch": "^4.0.7", + "std-env": "^4.2.0", + "tinybench": "^6.1.4", + "tinyexec": "^1.3.0", + "tinyglobby": "^0.2.17", + "why-is-node-running": "3.2.1" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.0.3", + "@vitest/browser-preview": "5.0.3", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.0.3", + "@vitest/coverage-v8": "5.0.3", + "@vitest/ui": "5.0.3", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false } } }, + "node_modules/vitest/node_modules/magic-string": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.3.tgz", + "integrity": "sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/w3c-xmlserializer": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-6.0.0.tgz", + "integrity": "sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/webidl-conversions": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-mimetype": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", + "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-url": { + "version": "17.2.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.2.0.tgz", + "integrity": "sha512-IhLIHNcBrzIixC5XXsbr4DxdjajyA5vQ5RwGZMtrUp+GbtE5Nrsge9QKau7jXrC0aTXLYGV0xiW7Tb4YS2aomw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.16.0", + "tr46": "^7.0.0", + "webidl-conversions": "^8.0.1" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, + "node_modules/why-is-node-running": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", + "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", + "dev": true, + "license": "MIT", + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=20.11" + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + }, "node_modules/yallist": { "version": "3.1.1", "resolved": "https://mirrors.huaweicloud.com/repository/npm/yallist/-/yallist-3.1.1.tgz", diff --git a/web/package.json b/web/package.json index 29cbe75..e2de1ec 100644 --- a/web/package.json +++ b/web/package.json @@ -6,18 +6,33 @@ "scripts": { "dev": "vite", "build": "tsc && vite build", - "postbuild": "node -e \"require('node:fs').closeSync(require('node:fs').openSync('../internal/webui/dist/.gitkeep','a'))\"" + "postbuild": "node -e \"require('node:fs').closeSync(require('node:fs').openSync('../internal/webui/dist/.gitkeep','a'))\"", + "test": "vitest run" }, "dependencies": { + "@fontsource-variable/geist": "^5.3.0", + "@fontsource-variable/geist-mono": "^5.3.0", + "@fontsource-variable/noto-sans-sc": "^5.3.0", + "class-variance-authority": "^0.7.1", + "cn": "^0.4.0", + "input-otp": "^1.5.0", + "lucide-react": "^1.52.0", + "radix-ui": "^1.7.0", "react": "^18.3.1", - "react-dom": "^18.3.1" + "react-dom": "^18.3.1", + "tw-animate-css": "^1.4.0" }, "devDependencies": { + "@tailwindcss/vite": "^4.3.3", + "@testing-library/react": "^16.3.3", "@types/node": "^22.10.2", "@types/react": "^18.3.12", "@types/react-dom": "^18.3.1", - "@vitejs/plugin-react": "^4.3.4", + "@vitejs/plugin-react": "^4.7.0", + "jsdom": "^30.1.2", + "tailwindcss": "^4.3.3", "typescript": "^5.6.3", - "vite": "^5.4.11" + "vite": "^6.4.3", + "vitest": "^5.0.3" } } diff --git a/web/src/App.tsx b/web/src/App.tsx index 89ecdda..21b83ea 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -1,85 +1,142 @@ -import { useEffect, useState } from "react"; +import { useEffect, useRef, useState } from "react"; +import { ShieldCheck } from "lucide-react"; +import { Card } from "@/components/ui/card"; import { post, errorText, usePanelStore } from "./api"; import type { FriendlyError } from "./errors"; -import { StatusCard, stateMeta } from "./components/StatusCard"; +import { StatusCard } from "./components/StatusCard"; import { UserCard } from "./components/UserCard"; import { SmsDialog } from "./components/SmsDialog"; import { TrustDevices } from "./components/TrustDevices"; import { EventsList } from "./components/EventsList"; - +import { ProxyCards } from "./components/ProxyCards"; +import { ThemeToggle } from "./components/ThemeToggle"; +import { ConfirmDialog } from "./components/ConfirmDialog"; export default function App() { const { snap, connected } = usePanelStore(); const [reloginBusy, setReloginBusy] = useState(false); const [reloginError, setReloginError] = useState(null); - - // Any panel state change (relogin accepted, another login finished) - // supersedes a stale relogin error. + const [confirm, setConfirm] = useState(false); + const [smsOpen, setSMSOpen] = useState(false); + const generation = snap?.generation; const state = snap?.state; + const pendingGen = snap?.sms_pending ? snap.sms_gen : 0; + const currentSession = useRef(""); + currentSession.current = `${generation}:${state}`; + const reloginInFlight = useRef(false); useEffect(() => { setReloginError(null); - }, [state]); - + setConfirm(false); + }, [state, generation]); + useEffect(() => { + setSMSOpen(pendingGen !== 0); + }, [pendingGen]); const relogin = async () => { - if (!window.confirm("确定重新登录?将丢弃当前会话并重新完整登录,可能需要短信验证。")) return; + if (!connected || reloginInFlight.current) return; + const requestedSession = currentSession.current; + reloginInFlight.current = true; setReloginBusy(true); setReloginError(null); try { await post("/api/relogin", {}); - // 202:后续进度经 SSE 推送(connecting → online/offline)。 - } catch (err) { - setReloginError( - errorText(err, "重新登录失败", { 409: "已有登录正在进行,请等待完成" }), - ); + } catch (error) { + if (currentSession.current === requestedSession) + setReloginError( + errorText(error, "重新登录失败", { + 409: "已有登录正在进行,请等待完成", + }), + ); } finally { + reloginInFlight.current = false; setReloginBusy(false); } }; - - if (!snap) { - return ( -
-
-

geekTrust 面板

- {connected ? ( -

正在加载状态…

- ) : ( - <> -

无法连接面板服务,正在自动重试…

-

- 请确认 geektrust run 正在运行,且访问地址与配置中的 web.listen 一致。 -

- - )} -
-
- ); - } - - const meta = stateMeta(snap.state, !connected); return ( -
-
-

geekTrust 面板

- {meta.label} + <> +
+
+
+ + + + geekTrust +
+ + / 本地控制台 + +
+ + + {connected ? "服务在线" : "服务离线"} + + +
+
- {!connected && ( -
- 与 geekTrust 的连接已断开,正在重连。以下为最后已知状态。 +
+
+
+

连接概览

+

查看本机会话与代理。

+
- )} -
- - -
- - - -
+ {!snap ? ( + +

+ {connected ? "正在加载状态…" : "正在连接面板服务…"} +

+

+ 请确认 geektrust run 正在运行。连接失败时会自动重试。 +

+
+ ) : ( + <> + {!connected && ( +
+ 与面板服务的连接已断开,正在重连。以下为最后已知状态。 +
+ )} +
+ setConfirm(true)} + onSMS={() => setSMSOpen(true)} + reloginBusy={reloginBusy} + reloginError={reloginError} + /> + +
+ + + + {!!pendingGen && ( + + )} + + )} +
+ void relogin()} + disabled={ + !connected || + reloginBusy || + state === "connecting" || + state === "sms_required" + } + /> + ); } diff --git a/web/src/api.test.tsx b/web/src/api.test.tsx new file mode 100644 index 0000000..8bcec9e --- /dev/null +++ b/web/src/api.test.tsx @@ -0,0 +1,64 @@ +import { act, render, screen } from "@testing-library/react"; +import { beforeEach, expect, it, vi } from "vitest"; +import type { Snapshot } from "./types"; +class Stream { + static instances: Stream[] = []; + onopen: (() => void) | null = null; + onerror: (() => void) | null = null; + onmessage: ((event: { data: string }) => void) | null = null; + close = vi.fn(); + constructor() { + Stream.instances.push(this); + } +} +const snapshot: Snapshot = { + generation: 1, + state: "online", + since: "2026-10-06T00:00:00Z", + last_error: null, + user: null, + device_id: "fixture", + client_type: "client", + controller_host: "vpn.example.edu.cn", + gateways: [], + dns: [], + proxy: { socks5: null, http: null }, + sms_pending: false, + sms_gen: 0, + events_dropped: 0, + events: [], +}; +beforeEach(() => { + vi.resetModules(); + Stream.instances = []; + vi.stubGlobal("EventSource", Stream); + vi.stubGlobal( + "fetch", + vi.fn(() => new Promise(() => {})), + ); +}); +it("waits for a current snapshot before declaring a reconnected panel live", async () => { + const { usePanelStore } = await import("./api"); + function Probe() { + const state = usePanelStore(); + return ( + + {state.connected ? "live" : "stale"}:{state.snap?.generation ?? 0} + + ); + } + render(); + const stream = Stream.instances[0]; + act(() => stream.onmessage?.({ data: JSON.stringify(snapshot) })); + expect(screen.getByText("live:1")).toBeTruthy(); + act(() => stream.onerror?.()); + expect(screen.getByText("stale:1")).toBeTruthy(); + act(() => stream.onopen?.()); + expect(screen.getByText("stale:1")).toBeTruthy(); + act(() => + stream.onmessage?.({ + data: JSON.stringify({ ...snapshot, generation: 2 }), + }), + ); + expect(screen.getByText("live:2")).toBeTruthy(); +}); diff --git a/web/src/api.ts b/web/src/api.ts index d8aac42..47750c6 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -6,8 +6,8 @@ import { friendlyError, type FriendlyError } from "./errors"; // Live store. The SSE stream feeds full snapshots; a one-shot /api/status // fetch seeds the first paint and is discarded once stream data exists, so a // slow fetch can never overwrite fresher data. `connected` mirrors the SSE -// link so the UI can flag stale data instead of presenting a dead process as -// "online". +// freshness so the UI cannot enable actions before a reconnected stream has +// delivered its current snapshot. export interface PanelStore { snap: Snapshot | null; @@ -25,13 +25,11 @@ function publish(next: PanelStore) { listeners.forEach((l) => l()); } -function connect() { +function connect(epoch: number) { const es = new EventSource("/api/events"); stream = es; - es.onopen = () => { - if (!store.connected) publish({ ...store, connected: true }); - }; es.onmessage = (e) => { + if (epoch !== streamEpoch) return; let snap: Snapshot; try { snap = JSON.parse(e.data) as Snapshot; @@ -42,6 +40,7 @@ function connect() { publish({ snap, connected: true }); }; es.onerror = () => { + if (epoch !== streamEpoch) return; // EventSource retries the connection itself. if (store.connected) publish({ ...store, connected: false }); }; @@ -64,8 +63,9 @@ function subscribePanel(cb: () => void) { listeners.add(cb); if (listeners.size === 1) { sawStream = false; - connect(); - void seed(++streamEpoch); + const epoch = ++streamEpoch; + connect(epoch); + void seed(epoch); } return () => { listeners.delete(cb); diff --git a/web/src/components/ConfirmDialog.tsx b/web/src/components/ConfirmDialog.tsx new file mode 100644 index 0000000..adf9d5d --- /dev/null +++ b/web/src/components/ConfirmDialog.tsx @@ -0,0 +1,54 @@ +import { + AlertDialog, + AlertDialogContent, + AlertDialogHeader, + AlertDialogTitle, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogCancel, + AlertDialogAction, +} from "@/components/ui/alert-dialog"; +export function ConfirmDialog({ + open, + onOpenChange, + title, + description, + action, + onConfirm, + disabled = false, + destructive = false, +}: { + open: boolean; + onOpenChange: (open: boolean) => void; + title: string; + description: string; + action: string; + onConfirm: () => void; + disabled?: boolean; + destructive?: boolean; +}) { + return ( + + + + {title} + {description} + + + 取消 + + {action} + + + + + ); +} diff --git a/web/src/components/CopyButton.tsx b/web/src/components/CopyButton.tsx new file mode 100644 index 0000000..3dda193 --- /dev/null +++ b/web/src/components/CopyButton.tsx @@ -0,0 +1,56 @@ +import { useEffect, useRef, useState } from "react"; +import { Check, Copy } from "lucide-react"; +import { Button } from "@/components/ui/button"; +function fallbackCopy(text: string): boolean { + const previous = document.activeElement; + const input = document.createElement("textarea"); + input.value = text; + input.style.position = "fixed"; + input.style.opacity = "0"; + document.body.appendChild(input); + input.select(); + try { + return document.execCommand("copy"); + } catch { + return false; + } finally { + input.remove(); + if (previous instanceof HTMLElement) previous.focus(); + } +} +export function CopyButton({ + value, + label = "复制", +}: { + value: string; + label?: string; +}) { + const [result, setResult] = useState<"ok" | "fail" | null>(null); + const timer = useRef(); + useEffect(() => () => window.clearTimeout(timer.current), []); + const copy = async () => { + let ok = false; + try { + await navigator.clipboard.writeText(value); + ok = true; + } catch { + ok = fallbackCopy(value); + } + setResult(ok ? "ok" : "fail"); + window.clearTimeout(timer.current); + timer.current = window.setTimeout(() => setResult(null), 2000); + }; + return ( + + ); +} diff --git a/web/src/components/ErrorText.tsx b/web/src/components/ErrorText.tsx index 4957d8e..be6d1c4 100644 --- a/web/src/components/ErrorText.tsx +++ b/web/src/components/ErrorText.tsx @@ -1,29 +1,25 @@ -import { useState } from "react"; import type { FriendlyError } from "../errors"; - -// ErrorText shows the actionable line and keeps the original Go error chain -// behind a toggle: out of the way for normal use, still there when the raw -// controller code or transport detail is what you actually need. -export function ErrorText({ error, prefix }: { error: FriendlyError; prefix?: string }) { - const [open, setOpen] = useState(false); - const { summary, detail } = error; +export function ErrorText({ + error, + prefix, +}: { + error: FriendlyError; + prefix?: string; +}) { return ( -
-

+

+

{prefix} - {summary} - {detail && ( - - )} + {error.summary}

- {open && detail &&
{detail}
} + {error.detail && ( +
+ 错误详情 +
+            {error.detail}
+          
+
+ )}
); } diff --git a/web/src/components/EventsList.tsx b/web/src/components/EventsList.tsx index af1875a..aa17b95 100644 --- a/web/src/components/EventsList.tsx +++ b/web/src/components/EventsList.tsx @@ -1,53 +1,113 @@ +import { useState } from "react"; +import { Card } from "@/components/ui/card"; +import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, + DialogClose, +} from "@/components/ui/dialog"; import { friendlyError } from "../errors"; import type { HistoryEvent } from "../types"; - -const KIND_LABEL: Record = { - login_start: "开始登录", - login_success: "登录成功", - restore_success: "恢复会话", - login_failed: "登录失败", - invalidated: "会话失效", -}; - -function formatTime(ts: string): string { - const d = new Date(ts); - if (Number.isNaN(d.getTime())) return ts; - return d.toLocaleString("zh-CN", { - month: "2-digit", - day: "2-digit", - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - hour12: false, - }); +function ActivityRows({ events }: { events: HistoryEvent[] }) { + return ( +
    + {events.map((event, index) => { + const date = new Date(event.ts); + const color = ["login_success", "restore_success"].includes(event.kind) + ? "bg-success" + : event.kind === "login_failed" + ? "bg-destructive" + : event.kind === "interaction_required" + ? "bg-warning" + : "bg-muted-foreground"; + const text = + event.kind === "login_failed" + ? friendlyError(event.message, "登录失败").summary + : event.kind === "interaction_required" + ? "登录需要验证,请重新登录" + : event.message; + return ( +
  • + +
  • + ); + })} +
+ ); } - -export function EventsList({ events, dropped }: { events: HistoryEvent[]; dropped: number }) { +export function EventsList({ + events, + dropped, +}: { + events: HistoryEvent[]; + dropped: number; +}) { + const [open, setOpen] = useState(false); + const newest = [...events].reverse(); return ( -
-

事件

- {dropped > 0 &&

另有 {dropped} 条较早的事件未能记录。

} - {events.length === 0 ? ( -

暂无事件

+ +
+

最近活动

+
+ + 最近 {Math.min(10, events.length)} 条 + + +
+
+ {events.length ? ( + ) : ( -
    - {[...events].reverse().map((ev, i) => { - // Only login_failed carries a wrapped Go error chain; every other - // kind is already a plain sentence that must not be rewritten. - const text = - ev.kind === "login_failed" ? friendlyError(ev.message, "登录失败").summary : ev.message; - return ( -
  • - {formatTime(ev.ts)} - {KIND_LABEL[ev.kind] ?? ev.kind} - - {text} - -
  • - ); - })} -
+

暂无活动记录

+ )} + {dropped > 0 && ( +

+ 另有 {dropped} 条事件未能记录。 +

)} -
+ + + + 活动记录 + 共 {events.length} 条 + +
+ +
+ + + + + +
+
+ ); } diff --git a/web/src/components/ProxyCards.tsx b/web/src/components/ProxyCards.tsx new file mode 100644 index 0000000..9691d0b --- /dev/null +++ b/web/src/components/ProxyCards.tsx @@ -0,0 +1,48 @@ +import { SquareTerminal } from "lucide-react"; +import { Card } from "@/components/ui/card"; +import type { Snapshot } from "../types"; +import { CopyButton } from "./CopyButton"; +export function ProxyCards({ + snap, + connected, +}: { + snap: Snapshot; + connected: boolean; +}) { + return ( +
+ {(["socks5", "http"] as const).map((type) => { + const address = snap.proxy[type]; + const available = !!address && connected && snap.state === "online"; + return ( + +
+ +

{type === "socks5" ? "SOCKS5" : "HTTP"} 代理

+ + {!address + ? "已禁用" + : available + ? "可用" + : !connected + ? "状态未知" + : "等待连接"} + +
+
+ {address || "未启用"} + {address && } +
+

+ {type === "socks5" + ? "用于支持 SOCKS5 的应用" + : "用于 HTTP 代理设置"} +

+
+ ); + })} +
+ ); +} diff --git a/web/src/components/SmsDialog.tsx b/web/src/components/SmsDialog.tsx index 7b207f2..68f36f1 100644 --- a/web/src/components/SmsDialog.tsx +++ b/web/src/components/SmsDialog.tsx @@ -1,122 +1,179 @@ import { useEffect, useRef, useState } from "react"; +import { KeyRound } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { + InputOTP, + InputOTPGroup, + InputOTPSlot, +} from "@/components/ui/input-otp"; +import { REGEXP_ONLY_DIGITS } from "input-otp"; +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, +} from "@/components/ui/dialog"; import { post, postJSON, ApiError, errorText } from "../api"; import type { FriendlyError } from "../errors"; import type { Snapshot } from "../types"; import { ErrorText } from "./ErrorText"; - -const RESEND_COOLDOWN = 60; - -// SmsDialog pops up whenever the controller demands SMS verification. The -// submission carries the current generation so a stale dialog can never -// deliver a code into a newer prompt; all local state resets whenever the -// generation changes. The resend button carries a client-side cooldown — -// the controller rate-limits resends anyway (429), so don't invite it. -export function SmsDialog({ snap }: { snap: Snapshot }) { +export function SmsDialog({ + snap, + connected, + open, + onOpenChange, +}: { + snap: Snapshot; + connected: boolean; + open: boolean; + onOpenChange: (open: boolean) => void; +}) { const [code, setCode] = useState(""); const [busy, setBusy] = useState(false); + const [resending, setResending] = useState(false); const [error, setError] = useState(null); const [notice, setNotice] = useState(null); - const [cooldown, setCooldown] = useState(RESEND_COOLDOWN); - const inputRef = useRef(null); - - const gen = snap.sms_pending ? snap.sms_gen : 0; - const currentGen = useRef(gen); - currentGen.current = gen; + const [cooldown, setCooldown] = useState(60); + const active = useRef(true); + const inFlight = useRef(false); useEffect(() => { - if (gen === 0) return; - setCode(""); - setBusy(false); - setError(null); - setNotice(null); - setCooldown(RESEND_COOLDOWN); - inputRef.current?.focus(); - const timer = window.setInterval(() => setCooldown((s) => (s > 0 ? s - 1 : 0)), 1000); - return () => window.clearInterval(timer); - }, [gen]); - - if (!snap.sms_pending) return null; - - const submit = async (e: React.FormEvent) => { - e.preventDefault(); - if (busy || code.length !== 6) return; + active.current = true; + const timer = window.setInterval( + () => setCooldown((value) => Math.max(0, value - 1)), + 1000, + ); + return () => { + active.current = false; + window.clearInterval(timer); + }; + }, []); + // App keys this dialog by SMS generation, so old responses cannot affect a new prompt. + const submit = async (event: React.FormEvent) => { + event.preventDefault(); + if (!connected || inFlight.current || code.length !== 6) return; + inFlight.current = true; setBusy(true); setError(null); setNotice(null); - const requestedGen = gen; try { - await post("/api/sms", { code, gen: requestedGen }); - if (currentGen.current !== requestedGen) return; - // 202 = 已投递;登录结果经 SSE 推送。验证失败会结束本次登录, - // 弹窗随之关闭,状态卡片会显示失败原因。 - setNotice("已提交,等待服务端验证…"); - } catch (err) { - if (currentGen.current !== requestedGen) return; + await post("/api/sms", { code, gen: snap.sms_gen }); + if (active.current) setNotice("已提交,等待服务端验证…"); + } catch (error) { + if (!active.current) return; + inFlight.current = false; setBusy(false); setError( - errorText(err, "提交失败", { + errorText(error, "提交失败", { 400: "验证码需为 6 位数字", - 409: "验证码已在其他页面或终端提交,或本轮验证已结束", + 409: "验证码已提交,或本轮验证已结束", }), ); } }; - const resend = async () => { - if (busy || cooldown > 0) return; + if (!connected || inFlight.current || cooldown > 0) return; + inFlight.current = true; + setResending(true); setError(null); setNotice(null); - const requestedGen = gen; try { - const result = await postJSON<{ restarting?: boolean }>("/api/sms/resend", { gen: requestedGen }); - if (currentGen.current !== requestedGen) return; - setNotice(result.restarting ? "验证已过期,正在重新登录并发送新验证码…" : "验证码已重新发送"); - setCooldown(RESEND_COOLDOWN); - } catch (err) { - if (currentGen.current !== requestedGen) return; - if (err instanceof ApiError && err.status === 429) { - // 上一条验证码仍在有效期内:直接输入它,同时进入冷却防止连点。 - setCooldown(RESEND_COOLDOWN); - setError(errorText(err, "发送过于频繁,上一条验证码仍然有效")); - } else { - setError(errorText(err, "重发失败", { 409: "本轮验证已结束" })); + const result = await postJSON<{ restarting?: boolean }>( + "/api/sms/resend", + { gen: snap.sms_gen }, + ); + if (!active.current) return; + setNotice( + result.restarting + ? "验证已过期,正在重新登录并发送新验证码…" + : "验证码已重新发送", + ); + setCooldown(60); + } catch (error) { + if (!active.current) return; + if (error instanceof ApiError && error.status === 429) setCooldown(60); + setError( + errorText(error, "重发失败", { + 409: "本轮验证已结束", + 429: "发送过于频繁,上一条验证码仍然有效", + }), + ); + } finally { + if (active.current) { + inFlight.current = false; + setResending(false); } } }; - return ( -
-
-

短信验证

-

6 位验证码已发送到你的手机,输入后继续登录。

- setCode(e.target.value.replace(/\D/g, "").slice(0, 6))} - placeholder="6 位验证码" - inputMode="numeric" - autoComplete="one-time-code" - disabled={busy} - className="code-input mono" - aria-label="6 位短信验证码" - /> - {error && } - {notice &&

{notice}

} -
- - + + +
+
-

也可以在运行 geektrust 的终端中输入验证码,以先提交的为准。

- -
+ + 短信验证 + + 6 位验证码已发送到你的手机,输入后继续登录。 + + +
void submit(event)} + className="flex flex-col gap-4" + > + + + {Array.from({ length: 6 }, (_, index) => ( + + ))} + + + {error && } + {notice && ( +

+ {notice} +

+ )} + {!connected && ( +

+ 面板连接已断开,恢复后可继续验证。 +

+ )} + + +

+ 也可以在运行 geektrust 的终端中输入验证码,以先提交的为准。 +

+ + + ); } diff --git a/web/src/components/StatusCard.tsx b/web/src/components/StatusCard.tsx index 42de3a9..24d02d5 100644 --- a/web/src/components/StatusCard.tsx +++ b/web/src/components/StatusCard.tsx @@ -1,55 +1,66 @@ -import type { Snapshot } from "../types"; +import { RefreshCw, LoaderCircle, KeyRound } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { Card } from "@/components/ui/card"; import { friendlyError, type FriendlyError } from "../errors"; +import type { Snapshot } from "../types"; import { ErrorText } from "./ErrorText"; - -const STATE_META: Record = { - online: { label: "在线", className: "pill ok" }, - connecting: { label: "连接中", className: "pill warn" }, - sms_required: { label: "需要短信验证", className: "pill warn" }, - offline: { label: "离线", className: "pill idle" }, -}; - -// stateMeta tolerates unknown states from a newer backend: show them raw -// instead of mislabeling as offline. `stale` marks a snapshot the panel can -// no longer refresh — a green "在线" light on a dead process is a lie. -export function stateMeta(state: string, stale = false): { label: string; className: string } { - const meta = STATE_META[state] ?? { label: state, className: "pill idle" }; - return stale ? { ...meta, className: `${meta.className} stale` } : meta; -} - -export function formatDateTime(iso: string): string { - const d = new Date(iso); - return Number.isNaN(d.getTime()) ? iso : d.toLocaleString("zh-CN", { hour12: false }); -} - -export function StatusCard({ snap, connected, onRelogin, reloginBusy, reloginError }: { +export function StatusCard({ + snap, + connected, + onRelogin, + onSMS, + reloginBusy, + reloginError, +}: { snap: Snapshot; connected: boolean; onRelogin: () => void; + onSMS: () => void; reloginBusy: boolean; reloginError: FriendlyError | null; }) { - const meta = stateMeta(snap.state, !connected); + const states = { + online: ["已连接", "校园资源可通过本地代理访问。"], + offline: ["会话已断开", "重新登录以恢复校园资源访问。"], + connecting: ["正在连接", "正在建立会话,请稍候。"], + sms_required: ["完成验证后连接", "请输入短信验证码,继续本次登录。"], + }; + const [title, description] = states[snap.state] ?? [ + "状态未知", + "等待面板更新连接状态。", + ]; + const working = reloginBusy || snap.state === "connecting"; return ( -
-

状态

-
- {meta.label} - 自 {formatDateTime(snap.since)} + +
+

{title}

+

{description}

{snap.last_error && ( - + )} - {snap.sms_pending &&

等待短信验证码,可在弹窗或终端中输入。

} -
- -
{reloginError && } -
+
+ {snap.sms_pending ? ( + + ) : ( + + )} +
+ ); } diff --git a/web/src/components/ThemeProvider.test.tsx b/web/src/components/ThemeProvider.test.tsx new file mode 100644 index 0000000..464a93a --- /dev/null +++ b/web/src/components/ThemeProvider.test.tsx @@ -0,0 +1,83 @@ +import { act, fireEvent, render, screen } from "@testing-library/react"; +import { beforeEach, expect, it, vi } from "vitest"; +import { ThemeProvider, useTheme } from "./ThemeProvider"; +function Controls() { + const { theme, setTheme } = useTheme(); + return ( + <> + {theme} + + + + + ); +} +let systemDark = false; +let listeners: Set<() => void>; +beforeEach(() => { + localStorage.clear(); + document.documentElement.className = ""; + systemDark = false; + listeners = new Set(); + vi.stubGlobal("matchMedia", () => ({ + get matches() { + return systemDark; + }, + addEventListener: (_: string, fn: () => void) => listeners.add(fn), + removeEventListener: (_: string, fn: () => void) => listeners.delete(fn), + })); +}); +it("follows live system changes and removes the listener when unmounted", () => { + const { unmount } = render( + + + , + ); + expect(document.documentElement.classList.contains("dark")).toBe(false); + act(() => { + systemDark = true; + listeners.forEach((fn) => fn()); + }); + expect(document.documentElement.classList.contains("dark")).toBe(true); + expect(document.documentElement.style.colorScheme).toBe("dark"); + unmount(); + expect(listeners.size).toBe(0); +}); +it("persists an explicit choice and ignores later system changes", () => { + const { unmount } = render( + + + , + ); + fireEvent.click(screen.getByRole("button", { name: "light" })); + act(() => { + systemDark = true; + listeners.forEach((fn) => fn()); + }); + expect(document.documentElement.classList.contains("dark")).toBe(false); + expect(localStorage.getItem("geektrust-theme")).toBe("light"); + unmount(); + render( + + + , + ); + expect(document.documentElement.classList.contains("dark")).toBe(false); + fireEvent.click(screen.getByRole("button", { name: "system" })); + expect(document.documentElement.classList.contains("dark")).toBe(true); +}); +it("falls back to system for invalid saved data and works when storage is blocked", () => { + localStorage.setItem("geektrust-theme", "invalid"); + systemDark = true; + vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { + throw new Error("blocked"); + }); + render( + + + , + ); + expect(document.documentElement.classList.contains("dark")).toBe(true); + fireEvent.click(screen.getByRole("button", { name: "light" })); + expect(document.documentElement.classList.contains("dark")).toBe(false); +}); diff --git a/web/src/components/ThemeProvider.tsx b/web/src/components/ThemeProvider.tsx new file mode 100644 index 0000000..55c2a15 --- /dev/null +++ b/web/src/components/ThemeProvider.tsx @@ -0,0 +1,54 @@ +import { + createContext, + useContext, + useEffect, + useState, + type ReactNode, +} from "react"; +export type Theme = "light" | "dark" | "system"; +const KEY = "geektrust-theme"; +function readTheme(): Theme { + try { + const value = localStorage.getItem(KEY); + if (value === "light" || value === "dark") return value; + } catch { + /* Storage can be unavailable. */ + } + return "system"; +} +const ThemeContext = createContext<{ + theme: Theme; + setTheme: (theme: Theme) => void; +} | null>(null); +export function ThemeProvider({ children }: { children: ReactNode }) { + const [theme, updateTheme] = useState(readTheme); + useEffect(() => { + const media = window.matchMedia("(prefers-color-scheme: dark)"); + const apply = () => { + const dark = theme === "dark" || (theme === "system" && media.matches); + document.documentElement.classList.toggle("dark", dark); + document.documentElement.style.colorScheme = dark ? "dark" : "light"; + }; + apply(); + media.addEventListener("change", apply); + return () => media.removeEventListener("change", apply); + }, [theme]); + const setTheme = (next: Theme) => { + updateTheme(next); + try { + localStorage.setItem(KEY, next); + } catch { + /* The current selection still works. */ + } + }; + return ( + + {children} + + ); +} +export function useTheme() { + const value = useContext(ThemeContext); + if (!value) throw new Error("ThemeProvider is missing"); + return value; +} diff --git a/web/src/components/ThemeToggle.tsx b/web/src/components/ThemeToggle.tsx new file mode 100644 index 0000000..e259266 --- /dev/null +++ b/web/src/components/ThemeToggle.tsx @@ -0,0 +1,47 @@ +import { Sun, Moon, Monitor } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { + DropdownMenu, + DropdownMenuTrigger, + DropdownMenuContent, + DropdownMenuRadioGroup, + DropdownMenuRadioItem, +} from "@/components/ui/dropdown-menu"; +import { useTheme, type Theme } from "./ThemeProvider"; +export function ThemeToggle() { + const { theme, setTheme } = useTheme(); + return ( + + + + + + setTheme(value as Theme)} + > + + + 浅色 + + + + 深色 + + + + 跟随系统 + + + + + ); +} diff --git a/web/src/components/TrustDevices.tsx b/web/src/components/TrustDevices.tsx index 194a692..24a6c74 100644 --- a/web/src/components/TrustDevices.tsx +++ b/web/src/components/TrustDevices.tsx @@ -1,230 +1,405 @@ import { useCallback, useEffect, useRef, useState } from "react"; +import { Laptop, Smartphone, RefreshCw, LoaderCircle } from "lucide-react"; +import { Card } from "@/components/ui/card"; +import { Button } from "@/components/ui/button"; +import { Checkbox } from "@/components/ui/checkbox"; +import { + Table, + TableHeader, + TableBody, + TableRow, + TableHead, + TableCell, +} from "@/components/ui/table"; import { fetchTrustDevices, post, errorText } from "../api"; import type { FriendlyError } from "../errors"; import type { Snapshot, TrustDeviceEntry, TrustDeviceList } from "../types"; import { ErrorText } from "./ErrorText"; - -function deviceLabel(d: TrustDeviceEntry): string { - const fallback = [d.os, d.osVersion].filter(Boolean).join(" ").trim(); - return (d.deviceName ?? "").trim() || fallback || "(未命名设备)"; +import { ConfirmDialog } from "./ConfirmDialog"; +function deviceLabel(device: TrustDeviceEntry) { + return ( + device.deviceName?.trim() || + [device.os, device.osVersion].filter(Boolean).join(" ") || + "未命名设备" + ); } - -const LIST_ERRORS: Record = { +const ERRORS = { 503: "会话未就绪,请稍后重试", - 409: "browser 模式不能绑定授信终端,请将登录模式设为 client 并重启 geektrust", + 409: "当前登录模式不能绑定设备", }; - -export function TrustDevices({ snap, connected }: { snap: Snapshot; connected: boolean }) { - const [list, setList] = useState(null); +type Confirmation = + | { session: string; kind: "logout"; device: TrustDeviceEntry } + | { session: string; kind: "unbind"; ids: string[] }; +export function TrustDevices({ + snap, + connected, +}: { + snap: Snapshot; + connected: boolean; +}) { + const [loaded, setLoaded] = useState<{ + session: string; + list: TrustDeviceList; + } | null>(null); const [error, setError] = useState(null); const [notice, setNotice] = useState(null); const [selected, setSelected] = useState>(new Set()); - // Which mutation is in flight, so the button that was clicked is the one - // that reports progress; null means idle. const [pending, setPending] = useState(null); const [refreshing, setRefreshing] = useState(false); - // Refresh results must never outlive the session they were fetched in. - const epochRef = useRef(0); + const [confirmation, setConfirmation] = useState(null); + const epoch = useRef(0); + const mutation = useRef(null); const sessionKey = `${snap.generation ?? 0}:${snap.state}:${snap.since}:${snap.user?.username ?? ""}`; const sessionRef = useRef(sessionKey); - if (sessionRef.current !== sessionKey) { sessionRef.current = sessionKey; epochRef.current++; } - + if (sessionRef.current !== sessionKey) { + sessionRef.current = sessionKey; + epoch.current++; + mutation.current = null; + } + const list = loaded?.session === sessionKey ? loaded.list : null; const refresh = useCallback(async () => { - const epoch = ++epochRef.current; + const request = ++epoch.current; + const session = sessionRef.current; + setRefreshing(true); setError(null); try { const next = await fetchTrustDevices(); - if (epoch === epochRef.current) setList(next); - } catch (err) { - if (epoch !== epochRef.current) return; - setList(null); - setError(errorText(err, "加载失败", LIST_ERRORS)); + if (request !== epoch.current) return; + setLoaded({ session, list: next }); + const ids = new Set((next.data ?? []).map((device) => device.id)); + setSelected( + (previous) => new Set([...previous].filter((id) => ids.has(id))), + ); + } catch (error) { + if (request !== epoch.current) return; + setLoaded(null); + setError(errorText(error, "加载设备失败", ERRORS)); + } finally { + if (request === epoch.current) setRefreshing(false); } }, []); - useEffect(() => { - if (snap.state === "online") { - void refresh(); - } else { - // Leaving online invalidates every row and in-flight fetch. - epochRef.current++; - setList(null); - setSelected(new Set()); - setError(null); - setNotice(null); - } - setPending(null); + epoch.current++; + setLoaded(null); + setSelected(new Set()); + setError(null); + setNotice(null); + setPending(null); setRefreshing(false); - }, [sessionKey, refresh]); - - // Only binding is refused in browser mode (server.go handleTrustBind); - // listing, unbinding and logout work on any session, so the card stays - // fully functional and just the bind button is disabled. - const isClient = snap.client_type === "client"; - const busy = pending !== null; - const canAct = connected && snap.state === "online" && !busy; - - const run = async (action: () => Promise, ok: string, label: string) => { - const session = sessionRef.current; + setConfirmation(null); + if (snap.state === "online") void refresh(); + return () => { + epoch.current++; + }; + }, [sessionKey, snap.state, refresh]); + const devices = [...(list?.data ?? [])].sort( + (a, b) => Number(b.id === list?.selfId) - Number(a.id === list?.selfId), + ); + const selfTrusted = devices.some((device) => device.id === list?.selfId); + const eligible = devices.filter((device) => device.id !== list?.selfId); + const selectedIDs = eligible + .filter((device) => selected.has(device.id)) + .map((device) => device.id); + const canRefresh = + connected && snap.state === "online" && pending === null && !refreshing; + const canAct = canRefresh && list !== null; + const run = async ( + action: () => Promise, + success: string, + label: string, + ) => { + if (!canAct || mutation.current === sessionKey) return; + const session = sessionKey; + mutation.current = session; setPending(label); setError(null); setNotice(null); try { await action(); if (session !== sessionRef.current) return; - setNotice(ok); + setNotice(success); setSelected(new Set()); await refresh(); - } catch (err) { - if (session !== sessionRef.current) return; - setError(errorText(err, "操作失败", LIST_ERRORS)); + } catch (error) { + if (session === sessionRef.current) + setError(errorText(error, "设备操作失败", ERRORS)); } finally { - if (session === sessionRef.current) setPending(null); + if (session === sessionRef.current) { + mutation.current = null; + setPending(null); + } } }; - - const toggle = (id: string) => { - setSelected((prev) => { - const next = new Set(prev); + const toggle = (id: string) => + setSelected((previous) => { + const next = new Set(previous); if (next.has(id)) next.delete(id); else next.add(id); return next; }); + const renderDevice = (device: TrustDeviceEntry) => { + const Icon = /ios|android|phone/i.test(`${device.os} ${device.deviceType}`) + ? Smartphone + : Laptop; + return ( +
+ + + +
+
+ {deviceLabel(device)} + {device.id === list?.selfId && ( + 本机 + )} +
+

+ {[device.os, device.osVersion, device.deviceType] + .filter(Boolean) + .join(" · ") || "设备信息未提供"} +

+
+
+ ); }; - - // Current device first, then the controller's order. - const devices = (list?.data ?? []).slice().sort((a, b) => { - const self = list?.selfId; - return Number(b.id === self) - Number(a.id === self); - }); - const selfTrusted = list != null && devices.some((d) => d.id === list.selfId); - + const logoutButton = (device: TrustDeviceEntry) => ( + + ); + const confirmTitle = + confirmation?.kind === "unbind" + ? `取消 ${confirmation.ids.length} 台设备的授信?` + : confirmation?.device.id === list?.selfId + ? "注销本机?" + : "注销设备?"; + const confirmDescription = + confirmation?.kind === "unbind" + ? "这些设备下次登录可能需要短信验证。" + : confirmation?.device.id === list?.selfId + ? "本机会话将立即失效,代理连接会断开。重新登录后可以恢复连接。" + : `设备「${confirmation ? deviceLabel(confirmation.device) : ""}」的会话将立即失效。`; return ( -
-
-

授信终端

-
- - + + {pending === "bind" + ? "绑定中…" + : selfTrusted + ? "本机已授信" + : "绑定本机"} +
- {list && ( -

- 服务端授信策略:{list.trustDeviceConfig.enable ? "已启用" : "未启用"};当前设备 - {selfTrusted ? "已" : "未"}授信。 -

- )} - {!isClient && ( -

- 当前为 browser 模式:可以查看、取消授信和注销设备,但不能绑定当前设备。将登录模式设为 client 并重启 geektrust 后才能绑定。 -

+ {(error || notice || snap.client_type !== "client") && ( +
+ {error && } + {notice && ( +

+ {notice} +

+ )} + {snap.client_type !== "client" && ( +

+ browser 模式可以管理已有设备;绑定本机需要 client 登录模式。 +

+ )} +
)} - {error && } - {notice &&

{notice}

} - {list ? ( - devices.length === 0 ? ( -

暂无授信终端。绑定当前设备后,后续登录通常不再需要短信验证。

- ) : ( - <> -
- - - - - - - - - - - - - {devices.map((d) => ( - - - - - - - - - ))} - -
设备类型最近登录 IP位置
- toggle(d.id)} - disabled={d.id === list.selfId} - aria-label={`选择 ${deviceLabel(d)}`} - /> - - {deviceLabel(d)} - {d.id === list.selfId && 当前设备} - {d.onlineStatus && 在线} - {d.deviceType || "-"}{d.lastLoginIp || "-"}{d.lastLoginAddress || "-"} - -
-
-
- -
- - ) + {list && devices.length ? ( + <> +
+ + + + + 0 + ? true + : selectedIDs.length + ? "indeterminate" + : false + } + onCheckedChange={(value) => + setSelected( + value === true + ? new Set(eligible.map((device) => device.id)) + : new Set(), + ) + } + /> + + 设备 + 最近登录 IP + 位置 + 状态 + 操作 + + + + {devices.map((device) => ( + + + toggle(device.id)} + /> + + {renderDevice(device)} + + {device.lastLoginIp || "—"} + + + {device.lastLoginAddress || "—"} + + + {device.onlineStatus === undefined + ? "未知" + : device.onlineStatus + ? "在线" + : "离线"} + + + {logoutButton(device)} + + + ))} + +
+
+
    + {devices.map((device) => ( +
  • + toggle(device.id)} + /> +
    {renderDevice(device)}
    + {logoutButton(device)} +
  • + ))} +
+ ) : ( - !error &&

{snap.state === "online" ? "加载中…" : "会话在线后可查看"}

+

+ {refreshing + ? "正在加载设备…" + : snap.state !== "online" + ? "连接后可查看授信设备。" + : error + ? "设备列表暂不可用。" + : "暂无授信设备。"} +

)} -
+
+ + {list + ? `授信策略${list.trustDeviceConfig.enable ? "已启用" : "未启用"}` + : ""} + + +
+ { + if (!value) setConfirmation(null); + }} + title={confirmTitle} + description={confirmDescription} + action={confirmation?.kind === "unbind" ? "取消授信" : "注销"} + destructive + disabled={!canAct || confirmation?.session !== sessionKey} + onConfirm={() => { + if (!confirmation || confirmation.session !== sessionKey) return; + if (confirmation.kind === "unbind") + void run( + () => + post("/api/trust-devices/unbind", { ids: confirmation.ids }), + "已取消授信", + "unbind", + ); + else + void run( + () => + post("/api/trust-devices/logout", { + id: confirmation.device.id, + }), + "已注销设备", + `logout:${confirmation.device.id}`, + ); + }} + /> + ); } diff --git a/web/src/components/UserCard.tsx b/web/src/components/UserCard.tsx index 1dad61e..5cd49ee 100644 --- a/web/src/components/UserCard.tsx +++ b/web/src/components/UserCard.tsx @@ -1,88 +1,72 @@ -import { useEffect, useRef, useState } from "react"; +import { ChevronRight } from "lucide-react"; +import { Card } from "@/components/ui/card"; +import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogTrigger, + DialogContent, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; import type { Snapshot } from "../types"; - -function shortID(id: string): string { - return id.length > 20 ? `${id.slice(0, 8)}…${id.slice(-8)}` : id; -} - -// legacyCopy is the fallback for browsers without the async clipboard API. -function legacyCopy(text: string): boolean { - const ta = document.createElement("textarea"); - ta.value = text; - ta.style.position = "fixed"; - ta.style.opacity = "0"; - document.body.appendChild(ta); - ta.select(); - let ok = false; - try { - ok = document.execCommand("copy"); - } catch { - ok = false; - } - ta.remove(); - return ok; -} - +import { CopyButton } from "./CopyButton"; export function UserCard({ snap }: { snap: Snapshot }) { - const [copied, setCopied] = useState<"ok" | "fail" | null>(null); - const timer = useRef(undefined); - useEffect(() => () => window.clearTimeout(timer.current), []); - - const copy = async () => { - let ok: boolean; - try { - await navigator.clipboard.writeText(snap.device_id); - ok = true; - } catch { - ok = legacyCopy(snap.device_id); - } - setCopied(ok ? "ok" : "fail"); - window.clearTimeout(timer.current); - timer.current = window.setTimeout(() => setCopied(null), 1600); - }; - + const name = snap.user?.display_name || snap.user?.username || "未登录"; return ( -
-

用户

- {snap.user ? ( -
-
账号
-
{snap.user.username}
-
姓名
-
{snap.user.display_name}
-
客户端 IP
-
{snap.user.client_ip}
-
- ) : ( -

未登录

- )} -
-
device_id
-
- {shortID(snap.device_id)} - -
-
登录模式
-
{snap.client_type}
-
SOCKS5
-
{snap.proxy.socks5 ?? "已禁用"}
-
HTTP
-
{snap.proxy.http ?? "已禁用"}
- {snap.gateways && snap.gateways.length > 0 && ( - <> + +
+
+

+ {name} +

+

+ {snap.controller_host || "控制器未配置"} +

+
+
+
+
账号
+
{snap.user?.username || "—"}
+
客户端 IP
+
{snap.user?.client_ip || "—"}
+
+ + + + + + + 连接与设备详情 + +
+
控制器
+
{snap.controller_host || "—"}
+
设备 ID
+
+ {snap.device_id} + +
+
登录模式
+
{snap.client_type}
+
状态更新时间
+
+ {Number.isNaN(Date.parse(snap.since)) + ? snap.since + : new Date(snap.since).toLocaleString("zh-CN")} +
网关
-
{snap.gateways.join(", ")}
- - )} - {snap.dns && snap.dns.length > 0 && ( - <> +
{snap.gateways?.join(", ") || "—"}
隧道 DNS
-
{snap.dns.join(", ")}
- - )} -
-
+
{snap.dns?.join(", ") || "—"}
+ + + + ); } diff --git a/web/src/components/interactions.test.tsx b/web/src/components/interactions.test.tsx new file mode 100644 index 0000000..58b5ac9 --- /dev/null +++ b/web/src/components/interactions.test.tsx @@ -0,0 +1,222 @@ +import { + act, + fireEvent, + render, + screen, + waitFor, +} from "@testing-library/react"; +import { beforeEach, expect, it, vi } from "vitest"; +import { SmsDialog } from "./SmsDialog"; +import { TrustDevices } from "./TrustDevices"; +import { EventsList } from "./EventsList"; +import type { Snapshot, TrustDeviceList } from "../types"; +const api = vi.hoisted(() => ({ + fetchTrustDevices: vi.fn(), + post: vi.fn(), + postJSON: vi.fn(), +})); +vi.mock("../api", async (original) => ({ + ...(await original()), + ...api, +})); +const snapshot: Snapshot = { + generation: 1, + state: "online", + since: "2026-10-06T00:00:00Z", + last_error: null, + user: { username: "user", display_name: "用户", client_ip: "192.0.2.1" }, + device_id: "fixture", + client_type: "client", + controller_host: "vpn.example.edu.cn", + gateways: [], + dns: [], + proxy: { socks5: null, http: null }, + sms_pending: false, + sms_gen: 0, + events_dropped: 0, + events: [], +}; +const devices: TrustDeviceList = { + data: [ + { id: "self", deviceName: "本机" }, + { id: "other", deviceName: "其他设备" }, + ], + selfId: "self", + currentTrustStatus: 1, + trustDeviceConfig: { enable: true }, +}; +function deferred() { + let resolve!: (value: T) => void; + let reject!: (error: Error) => void; + const promise = new Promise((yes, no) => { + resolve = yes; + reject = no; + }); + return { promise, resolve, reject }; +} +beforeEach(() => { + api.fetchTrustDevices.mockReset(); + api.post.mockReset(); + api.postJSON.mockReset(); +}); +it("discards a device response after the session changes", async () => { + const old = deferred(); + const next = deferred(); + api.fetchTrustDevices + .mockReturnValueOnce(old.promise) + .mockReturnValueOnce(next.promise); + const { rerender } = render(); + rerender(); + await act(async () => old.resolve(devices)); + expect(screen.queryByText("其他设备")).toBeNull(); + await act(async () => + next.resolve({ ...devices, data: [{ id: "new", deviceName: "新设备" }] }), + ); + expect(screen.getAllByText("新设备").length).toBeGreaterThan(0); +}); +it("closes an old confirmation and blocks its action when the session changes", async () => { + api.fetchTrustDevices.mockResolvedValue(devices); + const { rerender } = render(); + await waitFor(() => + expect( + screen.getAllByRole("button", { name: "注销 其他设备" }).length, + ).toBeGreaterThan(0), + ); + fireEvent.click(screen.getAllByRole("button", { name: "注销 其他设备" })[0]); + expect(screen.getByRole("alertdialog")).toBeTruthy(); + rerender(); + expect(screen.queryByRole("alertdialog")).toBeNull(); + expect(api.post).not.toHaveBeenCalled(); +}); +it("requires confirmation for self logout and posts the correct device", async () => { + api.fetchTrustDevices.mockResolvedValue(devices); + api.post.mockResolvedValue(undefined); + render(); + await waitFor(() => + expect( + screen.getAllByRole("button", { name: "注销 本机" }).length, + ).toBeGreaterThan(0), + ); + fireEvent.click(screen.getAllByRole("button", { name: "注销 本机" })[0]); + expect(api.post).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole("button", { name: "注销" })); + await waitFor(() => + expect(api.post).toHaveBeenCalledWith("/api/trust-devices/logout", { + id: "self", + }), + ); +}); +it("keeps mutations disabled after the panel disconnects", async () => { + api.fetchTrustDevices.mockResolvedValue(devices); + const { rerender } = render(); + await waitFor(() => + expect( + screen.getAllByRole("button", { name: "注销 其他设备" }).length, + ).toBeGreaterThan(0), + ); + rerender(); + expect( + ( + screen.getAllByRole("button", { + name: "注销 其他设备", + })[0] as HTMLButtonElement + ).disabled, + ).toBe(true); +}); +it("shows 10 recent events and all retained events in the dialog", () => { + const events = Array.from({ length: 40 }, (_, i) => ({ + ts: `2026-10-06T00:${String(i).padStart(2, "0")}:00Z`, + kind: "login_start", + message: `事件${i}`, + })); + render(); + expect(document.querySelector(".activity-list")?.children.length).toBe(10); + fireEvent.click(screen.getByRole("button", { name: "查看全部" })); + expect( + document.querySelector('[role="dialog"] .activity-list')?.children.length, + ).toBe(40); +}); +it("prevents duplicate SMS resends while the request is pending", async () => { + vi.useFakeTimers(); + const response = deferred<{ restarting?: boolean }>(); + api.postJSON.mockReturnValue(response.promise); + render( + {}} + />, + ); + act(() => vi.advanceTimersByTime(60000)); + const button = screen.getByRole("button", { name: "重新发送" }); + fireEvent.click(button); + fireEvent.click(button); + expect(api.postJSON).toHaveBeenCalledTimes(1); + await act(async () => response.resolve({})); + vi.useRealTimers(); +}); +it("keeps an old SMS result out of a new verification generation", async () => { + const old = deferred(); + api.post.mockReturnValue(old.promise); + const { rerender } = render( + {}} + />, + ); + fireEvent.change(screen.getByLabelText("6 位短信验证码"), { + target: { value: "123456" }, + }); + fireEvent.click(screen.getByRole("button", { name: "验证并连接" })); + expect(api.post).toHaveBeenCalledWith("/api/sms", { code: "123456", gen: 7 }); + rerender( + {}} + />, + ); + await act(async () => old.reject(new Error("old failure"))); + expect(screen.queryByRole("alert")).toBeNull(); + expect( + (screen.getByLabelText("6 位短信验证码") as HTMLInputElement).value, + ).toBe(""); +}); + +it("allows browser-mode device management while refusing a new local binding", async () => { + api.fetchTrustDevices.mockResolvedValue({ + ...devices, + data: [{ id: "other", deviceName: "其他设备" }], + }); + render( + , + ); + await waitFor(() => + expect( + screen.getAllByRole("button", { name: "注销 其他设备" }).length, + ).toBeGreaterThan(0), + ); + expect( + (screen.getByRole("button", { name: "绑定本机" }) as HTMLButtonElement) + .disabled, + ).toBe(true); + expect( + ( + screen.getAllByRole("button", { + name: "注销 其他设备", + })[0] as HTMLButtonElement + ).disabled, + ).toBe(false); +}); + +it("explains a background authentication challenge without showing an internal error", () => { + render(); + expect(screen.getByText("登录需要验证,请重新登录")).toBeTruthy(); + expect(screen.queryByText("authentication interaction required")).toBeNull(); +}); diff --git a/web/src/components/ui/alert-dialog.tsx b/web/src/components/ui/alert-dialog.tsx new file mode 100644 index 0000000..05560c6 --- /dev/null +++ b/web/src/components/ui/alert-dialog.tsx @@ -0,0 +1,199 @@ +"use client"; + +import * as React from "react"; +import { cn } from "cn"; +import { AlertDialog as AlertDialogPrimitive } from "radix-ui"; + +import { Button } from "@/components/ui/button"; + +function AlertDialog({ + ...props +}: React.ComponentProps) { + return ; +} + +function AlertDialogTrigger({ + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function AlertDialogPortal({ + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function AlertDialogOverlay({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function AlertDialogContent({ + className, + size = "default", + ...props +}: React.ComponentProps & { + size?: "default" | "sm"; +}) { + return ( + + + + + ); +} + +function AlertDialogHeader({ + className, + ...props +}: React.ComponentProps<"div">) { + return ( +
+ ); +} + +function AlertDialogFooter({ + className, + ...props +}: React.ComponentProps<"div">) { + return ( +
+ ); +} + +function AlertDialogMedia({ + className, + ...props +}: React.ComponentProps<"div">) { + return ( +
+ ); +} + +function AlertDialogTitle({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function AlertDialogDescription({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function AlertDialogAction({ + className, + variant = "default", + size = "default", + ...props +}: React.ComponentProps & + Pick, "variant" | "size">) { + return ( + + ); +} + +function AlertDialogCancel({ + className, + variant = "outline", + size = "default", + ...props +}: React.ComponentProps & + Pick, "variant" | "size">) { + return ( + + ); +} + +export { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogMedia, + AlertDialogOverlay, + AlertDialogPortal, + AlertDialogTitle, + AlertDialogTrigger, +}; diff --git a/web/src/components/ui/button.tsx b/web/src/components/ui/button.tsx new file mode 100644 index 0000000..f336ace --- /dev/null +++ b/web/src/components/ui/button.tsx @@ -0,0 +1,66 @@ +import * as React from "react"; +import { cva, type VariantProps } from "class-variance-authority"; +import { cn } from "cn"; +import { Slot } from "radix-ui"; + +const buttonVariants = cva( + "group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", + { + variants: { + variant: { + default: "bg-primary text-primary-foreground hover:bg-primary/80", + outline: + "border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50", + secondary: + "bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground", + ghost: + "hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50", + destructive: + "bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40", + link: "text-primary underline-offset-4 hover:underline", + }, + size: { + default: + "h-11 gap-2 px-3 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2", + xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3", + sm: "h-8 gap-2 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5", + lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2", + icon: "relative size-9", + "icon-xs": + "size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3", + "icon-sm": + "size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg", + "icon-lg": "size-9", + }, + }, + defaultVariants: { + variant: "default", + size: "default", + }, + }, +); + +function Button({ + className, + variant = "default", + size = "default", + asChild = false, + ...props +}: React.ComponentProps<"button"> & + VariantProps & { + asChild?: boolean; + }) { + const Comp = asChild ? Slot.Root : "button"; + + return ( + + ); +} + +export { Button, buttonVariants }; diff --git a/web/src/components/ui/card.tsx b/web/src/components/ui/card.tsx new file mode 100644 index 0000000..04e8c3d --- /dev/null +++ b/web/src/components/ui/card.tsx @@ -0,0 +1,102 @@ +import * as React from "react"; +import { cn } from "cn"; + +function Card({ + className, + size = "default", + ...props +}: React.ComponentProps<"div"> & { size?: "default" | "sm" }) { + return ( +
img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(3)] data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl", + className, + )} + {...props} + /> + ); +} + +function CardHeader({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ); +} + +function CardTitle({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ); +} + +function CardDescription({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ); +} + +function CardAction({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ); +} + +function CardContent({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ); +} + +function CardFooter({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ); +} + +export { + Card, + CardHeader, + CardFooter, + CardTitle, + CardAction, + CardDescription, + CardContent, +}; diff --git a/web/src/components/ui/checkbox.tsx b/web/src/components/ui/checkbox.tsx new file mode 100644 index 0000000..a485f1c --- /dev/null +++ b/web/src/components/ui/checkbox.tsx @@ -0,0 +1,31 @@ +"use client"; + +import * as React from "react"; +import { cn } from "cn"; +import { Checkbox as CheckboxPrimitive } from "radix-ui"; +import { CheckIcon } from "lucide-react"; + +function Checkbox({ + className, + ...props +}: React.ComponentProps) { + return ( + + + + + + ); +} + +export { Checkbox }; diff --git a/web/src/components/ui/dialog.tsx b/web/src/components/ui/dialog.tsx new file mode 100644 index 0000000..a9f8da9 --- /dev/null +++ b/web/src/components/ui/dialog.tsx @@ -0,0 +1,165 @@ +import * as React from "react"; +import { cn } from "cn"; +import { Dialog as DialogPrimitive } from "radix-ui"; + +import { Button } from "@/components/ui/button"; +import { XIcon } from "lucide-react"; + +function Dialog({ + ...props +}: React.ComponentProps) { + return ; +} + +function DialogTrigger({ + ...props +}: React.ComponentProps) { + return ; +} + +function DialogPortal({ + ...props +}: React.ComponentProps) { + return ; +} + +function DialogClose({ + ...props +}: React.ComponentProps) { + return ; +} + +function DialogOverlay({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function DialogContent({ + className, + children, + showCloseButton = true, + ...props +}: React.ComponentProps & { + showCloseButton?: boolean; +}) { + return ( + + + + {children} + {showCloseButton && ( + + + + )} + + + ); +} + +function DialogHeader({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ); +} + +function DialogFooter({ + className, + showCloseButton = false, + children, + ...props +}: React.ComponentProps<"div"> & { + showCloseButton?: boolean; +}) { + return ( +
+ {children} + {showCloseButton && ( + + + + )} +
+ ); +} + +function DialogTitle({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function DialogDescription({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} + +export { + Dialog, + DialogClose, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogOverlay, + DialogPortal, + DialogTitle, + DialogTrigger, +}; diff --git a/web/src/components/ui/dropdown-menu.tsx b/web/src/components/ui/dropdown-menu.tsx new file mode 100644 index 0000000..3cf7f92 --- /dev/null +++ b/web/src/components/ui/dropdown-menu.tsx @@ -0,0 +1,270 @@ +import * as React from "react"; +import { cn } from "cn"; +import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui"; +import { CheckIcon, ChevronRightIcon } from "lucide-react"; + +function DropdownMenu({ + ...props +}: React.ComponentProps) { + return ; +} + +function DropdownMenuPortal({ + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function DropdownMenuTrigger({ + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function DropdownMenuContent({ + className, + align = "start", + sideOffset = 4, + ...props +}: React.ComponentProps) { + return ( + + + + ); +} + +function DropdownMenuGroup({ + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function DropdownMenuItem({ + className, + inset, + variant = "default", + ...props +}: React.ComponentProps & { + inset?: boolean; + variant?: "default" | "destructive"; +}) { + return ( + + ); +} + +function DropdownMenuCheckboxItem({ + className, + children, + checked, + inset, + ...props +}: React.ComponentProps & { + inset?: boolean; +}) { + return ( + + + + + + + {children} + + ); +} + +function DropdownMenuRadioGroup({ + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function DropdownMenuRadioItem({ + className, + children, + inset, + ...props +}: React.ComponentProps & { + inset?: boolean; +}) { + return ( + + + + + + + {children} + + ); +} + +function DropdownMenuLabel({ + className, + inset, + ...props +}: React.ComponentProps & { + inset?: boolean; +}) { + return ( + + ); +} + +function DropdownMenuSeparator({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function DropdownMenuShortcut({ + className, + ...props +}: React.ComponentProps<"span">) { + return ( + + ); +} + +function DropdownMenuSub({ + ...props +}: React.ComponentProps) { + return ; +} + +function DropdownMenuSubTrigger({ + className, + inset, + children, + ...props +}: React.ComponentProps & { + inset?: boolean; +}) { + return ( + + {children} + + + ); +} + +function DropdownMenuSubContent({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} + +export { + DropdownMenu, + DropdownMenuPortal, + DropdownMenuTrigger, + DropdownMenuContent, + DropdownMenuGroup, + DropdownMenuLabel, + DropdownMenuItem, + DropdownMenuCheckboxItem, + DropdownMenuRadioGroup, + DropdownMenuRadioItem, + DropdownMenuSeparator, + DropdownMenuShortcut, + DropdownMenuSub, + DropdownMenuSubTrigger, + DropdownMenuSubContent, +}; diff --git a/web/src/components/ui/input-otp.tsx b/web/src/components/ui/input-otp.tsx new file mode 100644 index 0000000..8a7eccc --- /dev/null +++ b/web/src/components/ui/input-otp.tsx @@ -0,0 +1,85 @@ +"use client"; + +import * as React from "react"; +import { cn } from "cn"; +import { OTPInput, OTPInputContext } from "input-otp"; +import { MinusIcon } from "lucide-react"; + +function InputOTP({ + className, + containerClassName, + ...props +}: React.ComponentProps & { + containerClassName?: string; +}) { + return ( + + ); +} + +function InputOTPGroup({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ); +} + +function InputOTPSlot({ + index, + className, + ...props +}: React.ComponentProps<"div"> & { + index: number; +}) { + const inputOTPContext = React.useContext(OTPInputContext); + const { char, hasFakeCaret, isActive } = inputOTPContext?.slots[index] ?? {}; + + return ( +
+ {char} + {hasFakeCaret && ( +
+
+
+ )} +
+ ); +} + +function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) { + return ( +
+ +
+ ); +} + +export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator }; diff --git a/web/src/components/ui/table.tsx b/web/src/components/ui/table.tsx new file mode 100644 index 0000000..e25e7ec --- /dev/null +++ b/web/src/components/ui/table.tsx @@ -0,0 +1,113 @@ +import * as React from "react"; +import { cn } from "cn"; + +function Table({ className, ...props }: React.ComponentProps<"table">) { + return ( +
+ + + ); +} + +function TableHeader({ className, ...props }: React.ComponentProps<"thead">) { + return ( + + ); +} + +function TableBody({ className, ...props }: React.ComponentProps<"tbody">) { + return ( + + ); +} + +function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) { + return ( + tr]:last:border-b-0", + className, + )} + {...props} + /> + ); +} + +function TableRow({ className, ...props }: React.ComponentProps<"tr">) { + return ( + + ); +} + +function TableHead({ className, ...props }: React.ComponentProps<"th">) { + return ( +
+ ); +} + +function TableCell({ className, ...props }: React.ComponentProps<"td">) { + return ( + + ); +} + +function TableCaption({ + className, + ...props +}: React.ComponentProps<"caption">) { + return ( +
+ ); +} + +export { + Table, + TableHeader, + TableBody, + TableFooter, + TableHead, + TableRow, + TableCell, + TableCaption, +}; diff --git a/web/src/lib/utils.ts b/web/src/lib/utils.ts new file mode 100644 index 0000000..f815ded --- /dev/null +++ b/web/src/lib/utils.ts @@ -0,0 +1 @@ +export { cn } from "cn" diff --git a/web/src/main.tsx b/web/src/main.tsx index 693ac2e..a501999 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -1,10 +1,13 @@ import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import App from "./App"; +import { ThemeProvider } from "./components/ThemeProvider"; import "./styles.css"; createRoot(document.getElementById("root")!).render( - + + + , ); diff --git a/web/src/shadcn.css b/web/src/shadcn.css new file mode 100644 index 0000000..2463706 --- /dev/null +++ b/web/src/shadcn.css @@ -0,0 +1,6 @@ +/* State variants used by the generated Radix components. */ +@custom-variant data-open (&[data-state="open"]); +@custom-variant data-closed (&[data-state="closed"]); +@custom-variant data-checked (&[data-state="checked"]); +@custom-variant data-unchecked (&[data-state="unchecked"]); +@custom-variant data-disabled (&[data-disabled]); diff --git a/web/src/styles.css b/web/src/styles.css index ff8a1cd..2bf33ec 100644 --- a/web/src/styles.css +++ b/web/src/styles.css @@ -1,268 +1,280 @@ +@import "tailwindcss"; +@import "tw-animate-css"; +@import "./shadcn.css"; +@import "@fontsource-variable/geist"; +@import "@fontsource-variable/geist-mono"; +@import "@fontsource-variable/noto-sans-sc"; + +@custom-variant dark (&:is(.dark *)); +@theme inline { + --font-sans: "Geist Variable", "Noto Sans SC Variable", sans-serif; + --font-mono: "Geist Mono Variable", monospace; + --color-background: var(--background); + --color-foreground: var(--foreground); + --color-card: var(--card); + --color-card-foreground: var(--foreground); + --color-popover: var(--card); + --color-popover-foreground: var(--foreground); + --color-primary: var(--primary); + --color-primary-foreground: var(--primary-foreground); + --color-secondary: var(--muted); + --color-secondary-foreground: var(--foreground); + --color-muted: var(--muted); + --color-muted-foreground: var(--muted-foreground); + --color-accent: var(--muted); + --color-accent-foreground: var(--foreground); + --color-destructive: var(--destructive); + --color-border: var(--border); + --color-input: var(--border); + --color-ring: var(--ring); + --color-success: var(--success); + --color-warning: var(--warning); + --radius-sm: 0.375rem; + --radius-md: 0.5rem; + --radius-lg: 0.75rem; + --radius-xl: 1rem; +} :root { - color-scheme: light dark; - --bg: #f4f6f9; - --card: #ffffff; - --text: #1c2430; - --muted: #67748a; - --border: #e2e6ee; - --accent: #2563eb; - --accent-press: #1d4ed8; - --ok: #16a34a; - --warn: #d97706; - --danger: #dc2626; - --idle: #8494ab; - --shadow: 0 1px 2px rgba(15, 23, 42, 0.05); + --background: #fafafa; + --foreground: #171717; + --card: #fff; + --muted: #f5f5f5; + --muted-foreground: #737373; + --border: #e5e5e5; + --secondary: var(--muted); + --primary: #171717; + --primary-foreground: #fff; + --ring: #a3a3a3; + --success: #047857; + --success-bg: #ecfdf5; + --warning: #b45309; + --warning-bg: #fffbeb; + --destructive: #b91c1c; + --destructive-bg: #fef2f2; + --radius: 0.75rem; } - -@media (prefers-color-scheme: dark) { - :root { - --bg: #0f141c; - --card: #171e2a; - --text: #e6eaf2; - --muted: #8b96ab; - --border: #2a3346; - --accent: #3b82f6; - --accent-press: #2563eb; - --idle: #64748b; - --shadow: 0 1px 2px rgba(0, 0, 0, 0.4); +.dark { + --background: #090909; + --foreground: #fafafa; + --card: #171717; + --muted: #262626; + --muted-foreground: #a3a3a3; + --border: #303030; + --primary: #fafafa; + --primary-foreground: #171717; + --ring: #737373; + --success: #34d399; + --success-bg: #052e2b; + --warning: #fbbf24; + --warning-bg: #422006; + --destructive: #f87171; + --destructive-bg: #450a0a; +} +@layer base { + * { + @apply border-border outline-ring/50; + } + body { + @apply bg-background text-foreground font-sans antialiased; + margin: 0; + font-size: 14px; + } + button:not(:disabled), + summary { + cursor: pointer; + } + code, + pre { + @apply font-mono; } } - -* { box-sizing: border-box; } - -body { - margin: 0; - font-family: -apple-system, "PingFang SC", "Microsoft YaHei", system-ui, sans-serif; - background: var(--bg); - color: var(--text); - font-size: 15px; - line-height: 1.55; +.app-bar { + @apply border-b bg-card; } - -code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.92em; } - -.page { max-width: 960px; margin: 0 auto; padding: 24px 16px 64px; } - -.top { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; } -.top h1 { font-size: 20px; margin: 0; } - -.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; } -@media (max-width: 720px) { .grid { grid-template-columns: 1fr; } } - -.card { - background: var(--card); - border: 1px solid var(--border); - border-radius: 12px; - padding: 16px 18px; - margin-bottom: 16px; - box-shadow: var(--shadow); -} -.card h2 { font-size: 15px; margin: 0 0 10px; } -.card-head { display: flex; justify-content: space-between; align-items: center; gap: 8px; flex-wrap: wrap; } -.card-head h2 { margin: 0; } - -.boot { margin-top: 18vh; text-align: center; padding: 32px 24px; } -.boot h1 { font-size: 20px; margin: 0 0 12px; } - -.banner { - display: flex; - align-items: center; - gap: 8px; - border-radius: 10px; - padding: 10px 14px; - margin-bottom: 16px; - font-size: 14px; - background: color-mix(in srgb, var(--danger) 10%, var(--card)); - border: 1px solid color-mix(in srgb, var(--danger) 40%, transparent); -} -.banner::before { - content: ""; - flex: none; - width: 8px; - height: 8px; - border-radius: 50%; - background: var(--danger); - animation: blink 1.2s ease-in-out infinite; +.app-bar-inner { + @apply mx-auto flex h-[72px] max-w-[1208px] items-center gap-3 px-6; } - -/* 状态灯 */ -.pill { - display: inline-flex; - align-items: center; - gap: 7px; - padding: 3px 12px; - border-radius: 999px; - font-size: 13px; - font-weight: 600; - color: #fff; - white-space: nowrap; -} -.pill::before { content: ""; width: 6px; height: 6px; border-radius: 50%; background: #fff; opacity: 0.9; } -.pill.ok { background: var(--ok); } -.pill.ok::before { animation: blink 2.4s ease-in-out infinite; } -.pill.warn { background: var(--warn); } -.pill.idle { background: var(--idle); } -/* 连接断开:快照已不再刷新,状态灯不能继续冒充实时。 */ -.pill.stale { background: var(--idle); } -.pill.stale::before { animation: none; opacity: 0.5; } - -@keyframes blink { 50% { opacity: 0.25; } } - -.status-row { display: flex; align-items: center; gap: 12px; margin-bottom: 6px; flex-wrap: wrap; } - -.muted { color: var(--muted); } -.small { font-size: 13px; } -.mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 13px; } -.error-text { color: var(--danger); overflow-wrap: anywhere; } -.ok-text { color: var(--ok); } - -/* 错误摘要 + 可展开的原始错误链 */ -.error-block { margin: 0 0 6px; } -.error-block .error-text { margin: 0; } -.detail-toggle { font-size: 12px; white-space: nowrap; } -.error-detail { - margin: 6px 0 0; - padding: 8px 10px; - border: 1px solid color-mix(in srgb, var(--danger) 24%, transparent); - border-radius: 6px; - background: color-mix(in srgb, var(--danger) 7%, transparent); - color: var(--muted); - font-size: 12px; - white-space: pre-wrap; - overflow-wrap: anywhere; -} -.right { text-align: right; } - -.kv { display: grid; grid-template-columns: 96px 1fr; gap: 4px 12px; margin: 0 0 6px; } -.kv dt { color: var(--muted); } -.kv dd { margin: 0; overflow-wrap: anywhere; } - -.actions { display: flex; gap: 8px; align-items: center; margin-top: 10px; flex-wrap: wrap; } - -button { - background: var(--accent); - color: #fff; - border: none; - border-radius: 8px; - padding: 7px 14px; - font-size: 14px; - font-family: inherit; - cursor: pointer; - transition: background-color 0.15s, opacity 0.15s; -} -button:hover:not(:disabled) { background: var(--accent-press); } -button:disabled { opacity: 0.45; cursor: not-allowed; } -button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } -button.secondary { background: transparent; color: var(--accent); border: 1px solid var(--accent); } -button.secondary:hover:not(:disabled) { background: color-mix(in srgb, var(--accent) 10%, transparent); } -button.link { background: none; color: var(--accent); padding: 0 4px; font-size: 13px; } -button.link:hover:not(:disabled) { background: none; text-decoration: underline; } -button.link.danger { color: var(--danger); } - -input[type="checkbox"] { width: 15px; height: 15px; accent-color: var(--accent); } - -/* 授信终端表格 */ -.table-wrap { overflow-x: auto; margin-top: 8px; } -table.devices { width: 100%; border-collapse: collapse; } -table.devices th, table.devices td { - text-align: left; - padding: 7px 8px; - border-bottom: 1px solid var(--border); - font-size: 14px; - white-space: nowrap; -} -table.devices td:nth-child(2) { white-space: normal; min-width: 12em; } -table.devices th { color: var(--muted); font-weight: 500; } -table.devices tbody tr:hover { background: color-mix(in srgb, var(--accent) 4%, transparent); } -table.devices tr:last-child td { border-bottom: none; } - -.tag { - display: inline-block; - margin-left: 8px; - padding: 1px 8px; - border-radius: 999px; - font-size: 12px; - background: var(--border); - color: var(--muted); - white-space: nowrap; -} -.tag.ok { background: color-mix(in srgb, var(--ok) 16%, transparent); color: var(--ok); } -.tag.accent { background: color-mix(in srgb, var(--accent) 14%, transparent); color: var(--accent); } - -/* 事件列表 */ -.events { list-style: none; margin: 0; padding: 0; } -.events li { - display: flex; - gap: 10px; - align-items: baseline; - padding: 6px 0; - border-bottom: 1px solid var(--border); -} -.events li:last-child { border-bottom: none; } -.events .tag { margin-left: 0; flex: none; } -.ev-time { flex: none; } -.ev-msg { overflow-wrap: anywhere; } - -.tag.kind-login_success, .tag.kind-restore_success { - background: color-mix(in srgb, var(--ok) 16%, transparent); - color: var(--ok); +.brand { + @apply flex items-center gap-3 text-xl font-semibold; } -.tag.kind-login_failed { - background: color-mix(in srgb, var(--danger) 14%, transparent); - color: var(--danger); +.brand-mark { + @apply flex size-[30px] items-center justify-center rounded-lg bg-primary text-primary-foreground; } -.tag.kind-invalidated { - background: color-mix(in srgb, var(--warn) 16%, transparent); - color: var(--warn); +.workspace { + @apply flex gap-3 text-sm text-muted-foreground; } -.tag.kind-login_start { - background: color-mix(in srgb, var(--accent) 12%, transparent); - color: var(--accent); +.service-badge { + @apply flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs; } - -/* 短信弹窗 */ -.dialog-backdrop { - position: fixed; - inset: 0; - background: rgba(8, 12, 20, 0.5); - backdrop-filter: blur(2px); - display: flex; - align-items: center; - justify-content: center; - z-index: 10; - padding: 16px; -} -.dialog { - background: var(--card); - border: 1px solid var(--border); - border-radius: 14px; - padding: 24px; - width: min(400px, 100%); - box-shadow: 0 18px 50px rgba(0, 0, 0, 0.35); - animation: rise 0.18s ease-out; +.service-online { + color: var(--success); + background: var(--success-bg); } -.dialog h2 { margin-top: 0; } - -@keyframes rise { - from { opacity: 0; transform: translateY(8px); } - to { opacity: 1; transform: none; } +.service-offline { + color: var(--muted-foreground); + background: var(--muted); +} +.page { + @apply mx-auto flex max-w-[1208px] flex-col gap-6 px-6 pb-8 pt-8; +} +.page-heading { + @apply flex items-center justify-between gap-4; +} +.page-heading h1 { + @apply text-[32px] font-medium leading-[44px]; +} +.page-heading p { + @apply mt-1 text-sm leading-[22px] text-muted-foreground; +} +.overview-grid { + @apply grid grid-cols-[minmax(0,1fr)_320px] gap-5; +} +.status-card { + @apply min-h-[205px] gap-3 rounded-xl p-6 shadow-none; +} +.status-title { + @apply text-[32px] font-medium leading-[44px]; +} +.account-card { + @apply min-h-[205px] gap-3 rounded-xl p-6 shadow-none; +} +.account-fields { + @apply grid min-w-0 grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-3 text-xs; +} +.account-fields dt { + @apply text-muted-foreground; +} +.account-fields dd { + @apply truncate text-right font-mono; +} +.detail-fields { + @apply grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-4 text-sm; +} +.detail-fields dt { + @apply text-muted-foreground; +} +.detail-fields dd { + @apply min-w-0 break-words; +} +.proxy-grid { + @apply grid grid-cols-2 gap-5; +} +.proxy-card { + @apply gap-2 rounded-xl p-5 shadow-none; +} +.devices-card { + @apply gap-0 overflow-hidden rounded-xl py-0 shadow-none; +} +.devices-heading { + @apply flex min-h-[72px] items-center justify-between gap-3 px-6 py-4; +} +.devices-card thead { + @apply bg-background; +} +.devices-card th { + @apply h-11 text-xs font-normal text-muted-foreground; +} +.devices-card td { + @apply h-[70px]; +} +.device-icon { + @apply flex size-9 shrink-0 items-center justify-center rounded-lg bg-muted; +} +.devices-footer { + @apply flex min-h-[64px] items-center justify-between gap-3 border-t px-4 py-3; +} +.mobile-device { + @apply flex items-center gap-3 border-t px-5 py-4; +} +.activity-card { + @apply gap-3 rounded-xl p-6 shadow-none; +} +.activity-list { + @apply flex flex-col gap-2; +} +.activity-list li { + @apply flex items-start gap-3 text-sm leading-[22px]; +} +.activity-list time { + @apply w-[58px] shrink-0 pt-0.5 font-mono text-xs text-muted-foreground; +} +.activity-list li > span:first-of-type { + @apply mt-2; +} +.activity-dialog { + @apply flex max-h-[min(760px,calc(100dvh-40px))] flex-col sm:max-w-[720px]; +} +.dialog-icon { + @apply flex size-10 items-center justify-center rounded-lg bg-muted; +} +.error-block { + @apply rounded-lg p-3 text-sm leading-6; + color: var(--destructive); + background: var(--destructive-bg); +} +.connection-warning { + @apply rounded-lg border p-3 text-sm; + color: var(--warning); + background: var(--warning-bg); +} +@media (max-width: 767px) { + .app-bar-inner { + height: 64px; + padding: 0 20px; + } + .workspace { + display: none; + } + .brand { + gap: 8px; + font-size: 18px; + } + .page { + padding: 24px 20px; + gap: 20px; + } + .overview-grid, + .proxy-grid { + grid-template-columns: minmax(0, 1fr); + gap: 20px; + } + .status-card { + min-height: 205px; + padding: 24px; + } + .account-card { + min-height: auto; + } + .devices-heading { + padding: 16px 20px; + } + .activity-card { + padding: 20px; + } + .detail-fields { + grid-template-columns: minmax(0, 1fr); + gap: 6px; + } + .detail-fields dd { + margin-bottom: 10px; + } +} +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + animation-duration: 0.01ms !important; + transition-duration: 0.01ms !important; + } } -.code-input { - width: 100%; - font-size: 24px; - letter-spacing: 8px; - text-align: center; - padding: 10px; +[data-slot="card"] { border: 1px solid var(--border); - border-radius: 8px; - background: var(--bg); - color: var(--text); - margin: 10px 0; + box-shadow: none; } -.code-input::placeholder { letter-spacing: normal; font-size: 15px; } -.code-input:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; border-color: transparent; } -@media (prefers-reduced-motion: reduce) { - * { animation: none !important; transition: none !important; } +[data-slot="dialog-content"]:not(.activity-dialog), +[data-slot="alert-dialog-content"] { + max-height: calc(100dvh - 2rem); + overflow-y: auto; } diff --git a/web/src/test/setup.ts b/web/src/test/setup.ts new file mode 100644 index 0000000..3e3cddc --- /dev/null +++ b/web/src/test/setup.ts @@ -0,0 +1,10 @@ +import { afterEach, vi } from "vitest"; +import { cleanup } from "@testing-library/react"; +afterEach(() => { cleanup(); vi.restoreAllMocks(); }); +class ResizeObserverStub { observe() {} unobserve() {} disconnect() {} } +vi.stubGlobal("ResizeObserver", ResizeObserverStub); +Element.prototype.scrollIntoView = () => {}; +Element.prototype.hasPointerCapture = () => false; +Element.prototype.setPointerCapture = () => {}; +Element.prototype.releasePointerCapture = () => {}; +document.elementFromPoint = () => null; diff --git a/web/src/types.ts b/web/src/types.ts index 9e1160f..948207b 100644 --- a/web/src/types.ts +++ b/web/src/types.ts @@ -26,6 +26,7 @@ export interface Snapshot { user: UserInfo | null; device_id: string; client_type: string; + controller_host: string; gateways: string[] | null; dns: string[] | null; proxy: ProxyInfo; diff --git a/web/tsconfig.json b/web/tsconfig.json index 3c5bd47..43dac97 100644 --- a/web/tsconfig.json +++ b/web/tsconfig.json @@ -14,7 +14,11 @@ "resolveJsonModule": true, "isolatedModules": true, "noUnusedLocals": true, - "noUnusedParameters": true + "noUnusedParameters": true, + "baseUrl": ".", + "paths": { + "@/*": ["./src/*"] + } }, "include": ["src", "vite.config.ts"] } diff --git a/web/vite.config.ts b/web/vite.config.ts index 2619ec7..a2a606d 100644 --- a/web/vite.config.ts +++ b/web/vite.config.ts @@ -1,8 +1,11 @@ import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; +import tailwindcss from "@tailwindcss/vite"; +import { fileURLToPath, URL } from "node:url"; export default defineConfig({ - plugins: [react()], + plugins: [react(), tailwindcss()], + resolve: { alias: { "@": fileURLToPath(new URL("./src", import.meta.url)) } }, build: { outDir: "../internal/webui/dist", emptyOutDir: true, diff --git a/web/vitest.config.ts b/web/vitest.config.ts new file mode 100644 index 0000000..c4c328d --- /dev/null +++ b/web/vitest.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from "vitest/config"; +import react from "@vitejs/plugin-react"; +import { fileURLToPath, URL } from "node:url"; +export default defineConfig({ + plugins: [react()], + resolve: { alias: { "@": fileURLToPath(new URL("./src", import.meta.url)) } }, + test: { + environment: "jsdom", + setupFiles: ["./src/test/setup.ts"], + clearMocks: true, + }, +}); From 69b97743df58c841f300a7f34b871e2ec92af48e Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Wed, 7 Oct 2026 17:57:00 +0800 Subject: [PATCH 10/28] fix(build): reject unsafe archive extraction paths Extract ZIP entries through an os.Root so existing symlinks cannot redirect writes outside the destination. Cover traversal, external symlinks and normal nested entries with regression tests. --- tools/zipdir/main.go | 12 ++++-- tools/zipdir/main_test.go | 78 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 4 deletions(-) create mode 100644 tools/zipdir/main_test.go diff --git a/tools/zipdir/main.go b/tools/zipdir/main.go index 4731136..06cff0b 100644 --- a/tools/zipdir/main.go +++ b/tools/zipdir/main.go @@ -116,6 +116,11 @@ func unzip(archivePath, destination string) error { if err := os.MkdirAll(destination, 0o755); err != nil { return err } + root, err := os.OpenRoot(destination) + if err != nil { + return err + } + defer root.Close() archive, err := zip.OpenReader(archivePath) if err != nil { return err @@ -128,22 +133,21 @@ func unzip(archivePath, destination string) error { strings.HasPrefix(name, ".."+string(filepath.Separator)) { return fmt.Errorf("unsafe archive path: %q", entry.Name) } - target := filepath.Join(destination, name) mode := entry.Mode() switch { case mode.IsDir(): - if err := os.MkdirAll(target, mode.Perm()); err != nil { + if err := root.MkdirAll(name, mode.Perm()); err != nil { return err } case mode.IsRegular(): - if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + if err := root.MkdirAll(filepath.Dir(name), 0o755); err != nil { return err } reader, err := entry.Open() if err != nil { return err } - writer, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode.Perm()) + writer, err := root.OpenFile(name, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode.Perm()) if err != nil { reader.Close() return err diff --git a/tools/zipdir/main_test.go b/tools/zipdir/main_test.go new file mode 100644 index 0000000..d0b4369 --- /dev/null +++ b/tools/zipdir/main_test.go @@ -0,0 +1,78 @@ +package main + +import ( + "archive/zip" + "os" + "path/filepath" + "testing" +) + +func TestArchiveRoundTrip(t *testing.T) { + dir := t.TempDir() + source := filepath.Join(dir, "source", "nested") + if err := os.MkdirAll(source, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(source, "file.txt"), []byte("round trip"), 0o644); err != nil { + t.Fatal(err) + } + archive := filepath.Join(dir, "archive.zip") + if err := zipDir(filepath.Dir(source), archive); err != nil { + t.Fatal(err) + } + destination := filepath.Join(dir, "output") + if err := unzip(archive, destination); err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(filepath.Join(destination, "source", "nested", "file.txt")) + if err != nil || string(got) != "round trip" { + t.Fatalf("extracted content = %q, %v", got, err) + } +} + +func TestExtractCannotWriteThroughExistingSymlink(t *testing.T) { + for _, name := range []string{"linked/file.txt", "leaf.txt"} { + t.Run(name, func(t *testing.T) { + dir := t.TempDir() + outside, destination := filepath.Join(dir, "outside"), filepath.Join(dir, "output") + for _, path := range []string{outside, destination} { + if err := os.Mkdir(path, 0o755); err != nil { + t.Fatal(err) + } + } + target, link := outside, filepath.Join(destination, "linked") + if name == "leaf.txt" { + target = filepath.Join(outside, "file.txt") + link = filepath.Join(destination, "leaf.txt") + } + if err := os.Symlink(target, link); err != nil { + t.Skipf("symlink unavailable: %v", err) + } + archivePath := filepath.Join(dir, "archive.zip") + file, err := os.Create(archivePath) + if err != nil { + t.Fatal(err) + } + archive := zip.NewWriter(file) + writer, err := archive.Create(name) + if err != nil { + t.Fatal(err) + } + if _, err := writer.Write([]byte("escape")); err != nil { + t.Fatal(err) + } + if err := archive.Close(); err != nil { + t.Fatal(err) + } + if err := file.Close(); err != nil { + t.Fatal(err) + } + if err := unzip(archivePath, destination); err == nil { + t.Fatal("accepted an escaping symlink") + } + if _, err := os.Stat(filepath.Join(outside, "file.txt")); !os.IsNotExist(err) { + t.Fatalf("wrote outside destination: %v", err) + } + }) + } +} From c90819fcb046efd2768a78e63f990a13bf5aace1 Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Wed, 7 Oct 2026 18:06:44 +0800 Subject: [PATCH 11/28] fix(auth): compare redirect origins using default ports Treat an omitted HTTPS port and explicit :443 as the same origin, including host case differences. Use the same comparison for identity, controller and CAS redirects while preserving rejection of other hosts, ports and HTTPS downgrades. Cover the login completion regression observed against ShanghaiTech IDS. --- internal/httporigin/origin.go | 27 +++++++++++ internal/httporigin/origin_test.go | 43 ++++++++++++++++ internal/idsauth/client.go | 4 +- internal/idsauth/default_port_test.go | 70 +++++++++++++++++++++++++++ internal/idsauth/ecnu.go | 3 +- internal/sdpc/client.go | 4 +- internal/sdpc/login.go | 7 +-- 7 files changed, 152 insertions(+), 6 deletions(-) create mode 100644 internal/httporigin/origin.go create mode 100644 internal/httporigin/origin_test.go create mode 100644 internal/idsauth/default_port_test.go diff --git a/internal/httporigin/origin.go b/internal/httporigin/origin.go new file mode 100644 index 0000000..bab59ab --- /dev/null +++ b/internal/httporigin/origin.go @@ -0,0 +1,27 @@ +// Package httporigin compares HTTP origins without treating a default port as a different origin. +package httporigin + +import ( + "net/url" + "strings" +) + +func Same(a, b *url.URL) bool { + if a == nil || b == nil || a.User != nil || b.User != nil || a.Hostname() == "" || b.Hostname() == "" { + return false + } + scheme := strings.ToLower(a.Scheme) + if (scheme != "https" && scheme != "http") || scheme != strings.ToLower(b.Scheme) { + return false + } + port := func(u *url.URL) string { + if p := u.Port(); p != "" { + return p + } + if scheme == "https" { + return "443" + } + return "80" + } + return strings.EqualFold(a.Hostname(), b.Hostname()) && port(a) == port(b) +} diff --git a/internal/httporigin/origin_test.go b/internal/httporigin/origin_test.go new file mode 100644 index 0000000..57d7cc1 --- /dev/null +++ b/internal/httporigin/origin_test.go @@ -0,0 +1,43 @@ +package httporigin + +import ( + "net/url" + "testing" +) + +func TestSame(t *testing.T) { + for _, test := range []struct { + name, first, second string + want bool + }{ + {"https default port", "https://example.edu.cn/login", "https://example.edu.cn:443/result", true}, + {"https reverse", "https://example.edu.cn:443", "https://example.edu.cn", true}, + {"host case", "https://EXAMPLE.edu.cn", "https://example.edu.cn:443", true}, + {"http default port", "http://example.edu.cn", "http://example.edu.cn:80", true}, + {"same custom port", "https://example.edu.cn:8443", "https://example.edu.cn:8443/result", true}, + {"ipv6 default port", "https://[::1]", "https://[::1]:443", true}, + {"different port", "https://example.edu.cn", "https://example.edu.cn:8443", false}, + {"different host", "https://example.edu.cn", "https://other.edu.cn:443", false}, + {"downgrade", "https://example.edu.cn", "http://example.edu.cn:443", false}, + {"userinfo", "https://example.edu.cn", "https://user@example.edu.cn", false}, + {"unsupported scheme", "file://example.edu.cn", "file://example.edu.cn", false}, + {"missing host", "https:/login", "https:/login", false}, + } { + t.Run(test.name, func(t *testing.T) { + a, err := url.Parse(test.first) + if err != nil { + t.Fatal(err) + } + b, err := url.Parse(test.second) + if err != nil { + t.Fatal(err) + } + if got := Same(a, b); got != test.want { + t.Fatalf("Same = %t, want %t", got, test.want) + } + }) + } + if Same(nil, &url.URL{}) || Same(&url.URL{}, nil) { + t.Fatal("missing URL accepted") + } +} diff --git a/internal/idsauth/client.go b/internal/idsauth/client.go index 34ab0e5..e3a97f1 100644 --- a/internal/idsauth/client.go +++ b/internal/idsauth/client.go @@ -5,6 +5,8 @@ import ( "errors" "net/http" "strings" + + "github.com/ShanghaitechGeekPie/geektrust/internal/httporigin" ) // DefaultUserAgent matches the Python library's default browser UA. @@ -62,7 +64,7 @@ func (c *Client) do(req *http.Request) (*http.Response, error) { // A successful login may navigate to another service. Return that // response and confirm the identity session separately; never forward // assertion data or fetch challenges outside the credential origin. - if r.URL.Scheme != req.URL.Scheme || r.URL.Host != req.URL.Host { + if !httporigin.Same(r.URL, req.URL) { return http.ErrUseLastResponse } if checkRedirect != nil { diff --git a/internal/idsauth/default_port_test.go b/internal/idsauth/default_port_test.go new file mode 100644 index 0000000..61c30a4 --- /dev/null +++ b/internal/idsauth/default_port_test.go @@ -0,0 +1,70 @@ +package idsauth + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/cookiejar" + "strings" + "testing" +) + +type identityTransportFunc func(*http.Request) (*http.Response, error) + +func (f identityTransportFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +func TestShanghaiTechLoginCompletesDefaultPortRedirect(t *testing.T) { + const host = "ids.example.edu.cn" + for _, destination := range []string{host + ":443", "IDS.example.edu.cn:443"} { + t.Run(destination, func(t *testing.T) { + persisted, completed := false, false + transport := identityTransportFunc(func(r *http.Request) (*http.Response, error) { + response := &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Request: r} + body := "" + switch r.URL.Path { + case "/authserver/login": + if r.Method == http.MethodGet { + body = `` + } else { + if !persisted { + t.Error("assertion submitted before counter persistence") + } + response.StatusCode = http.StatusFound + response.Header.Set("Location", "https://"+destination+"/authserver/index.do") + } + case "/authserver/startAssertion": + options := challengeOptions() + options["rpId"] = host + options["allowCredentials"] = []any{map[string]any{"id": "cred-id-b64url", "type": "public-key"}} + payload, _ := json.Marshal(map[string]any{"result": map[string]any{"request": map[string]any{"requestId": "synthetic-request", "publicKeyCredentialRequestOptions": options}}}) + body = string(payload) + case "/authserver/index.do": + completed = true + response.Header.Set("Set-Cookie", "identity-session=synthetic; Path=/; Secure") + case "/personalInfo/common/tenant/info": + if _, err := r.Cookie("identity-session"); err != nil { + response.StatusCode = http.StatusUnauthorized + } + default: + t.Fatalf("unexpected login request: %s", r.URL.Path) + } + response.Body = io.NopCloser(strings.NewReader(body)) + return response, nil + }) + fields := testKeystoreMap(t) + fields["base_url"], fields["rp_id"] = "https://"+host, host + store, err := ParseKeystore(pythonFormat(t, fields), func([]byte) error { persisted = true; return nil }) + if err != nil { + t.Fatal(err) + } + jar, _ := cookiejar.New(nil) + if err := NewClient(store, &http.Client{Jar: jar, Transport: transport}).Login(context.Background()); err != nil { + t.Fatal(err) + } + if !completed { + t.Fatal("default-port login completion was skipped") + } + }) + } +} diff --git a/internal/idsauth/ecnu.go b/internal/idsauth/ecnu.go index d368c56..6904d42 100644 --- a/internal/idsauth/ecnu.go +++ b/internal/idsauth/ecnu.go @@ -18,6 +18,7 @@ import ( "regexp" "strings" + "github.com/ShanghaitechGeekPie/geektrust/internal/httporigin" "golang.org/x/net/html" ) @@ -164,7 +165,7 @@ func (c *ecnuClient) request(ctx context.Context, method, target, content string if len(via) >= 10 { return errors.New("SSO redirect limit") } - if r.URL.Scheme != origin.Scheme || r.URL.Host != origin.Host { + if !httporigin.Same(r.URL, origin) { return http.ErrUseLastResponse } return nil diff --git a/internal/sdpc/client.go b/internal/sdpc/client.go index ac94d08..33d011e 100644 --- a/internal/sdpc/client.go +++ b/internal/sdpc/client.go @@ -17,6 +17,8 @@ import ( "io" "net/http" "net/url" + + "github.com/ShanghaitechGeekPie/geektrust/internal/httporigin" ) // ClientTypeBrowser is the unsigned browser client path. @@ -185,7 +187,7 @@ func (c *Client) doJSONWithType(ctx context.Context, method, path, clientType st hc := *c.HTTP checkRedirect := hc.CheckRedirect hc.CheckRedirect = func(r *http.Request, via []*http.Request) error { - if r.URL.Scheme != req.URL.Scheme || r.URL.Host != req.URL.Host { + if !httporigin.Same(r.URL, req.URL) { return errors.New("controller redirect outside origin") } if checkRedirect != nil { diff --git a/internal/sdpc/login.go b/internal/sdpc/login.go index 7ba8723..6fc944b 100644 --- a/internal/sdpc/login.go +++ b/internal/sdpc/login.go @@ -9,6 +9,7 @@ import ( "net/url" "github.com/ShanghaitechGeekPie/geektrust/auth" + "github.com/ShanghaitechGeekPie/geektrust/internal/httporigin" ) // CasTicket runs the CAS redirect chain: @@ -50,12 +51,12 @@ func (c *Client) CasTicket(ctx context.Context) (string, error) { if base.Scheme == "https" && r.URL.Scheme != "https" { return errors.New("cas chain: insecure redirect") } - if r.URL.Host == base.Host && r.URL.Scheme == base.Scheme && r.URL.Path == "/portal/shortcut.html" { + if httporigin.Same(r.URL, base) && r.URL.Path == "/portal/shortcut.html" { shortcutURL = r.URL return http.ErrUseLastResponse } // Never leak the controller CSRF token to the IDS hop. - if r.URL.Host != base.Host { + if !httporigin.Same(r.URL, base) { r.Header.Del("x-csrf-token") } if len(via) >= 10 { @@ -83,7 +84,7 @@ func (c *Client) CasTicket(ctx context.Context) (string, error) { if shortcutURL == nil { // Some controllers serve shortcut.html directly as the final 200. - if resp.StatusCode == http.StatusOK && resp.Request != nil && resp.Request.URL.Host == base.Host && resp.Request.URL.Scheme == base.Scheme && resp.Request.URL.Path == "/portal/shortcut.html" { + if resp.StatusCode == http.StatusOK && resp.Request != nil && httporigin.Same(resp.Request.URL, base) && resp.Request.URL.Path == "/portal/shortcut.html" { shortcutURL = resp.Request.URL } } From 348d829c1e2706fe8e6598345549f2ac6829ecf6 Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Wed, 7 Oct 2026 18:16:58 +0800 Subject: [PATCH 12/28] fix(web): forward button refs for theme menu positioning Forward the shared Button ref to its DOM element for React 18 so Radix can position the theme dropdown and restore keyboard focus. Cover real theme menu selection, persistence, system changes and Escape focus restoration. --- web/src/components/ThemeToggle.test.tsx | 55 +++++++++++++++++++++++++ web/src/components/ui/button.tsx | 27 +++++++----- 2 files changed, 71 insertions(+), 11 deletions(-) create mode 100644 web/src/components/ThemeToggle.test.tsx diff --git a/web/src/components/ThemeToggle.test.tsx b/web/src/components/ThemeToggle.test.tsx new file mode 100644 index 0000000..a2b1ef7 --- /dev/null +++ b/web/src/components/ThemeToggle.test.tsx @@ -0,0 +1,55 @@ +import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { beforeEach, expect, it, vi } from "vitest"; +import { ThemeProvider } from "./ThemeProvider"; +import { ThemeToggle } from "./ThemeToggle"; + +let systemDark = false; +let listeners: Set<() => void>; +beforeEach(() => { + localStorage.clear(); + document.documentElement.className = ""; + systemDark = false; + listeners = new Set(); + vi.stubGlobal("matchMedia", () => ({ + get matches() { return systemDark; }, + addEventListener: (_: string, fn: () => void) => listeners.add(fn), + removeEventListener: (_: string, fn: () => void) => listeners.delete(fn), + })); +}); + +function openMenu() { + const button = screen.getByRole("button", { name: "切换主题" }); + fireEvent(button, new MouseEvent("pointerdown", { bubbles: true, button: 0 })); + return screen.findByRole("menu"); +} + +it("selects each mode from the icon menu and remembers the selection", async () => { + const first = render(); + await openMenu(); + fireEvent.click(screen.getByRole("menuitemradio", { name: "浅色" })); + expect(localStorage.getItem("geektrust-theme")).toBe("light"); + expect(document.documentElement.classList.contains("dark")).toBe(false); + first.unmount(); + render(); + await openMenu(); + expect(screen.getByRole("menuitemradio", { name: "浅色" }).getAttribute("aria-checked")).toBe("true"); + fireEvent.click(screen.getByRole("menuitemradio", { name: "深色" })); + expect(document.documentElement.classList.contains("dark")).toBe(true); + await openMenu(); + fireEvent.click(screen.getByRole("menuitemradio", { name: "跟随系统" })); + expect(localStorage.getItem("geektrust-theme")).toBe("system"); + expect(document.documentElement.classList.contains("dark")).toBe(false); + act(() => { systemDark = true; listeners.forEach(fn => fn()); }); + expect(document.documentElement.classList.contains("dark")).toBe(true); +}); + +it("opens from the keyboard and restores focus to the icon after Escape", async () => { + render(); + const button = screen.getByRole("button", { name: "切换主题" }); + button.focus(); + fireEvent.keyDown(button, { key: "Enter" }); + const menu = await screen.findByRole("menu"); + fireEvent.keyDown(menu, { key: "Escape" }); + await waitFor(() => expect(screen.queryByRole("menu")).toBeNull()); + await waitFor(() => expect(document.activeElement).toBe(button)); +}); diff --git a/web/src/components/ui/button.tsx b/web/src/components/ui/button.tsx index f336ace..2e72b3d 100644 --- a/web/src/components/ui/button.tsx +++ b/web/src/components/ui/button.tsx @@ -40,20 +40,25 @@ const buttonVariants = cva( }, ); -function Button({ - className, - variant = "default", - size = "default", - asChild = false, - ...props -}: React.ComponentProps<"button"> & - VariantProps & { - asChild?: boolean; - }) { +const Button = React.forwardRef< + HTMLButtonElement, + React.ComponentProps<"button"> & + VariantProps & { asChild?: boolean } +>(function Button( + { + className, + variant = "default", + size = "default", + asChild = false, + ...props + }, + ref, +) { const Comp = asChild ? Slot.Root : "button"; return ( ); -} +}); export { Button, buttonVariants }; From be085aa91ab4aad983b3f761bc05165f1478e5c3 Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Wed, 7 Oct 2026 18:39:28 +0800 Subject: [PATCH 13/28] fix(web): keep destructive confirmation text readable in both themes Use the Button destructive variant instead of competing default and custom color classes. Reduce destructive background opacity in dark mode and on hover, verified against the built UI alongside the main dialogs in both themes. --- web/src/components/ConfirmDialog.tsx | 6 +----- web/src/components/ui/button.tsx | 2 +- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/web/src/components/ConfirmDialog.tsx b/web/src/components/ConfirmDialog.tsx index adf9d5d..62a877a 100644 --- a/web/src/components/ConfirmDialog.tsx +++ b/web/src/components/ConfirmDialog.tsx @@ -37,13 +37,9 @@ export function ConfirmDialog({ 取消 {action} diff --git a/web/src/components/ui/button.tsx b/web/src/components/ui/button.tsx index 2e72b3d..992a0ee 100644 --- a/web/src/components/ui/button.tsx +++ b/web/src/components/ui/button.tsx @@ -16,7 +16,7 @@ const buttonVariants = cva( ghost: "hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50", destructive: - "bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40", + "bg-destructive/10 text-destructive hover:bg-destructive/15 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/10 dark:hover:bg-destructive/15 dark:focus-visible:ring-destructive/40", link: "text-primary underline-offset-4 hover:underline", }, size: { From 5cb3d774db6a476ed0c10ba5b018a04d1bd64153 Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Wed, 7 Oct 2026 19:10:15 +0800 Subject: [PATCH 14/28] test(config): handle Windows line endings in the example regression Enable logging comments independently of newline bytes and run the example through both LF and CRLF inputs. Remove an obsolete placeholder replacement. --- internal/config/example_regression_test.go | 30 +++++++++++++--------- 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/internal/config/example_regression_test.go b/internal/config/example_regression_test.go index 51b7a5f..49782a4 100644 --- a/internal/config/example_regression_test.go +++ b/internal/config/example_regression_test.go @@ -12,17 +12,23 @@ func TestExampleLoggingGroupCanBeEnabled(t *testing.T) { if err != nil { t.Fatal(err) } - s := strings.ReplaceAll(string(b), "REPLACE_WITH_32_UPPERCASE_HEX", "0123456789ABCDEF0123456789ABCDEF") - s = strings.Replace(s, "# [logging]\n# level = \"info\"", "[logging]\nlevel = \"debug\"", 1) - path := filepath.Join(t.TempDir(), "config.toml") - if err := os.WriteFile(path, []byte(s), 0600); err != nil { - t.Fatal(err) - } - cfg, err := Load(path) - if err != nil { - t.Fatal(err) - } - if cfg.LogLevel != "debug" { - t.Fatalf("template log level=%s, want debug", cfg.LogLevel) + template := strings.ReplaceAll(string(b), "\r\n", "\n") + for _, ending := range []struct{ name, newline string }{{"LF", "\n"}, {"CRLF", "\r\n"}} { + t.Run(ending.name, func(t *testing.T) { + s := strings.ReplaceAll(template, "\n", ending.newline) + s = strings.Replace(s, "# [logging]", "[logging]", 1) + s = strings.Replace(s, "# level = \"info\"", "level = \"debug\"", 1) + path := filepath.Join(t.TempDir(), "config.toml") + if err := os.WriteFile(path, []byte(s), 0600); err != nil { + t.Fatal(err) + } + cfg, err := Load(path) + if err != nil { + t.Fatal(err) + } + if cfg.LogLevel != "debug" { + t.Fatalf("template log level=%s, want debug", cfg.LogLevel) + } + }) } } From 790f882131e762db29fee13cead27de00e89b170 Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Wed, 7 Oct 2026 19:10:23 +0800 Subject: [PATCH 15/28] feat(config): warn on file permission issues unless strict mode is enabled Add storage.strict_permissions, defaulting to warnings for permission inspection and restriction failures. Preserve content validation and I/O errors, pass the policy to credential and session storage, and verify existing files without changing their permissions. Keep best-effort private permissions for new files and preserve the setting during configuration migration. --- README.md | 2 + cmd/geektrust/config_cmd.go | 12 ++-- cmd/geektrust/init_cmd.go | 4 +- cmd/geektrust/library.go | 4 +- config.example.toml | 1 + internal/config/config.go | 37 +++++++++--- internal/config/init.go | 4 +- internal/config/permissions_test.go | 58 +++++++++++++++++++ internal/config/v2.go | 19 ++++-- internal/idsauth/keystore.go | 10 +--- internal/privatefile/permissions.go | 35 +++++++++++ internal/privatefile/permissions_test.go | 33 +++++++++++ internal/privatefile/permissions_unix.go | 14 ++++- internal/privatefile/permissions_windows.go | 52 ++++++++++++++++- internal/runtime/client_test.go | 2 +- internal/session/events_test.go | 4 +- internal/session/live_test.go | 2 +- internal/session/provider_test.go | 8 +-- internal/session/store.go | 26 ++++++--- .../session/store_permissions_unix_test.go | 34 +++++++++++ internal/session/store_test.go | 6 +- internal/storage/files.go | 26 +++++---- internal/storage/files_test.go | 6 +- internal/storage/lock_unix.go | 2 +- internal/storage/lock_windows.go | 2 +- internal/storage/permissions_unix_test.go | 38 ++++++++++++ internal/storage/permissions_windows_test.go | 40 ++++++++++++- 27 files changed, 410 insertions(+), 71 deletions(-) create mode 100644 internal/config/permissions_test.go create mode 100644 internal/privatefile/permissions_test.go create mode 100644 internal/session/store_permissions_unix_test.go create mode 100644 internal/storage/permissions_unix_test.go diff --git a/README.md b/README.md index 6bd624f..0f1c095 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,8 @@ keystore = "./ids-passkey.keystore" 配置按 `controller`、`auth`、`proxy`、`web`、`dns`、`storage`、`logging` 分组。监听地址省略时采用默认值,空字符串表示禁用。`controller.compatibility` 选择 `auto`、`shanghaitech`、`ecnu` 或 `generic`;它用于控制器兼容适配。`auth.mode` 支持 `auto`、`client`、`browser`;browser 模式不能绑定授信终端。 +文件权限检查和设置问题默认输出英文警告。在 `[storage]` 中设置 `strict_permissions = true` 后,这些问题会阻止操作。新文件仍会尝试设置私有权限;文件内容的格式校验始终保留,实际读写失败仍会报错。旧格式使用顶层 `strict_permissions`,迁移时会保留该设置。 + 旧格式继续可读,不自动重写。检查和迁移命令: ```sh diff --git a/cmd/geektrust/config_cmd.go b/cmd/geektrust/config_cmd.go index 9c091f1..0eba013 100644 --- a/cmd/geektrust/config_cmd.go +++ b/cmd/geektrust/config_cmd.go @@ -32,7 +32,7 @@ func cmdConfig(path string, args []string) error { fmt.Println("configuration valid") return nil } - fmt.Printf("config_version = %d\ncontroller = %q\ncompatibility = %q\nauth_mode = %q\ndns_strategy = %q\nkeystore = %q\nstate_file = %q\n", c.Version, c.BaseURL, c.Compatibility, c.ClientType, c.DNSStrategy, c.Keystore, c.StateFile) + fmt.Printf("config_version = %d\ncontroller = %q\ncompatibility = %q\nauth_mode = %q\ndns_strategy = %q\nkeystore = %q\nstate_file = %q\nstrict_permissions = %t\n", c.Version, c.BaseURL, c.Compatibility, c.ClientType, c.DNSStrategy, c.Keystore, c.StateFile, c.StrictPermissions) return nil case "migrate": fs := flag.NewFlagSet("config migrate", flag.ContinueOnError) @@ -51,18 +51,22 @@ func cmdConfig(path string, args []string) error { fmt.Print(string(b)) return nil } + cfg, e := config.Load(path) + if e != nil { + return e + } old, e := os.ReadFile(path) if e != nil { return e } - if e = storage.CreateExclusive(path+".v1.bak", old); e != nil { + if e = storage.CreateExclusive(path+".v1.bak", old, cfg.StrictPermissions); e != nil { return fmt.Errorf("create migration backup: %w", e) } - if e = storage.WriteAtomic(path, b, 0600); e != nil { + if e = storage.WriteAtomic(path, b, cfg.StrictPermissions); e != nil { return e } if _, e = config.Load(path); e != nil { - _ = storage.WriteAtomic(path, old, 0600) + _ = storage.WriteAtomic(path, old, cfg.StrictPermissions) return e } fmt.Println("configuration migrated; original retained in " + path + ".v1.bak") diff --git a/cmd/geektrust/init_cmd.go b/cmd/geektrust/init_cmd.go index 4c74ac5..7d7d7f3 100644 --- a/cmd/geektrust/init_cmd.go +++ b/cmd/geektrust/init_cmd.go @@ -140,7 +140,7 @@ func bindPasskeyKeystore(ctx context.Context, uvx, destination string) error { _ = os.Remove(tmpPath) } }() - if err := privatefile.Protect(tmpPath); err != nil { + if err := privatefile.Protect(tmpPath, false); err != nil { _ = tmp.Close() return fmt.Errorf("secure temporary keystore: %w", err) } @@ -163,7 +163,7 @@ func bindPasskeyKeystore(ctx context.Context, uvx, destination string) error { if err != nil || !info.Mode().IsRegular() || info.Size() == 0 { return fmt.Errorf("passkey binding completed without creating a valid keystore") } - if err := privatefile.Protect(tmpPath); err != nil { + if err := privatefile.Protect(tmpPath, false); err != nil { return fmt.Errorf("secure bound keystore: %w", err) } // Linking within the same directory installs the completed file diff --git a/cmd/geektrust/library.go b/cmd/geektrust/library.go index 6266c4d..fbac12d 100644 --- a/cmd/geektrust/library.go +++ b/cmd/geektrust/library.go @@ -24,7 +24,7 @@ func commandClient(cfg *config.Config, logger *slog.Logger) (*runtime.Runtime, e if e := cfg.EnsureDeviceID(); e != nil { return nil, e } - identity, e := auth.NewPasskey(storage.CredentialFile(cfg.Keystore)) + identity, e := auth.NewPasskey(storage.CredentialFile{Path: cfg.Keystore, StrictPermissions: cfg.StrictPermissions}) if e != nil { return nil, e } @@ -33,7 +33,7 @@ func commandClient(cfg *config.Config, logger *slog.Logger) (*runtime.Runtime, e return "", auth.ErrUnsupported } return smsPrompt(ctx) - }}, Compatibility: compatibility.Options{Profile: cfg.Compatibility, Protocol: compatibility.ProtocolOptions{ControllerPlatform: cfg.Platform}, Fallbacks: &cfg.Fallbacks}, SessionStore: commandSessionStore{session.NewStore(cfg.StateFile)}} + }}, Compatibility: compatibility.Options{Profile: cfg.Compatibility, Protocol: compatibility.ProtocolOptions{ControllerPlatform: cfg.Platform}, Fallbacks: &cfg.Fallbacks}, SessionStore: commandSessionStore{session.NewStore(cfg.StateFile, cfg.StrictPermissions)}} if cfg.ClientType == "client" { o.Auth.Mode = runtime.DesktopMode } diff --git a/config.example.toml b/config.example.toml index 5f577d8..016dc23 100644 --- a/config.example.toml +++ b/config.example.toml @@ -30,6 +30,7 @@ keystore = "./ids-passkey.keystore" # [storage] # directory = "" # 缺省使用平台用户私有持久目录 # state_file = "" # 留空使用 directory/session.enc;非空覆盖会话文件读写路径 +# strict_permissions = false # 权限问题默认只警告;设为 true 时拒绝权限不合格的文件 # [logging] # level = "info" diff --git a/internal/config/config.go b/internal/config/config.go index e50e041..a1d8412 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -14,6 +14,7 @@ import ( "github.com/BurntSushi/toml" + "github.com/ShanghaitechGeekPie/geektrust/internal/privatefile" "github.com/ShanghaitechGeekPie/geektrust/internal/settings" ) @@ -30,13 +31,14 @@ const DefaultWebListen = "127.0.0.1:8081" // Config is the top-level configuration. type Config struct { - UnknownFields []string `toml:"-"` - Version int `toml:"-"` - Compatibility public.Profile `toml:"-"` - DNSStrategy string `toml:"-"` - Directory string `toml:"-"` - CAFile string `toml:"-"` - AppID string `toml:"app_id"` + UnknownFields []string `toml:"-"` + Version int `toml:"-"` + Compatibility public.Profile `toml:"-"` + DNSStrategy string `toml:"-"` + Directory string `toml:"-"` + CAFile string `toml:"-"` + AppID string `toml:"app_id"` + StrictPermissions bool `toml:"strict_permissions"` Fallbacks public.Fallbacks `toml:"-"` GatewayTLSName string `toml:"-"` @@ -96,7 +98,11 @@ func Load(path string) (*Config, error) { if header.Version != 2 { return nil, fmt.Errorf("unsupported config_version %d", header.Version) } - return loadV2(path, data) + cfg, err := loadV2(path, data) + if err != nil { + return nil, err + } + return cfg, cfg.checkPermissions(path) } var cfg Config meta, err := toml.Decode(string(data), &cfg) @@ -121,7 +127,20 @@ func Load(path string) (*Config, error) { if err := cfg.validate(); err != nil { return nil, fmt.Errorf("config %s: %w", path, err) } - return &cfg, nil + return &cfg, cfg.checkPermissions(path) +} + +func (c *Config) checkPermissions(path string) error { + paths := []string{path, c.Keystore, c.StateFile, c.StateFile + ".key"} + for _, p := range paths { + if p == "" { + continue + } + if err := privatefile.Check(p, c.StrictPermissions); err != nil { + return err + } + } + return nil } func (c *Config) applyDefaults() { diff --git a/internal/config/init.go b/internal/config/init.go index e1d0587..14521ae 100644 --- a/internal/config/init.go +++ b/internal/config/init.go @@ -147,7 +147,7 @@ func writeConfigFile(path string, data []byte, force bool) error { } tmpPath := tmp.Name() defer os.Remove(tmpPath) - if err := privatefile.Protect(tmpPath); err != nil { + if err := privatefile.Protect(tmpPath, false); err != nil { _ = tmp.Close() return fmt.Errorf("secure temporary config: %w", err) } @@ -161,7 +161,7 @@ func writeConfigFile(path string, data []byte, force bool) error { } func writeAndClose(f *os.File, data []byte) error { - if err := privatefile.Protect(f.Name()); err != nil { + if err := privatefile.Protect(f.Name(), false); err != nil { f.Close() return err } diff --git a/internal/config/permissions_test.go b/internal/config/permissions_test.go new file mode 100644 index 0000000..d320993 --- /dev/null +++ b/internal/config/permissions_test.go @@ -0,0 +1,58 @@ +//go:build !windows + +package config + +import ( + "os" + "path/filepath" + "testing" +) + +func TestStrictPermissionsIsOptionalAndPreservedByMigration(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.toml") + data := "keystore='fixture'\nstrict_permissions=true\n" + if err := os.WriteFile(path, []byte(data), 0600); err != nil { + t.Fatal(err) + } + if err := os.Chmod(path, 0644); err != nil { + t.Fatal(err) + } + if _, err := Load(path); err == nil { + t.Fatal("strict configuration accepted shared permissions") + } + if err := os.WriteFile(path, []byte("keystore='fixture'\n"), 0600); err != nil { + t.Fatal(err) + } + if cfg, err := Load(path); err != nil || cfg.StrictPermissions { + t.Fatalf("default permission mode rejected config: %v", err) + } + if err := os.Chmod(path, 0600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(data), 0600); err != nil { + t.Fatal(err) + } + migrated, err := Migration(path) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, migrated, 0600); err != nil { + t.Fatal(err) + } + cfg, err := Load(path) + if err != nil || !cfg.StrictPermissions { + t.Fatalf("migration lost strict permissions: %v", err) + } + if err := os.Chmod(path, 0644); err != nil { + t.Fatal(err) + } + if _, err := Load(path); err == nil { + t.Fatal("strict v2 configuration accepted shared permissions") + } + if err := os.WriteFile(path, []byte("config_version=2\ninvalid = ["), 0600); err != nil { + t.Fatal(err) + } + if _, err := Load(path); err == nil { + t.Fatal("default permission mode disabled format validation") + } +} diff --git a/internal/config/v2.go b/internal/config/v2.go index 172c2b7..a2672b8 100644 --- a/internal/config/v2.go +++ b/internal/config/v2.go @@ -7,6 +7,7 @@ import ( "github.com/BurntSushi/toml" public "github.com/ShanghaitechGeekPie/geektrust/compatibility" defaults "github.com/ShanghaitechGeekPie/geektrust/internal/compatibility" + "github.com/ShanghaitechGeekPie/geektrust/internal/privatefile" "github.com/ShanghaitechGeekPie/geektrust/internal/storage" "net" "net/url" @@ -49,8 +50,9 @@ type FileV2 struct { Servers []string `toml:"servers"` } `toml:"dns"` Storage struct { - Directory string `toml:"directory"` - StateFile string `toml:"state_file"` + Directory string `toml:"directory"` + StateFile string `toml:"state_file"` + StrictPermissions bool `toml:"strict_permissions"` } `toml:"storage"` Logging struct { Level string `toml:"level"` @@ -135,7 +137,11 @@ func loadV2(path string, data []byte) (*Config, error) { } id := f.Auth.DeviceID if id == "" { - b, e := os.ReadFile(filepath.Join(directory, "device_id")) + identityPath := filepath.Join(directory, "device_id") + if e := privatefile.Check(identityPath, f.Storage.StrictPermissions); e != nil { + return nil, e + } + b, e := os.ReadFile(identityPath) if e == nil { id = strings.TrimSpace(string(b)) } else if !errors.Is(e, os.ErrNotExist) { @@ -143,6 +149,7 @@ func loadV2(path string, data []byte) (*Config, error) { } } cfg := &Config{Version: 2, Directory: directory, DeviceID: id, Keystore: resolve(f.Auth.Passkey.Keystore), BaseURL: strings.TrimRight(f.Controller.URL, "/"), Platform: v.Platform, Compatibility: profile, ClientType: mode, LoginDomain: f.Auth.LoginDomain, Fallbacks: v.Fallbacks, GatewayTLSName: v.GatewayServerName, StateFile: filepath.Join(directory, "session.enc"), DNS: append([]string(nil), f.DNS.Servers...), DNSStrategy: f.DNS.Strategy, LogLevel: f.Logging.Level} + cfg.StrictPermissions = f.Storage.StrictPermissions if cfg.DNSStrategy == "" { cfg.DNSStrategy = "auto" } @@ -240,7 +247,10 @@ func (c *Config) EnsureDeviceID() error { return e } p := filepath.Join(c.Directory, "device_id") - if e = storage.CreateExclusive(p, []byte(id+"\n")); errors.Is(e, os.ErrExist) { + if e = storage.CreateExclusive(p, []byte(id+"\n"), c.StrictPermissions); errors.Is(e, os.ErrExist) { + if e := privatefile.Check(p, c.StrictPermissions); e != nil { + return e + } b, e := os.ReadFile(p) if e != nil { return e @@ -283,6 +293,7 @@ func Migration(path string) ([]byte, error) { return nil, e } f.Storage.StateFile, e = filepath.Abs(c.StateFile) + f.Storage.StrictPermissions = c.StrictPermissions if e != nil { return nil, e } diff --git a/internal/idsauth/keystore.go b/internal/idsauth/keystore.go index ebc27f8..9f59208 100644 --- a/internal/idsauth/keystore.go +++ b/internal/idsauth/keystore.go @@ -40,7 +40,7 @@ func LoadKeystore(path string) (*Keystore, error) { if err != nil { return nil, fmt.Errorf("read keystore: %w", err) } - k, err := ParseKeystore(blob, func(data []byte) error { return writeFileAtomic(path, data, 0o600) }) + k, err := ParseKeystore(blob, func(data []byte) error { return storage.WriteAtomic(path, data, false) }) if err == nil { k.path = path } @@ -219,7 +219,7 @@ func (k *Keystore) Save() error { return fmt.Errorf("credential persistence is required") } if save == nil { - save = func(data []byte) error { return writeFileAtomic(k.path, data, 0o600) } + save = func(data []byte) error { return storage.WriteAtomic(k.path, data, false) } } if err := save(buf.Bytes()); err != nil { return fmt.Errorf("write keystore: %w", err) @@ -239,9 +239,3 @@ func marshalNoEscape(v any) ([]byte, error) { } return bytes.TrimRight(buf.Bytes(), "\n"), nil } - -// writeFileAtomic writes data to a temp file in the same directory and renames -// it over path, so a crash never leaves a half-written secret file. -func writeFileAtomic(path string, data []byte, perm os.FileMode) error { - return storage.WriteAtomic(path, data, perm) -} diff --git a/internal/privatefile/permissions.go b/internal/privatefile/permissions.go index 5df4b7e..a9f9ea6 100644 --- a/internal/privatefile/permissions.go +++ b/internal/privatefile/permissions.go @@ -1,2 +1,37 @@ // Package privatefile protects new secret files; it does not audit user directories. package privatefile + +import ( + "errors" + "fmt" + "os" +) + +// Check verifies existing file permissions without changing them. +func Check(path string, strict bool) error { + err := check(path) + if errors.Is(err, os.ErrNotExist) { + return nil + } + return permissionResult(path, "verify", err, strict) +} + +// Protect attempts to restrict a file before its contents are written. +func Protect(path string, strict bool) error { + err := protect(path) + if err == nil { + err = check(path) + } + return permissionResult(path, "restrict", err, strict) +} + +func permissionResult(path, operation string, err error, strict bool) error { + if err == nil { + return nil + } + if strict { + return fmt.Errorf("cannot %s private file permissions for %q: %w", operation, path, err) + } + fmt.Fprintf(os.Stderr, "Warning: cannot %s private file permissions for %q: %v; continuing because strict_permissions is disabled.\n", operation, path, err) + return nil +} diff --git a/internal/privatefile/permissions_test.go b/internal/privatefile/permissions_test.go new file mode 100644 index 0000000..ca295cf --- /dev/null +++ b/internal/privatefile/permissions_test.go @@ -0,0 +1,33 @@ +package privatefile + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestPermissionSettingFailureWarnsUnlessStrict(t *testing.T) { + path := filepath.Join(t.TempDir(), "missing", "secret") + warnings, err := os.CreateTemp(t.TempDir(), "warnings") + if err != nil { + t.Fatal(err) + } + previous := os.Stderr + os.Stderr = warnings + defer func() { os.Stderr = previous; warnings.Close() }() + if err := Protect(path, false); err != nil { + t.Fatal(err) + } + os.Stderr = previous + data, err := os.ReadFile(warnings.Name()) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(data), "Warning:") || !strings.Contains(string(data), "strict_permissions is disabled") { + t.Fatalf("missing English warning: %s", data) + } + if err := Protect(path, true); err == nil { + t.Fatal("strict permission setting accepted a missing target") + } +} diff --git a/internal/privatefile/permissions_unix.go b/internal/privatefile/permissions_unix.go index fe8a862..f0b80b4 100644 --- a/internal/privatefile/permissions_unix.go +++ b/internal/privatefile/permissions_unix.go @@ -3,9 +3,21 @@ package privatefile import ( + "fmt" "os" "path/filepath" ) func ResolveExistingPath(path string) (string, error) { return filepath.EvalSymlinks(path) } -func Protect(path string) error { return os.Chmod(path, 0600) } +func protect(path string) error { return os.Chmod(path, 0600) } + +func check(path string) error { + info, err := os.Stat(path) + if err != nil { + return err + } + if info.Mode().Perm()&0077 != 0 { + return fmt.Errorf("group or other users have access (mode %04o)", info.Mode().Perm()) + } + return nil +} diff --git a/internal/privatefile/permissions_windows.go b/internal/privatefile/permissions_windows.go index 651946d..2673b49 100644 --- a/internal/privatefile/permissions_windows.go +++ b/internal/privatefile/permissions_windows.go @@ -1,12 +1,15 @@ package privatefile import ( + "errors" "golang.org/x/sys/windows" "path/filepath" + "runtime" + "unsafe" ) func ResolveExistingPath(path string) (string, error) { return filepath.EvalSymlinks(path) } -func Protect(path string) error { +func protect(path string) error { user, err := windows.GetCurrentProcessToken().GetTokenUser() if err != nil { return err @@ -22,3 +25,50 @@ func Protect(path string) error { return windows.SetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, nil, nil, dacl, nil) } + +func check(path string) error { + resolved, err := ResolveExistingPath(path) + if err != nil { + return err + } + user, err := windows.GetCurrentProcessToken().GetTokenUser() + if err != nil { + return err + } + sd, err := windows.GetNamedSecurityInfo(resolved, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION) + if err != nil { + return err + } + defer runtime.KeepAlive(sd) + control, _, err := sd.Control() + if err != nil { + return err + } + if control&windows.SE_DACL_PROTECTED == 0 { + return errors.New("file permissions inherit from the parent directory") + } + dacl, _, err := sd.DACL() + if err != nil { + return err + } + if dacl == nil { + return errors.New("file has no restrictive DACL") + } + for i := uint32(0); i < uint32(dacl.AceCount); i++ { + var ace *windows.ACCESS_ALLOWED_ACE + if err := windows.GetAce(dacl, i, &ace); err != nil { + return err + } + if ace.Header.AceType == windows.ACCESS_DENIED_ACE_TYPE { + continue + } + if ace.Header.AceType != windows.ACCESS_ALLOWED_ACE_TYPE { + return errors.New("unsupported file permission entry") + } + sid := (*windows.SID)(unsafe.Pointer(&ace.SidStart)) + if ace.Mask != 0 && !sid.Equals(user.User.Sid) && !sid.IsWellKnown(windows.WinLocalSystemSid) { + return errors.New("file grants access to another identity") + } + } + return nil +} diff --git a/internal/runtime/client_test.go b/internal/runtime/client_test.go index 3d99b29..42576b4 100644 --- a/internal/runtime/client_test.go +++ b/internal/runtime/client_test.go @@ -79,7 +79,7 @@ func TestECNULiveAccess(t *testing.T) { t.Skip("explicit live credential required") } id, _ := NewDeviceID() - identity, err := auth.NewPasskey(storage.CredentialFile(path)) + identity, err := auth.NewPasskey(storage.CredentialFile{Path: path}) if err != nil { t.Fatal(err) } diff --git a/internal/session/events_test.go b/internal/session/events_test.go index a82dc82..0ebecfc 100644 --- a/internal/session/events_test.go +++ b/internal/session/events_test.go @@ -174,7 +174,7 @@ func newRestoreFixture(t *testing.T, handler http.HandlerFunc) *Provider { dir := t.TempDir() statePath := filepath.Join(dir, "state.enc") - if err := NewStore(statePath).Save(context.Background(), &State{ + if err := NewStore(statePath, false).Save(context.Background(), &State{ ControllerURL: srv.URL, Username: "u1", SID: "synthetic-sid", DeviceID: testDeviceID, @@ -185,7 +185,7 @@ func newRestoreFixture(t *testing.T, handler http.HandlerFunc) *Provider { t.Fatal(err) } p := NewProvider(settings.Session{DeviceID: testDeviceID, BaseURL: srv.URL, Platform: "Mac", ClientType: "browser", Gateways: []string{"192.0.2.1:441"}, LegacyGatewayOverride: true}, testLogger(), nil) - p.SetStore(NewStore(statePath)) + p.SetStore(NewStore(statePath, false)) p.Authenticate = func(context.Context, *http.Client) (string, error) { return "", errors.New("fixture full login disabled") } diff --git a/internal/session/live_test.go b/internal/session/live_test.go index 440bd47..c6496c6 100644 --- a/internal/session/live_test.go +++ b/internal/session/live_test.go @@ -28,7 +28,7 @@ func TestECNULiveSession(t *testing.T) { } cfg := &config.Config{Keystore: path, BaseURL: "https://vpn.ecnu.edu.cn", Platform: "Mac", ClientType: "browser", DeviceID: device} p := NewProvider(cfg.SessionOptions(), slog.New(slog.NewTextHandler(io.Discard, nil)), nil) - identity, err := auth.NewPasskey(storage.CredentialFile(path)) + identity, err := auth.NewPasskey(storage.CredentialFile{Path: path}) if err != nil { t.Fatal(err) } diff --git a/internal/session/provider_test.go b/internal/session/provider_test.go index 10fd8d9..f8aa048 100644 --- a/internal/session/provider_test.go +++ b/internal/session/provider_test.go @@ -78,7 +78,7 @@ func TestRestoreSkipsDifferentClientType(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { statePath := filepath.Join(t.TempDir(), "state.enc") - store := NewStore(statePath) + store := NewStore(statePath, false) const deviceID = "0123456789ABCDEF0123456789ABCDEF" if err := store.Save(context.Background(), &State{ ControllerURL: "http://127.0.0.1:1", @@ -139,7 +139,7 @@ func TestStoreReadPreservesExistingPermissions(t *testing.T) { if err := os.WriteFile(keyPath, key, 0o644); err != nil { t.Fatal(err) } - st := NewStore(filepath.Join(dir, "state.enc")) + st := NewStore(filepath.Join(dir, "state.enc"), false) if err := st.Save(context.Background(), &State{SID: "s"}); err != nil { t.Fatal(err) } @@ -161,9 +161,9 @@ func TestStoreReadPreservesExistingPermissions(t *testing.T) { // and creation, the existing key wins (O_EXCL path). func TestStoreReusesExistingKey(t *testing.T) { dir := t.TempDir() - st := NewStore(filepath.Join(dir, "state.enc")) + st := NewStore(filepath.Join(dir, "state.enc"), false) // Simulate the winner: create the key first. - winner := NewStore(filepath.Join(dir, "state.enc")) + winner := NewStore(filepath.Join(dir, "state.enc"), false) if err := winner.Save(context.Background(), &State{SID: "winner"}); err != nil { t.Fatal(err) } diff --git a/internal/session/store.go b/internal/session/store.go index e64ea63..cc7db1b 100644 --- a/internal/session/store.go +++ b/internal/session/store.go @@ -14,10 +14,11 @@ import ( "os" "time" + "github.com/ShanghaitechGeekPie/geektrust/internal/privatefile" "github.com/ShanghaitechGeekPie/geektrust/internal/storage" ) -// State is the persisted session (encrypted, 0600). +// State is the persisted encrypted session. type State struct { Version int `json:"version"` ControllerURL string `json:"controller_url"` @@ -46,16 +47,17 @@ type CookieRecord struct { Value string `json:"value"` } -// Store encrypts State with AES-256-GCM under a random key kept in a sibling -// 0600 key file (.key). The key is generated on first save; both -// files together protect credentials at rest while staying fully automatic -// (no passphrase to type). +// Store encrypts State with AES-256-GCM under a random sibling key file. +// File permission problems warn by default or fail when strict mode is enabled. type Store struct { - path string + path string + strictPermissions bool } // NewStore creates a Store for the given state file path. -func NewStore(path string) *Store { return &Store{path: path} } +func NewStore(path string, strictPermissions bool) *Store { + return &Store{path: path, strictPermissions: strictPermissions} +} func (s *Store) keyPath() string { return s.path + ".key" } @@ -85,6 +87,9 @@ func (s *Store) LoadBytes(ctx context.Context) ([]byte, error) { if e := ctx.Err(); e != nil { return nil, e } + if e := privatefile.Check(s.path, s.strictPermissions); e != nil { + return nil, e + } sealed, e := os.ReadFile(s.path) if errors.Is(e, os.ErrNotExist) { return nil, nil @@ -110,7 +115,7 @@ func (s *Store) SaveBytes(ctx context.Context, b []byte) error { if e != nil { return e } - return storage.WriteAtomic(s.path, sealed, 0600) + return storage.WriteAtomic(s.path, sealed, s.strictPermissions) } func (s *Store) Delete(ctx context.Context) error { if e := ctx.Err(); e != nil { @@ -125,6 +130,9 @@ func (s *Store) Delete(ctx context.Context) error { func (s *Store) readKey() ([]byte, error) { path := s.keyPath() + if err := privatefile.Check(path, s.strictPermissions); err != nil { + return nil, err + } key, err := os.ReadFile(path) if err != nil { return nil, err @@ -147,7 +155,7 @@ func (s *Store) loadOrCreateKey() ([]byte, error) { if _, e = rand.Read(key); e != nil { return nil, e } - if e = storage.CreateExclusive(s.keyPath(), key); errors.Is(e, os.ErrExist) { + if e = storage.CreateExclusive(s.keyPath(), key, s.strictPermissions); errors.Is(e, os.ErrExist) { return s.readKey() } else if e != nil { return nil, e diff --git a/internal/session/store_permissions_unix_test.go b/internal/session/store_permissions_unix_test.go new file mode 100644 index 0000000..39d56ee --- /dev/null +++ b/internal/session/store_permissions_unix_test.go @@ -0,0 +1,34 @@ +//go:build !windows + +package session + +import ( + "context" + "os" + "path/filepath" + "testing" +) + +func TestSessionKeyPermissionsRespectStrictMode(t *testing.T) { + path := filepath.Join(t.TempDir(), "session.enc") + strict := NewStore(path, true) + if err := strict.SaveBytes(context.Background(), []byte("fixture")); err != nil { + t.Fatal(err) + } + if err := os.Chmod(strict.keyPath(), 0644); err != nil { + t.Fatal(err) + } + if _, err := strict.LoadBytes(context.Background()); err == nil { + t.Fatal("strict session store accepted a shared key") + } + soft := NewStore(path, false) + if data, err := soft.LoadBytes(context.Background()); err != nil || string(data) != "fixture" { + t.Fatalf("default session read blocked: %v", err) + } + if err := os.WriteFile(path, []byte("invalid ciphertext"), 0600); err != nil { + t.Fatal(err) + } + if _, err := soft.LoadBytes(context.Background()); err == nil { + t.Fatal("default permission mode accepted invalid ciphertext") + } +} diff --git a/internal/session/store_test.go b/internal/session/store_test.go index 0e07ab1..5fe5af3 100644 --- a/internal/session/store_test.go +++ b/internal/session/store_test.go @@ -10,7 +10,7 @@ import ( func TestStoreRoundTrip(t *testing.T) { dir := t.TempDir() - st := NewStore(filepath.Join(dir, "state.enc")) + st := NewStore(filepath.Join(dir, "state.enc"), false) // No file yet → (nil, nil). got, err := st.Load(context.Background()) @@ -76,7 +76,7 @@ func TestStoreRoundTrip(t *testing.T) { func TestStoreWrongKey(t *testing.T) { dir := t.TempDir() - st := NewStore(filepath.Join(dir, "state.enc")) + st := NewStore(filepath.Join(dir, "state.enc"), false) if err := st.Save(context.Background(), &State{SID: "s"}); err != nil { t.Fatal(err) } @@ -95,7 +95,7 @@ func TestStoreInvalidKeyNotOverwritten(t *testing.T) { if err := os.WriteFile(keyPath, []byte("short"), 0o600); err != nil { t.Fatal(err) } - st := NewStore(filepath.Join(dir, "state.enc")) + st := NewStore(filepath.Join(dir, "state.enc"), false) if err := st.Save(context.Background(), &State{SID: "s"}); err == nil { t.Fatal("Save must fail on a present-but-invalid key file, not regenerate it") } diff --git a/internal/storage/files.go b/internal/storage/files.go index 88b1ec2..e4e758c 100644 --- a/internal/storage/files.go +++ b/internal/storage/files.go @@ -8,7 +8,7 @@ import ( "path/filepath" ) -func WriteAtomic(path string, data []byte, mode os.FileMode) error { +func WriteAtomic(path string, data []byte, strict bool) error { dir := filepath.Dir(path) if e := os.MkdirAll(dir, 0700); e != nil { return e @@ -19,7 +19,7 @@ func WriteAtomic(path string, data []byte, mode os.FileMode) error { } name := f.Name() defer os.Remove(name) - if e = privatefile.Protect(name); e != nil { + if e = privatefile.Protect(name, strict); e != nil { f.Close() return e } @@ -27,10 +27,6 @@ func WriteAtomic(path string, data []byte, mode os.FileMode) error { f.Close() return e } - if e = f.Chmod(mode); e != nil { - f.Close() - return e - } if e = f.Sync(); e != nil { f.Close() return e @@ -43,7 +39,7 @@ func WriteAtomic(path string, data []byte, mode os.FileMode) error { } return syncDirectory(dir) } -func CreateExclusive(path string, data []byte) error { +func CreateExclusive(path string, data []byte, strict bool) error { dir := filepath.Dir(path) if e := os.MkdirAll(dir, 0700); e != nil { return e @@ -54,7 +50,7 @@ func CreateExclusive(path string, data []byte) error { } name := f.Name() defer os.Remove(name) - if e = privatefile.Protect(name); e != nil { + if e = privatefile.Protect(name, strict); e != nil { f.Close() return e } @@ -75,21 +71,27 @@ func CreateExclusive(path string, data []byte) error { return syncDirectory(dir) } -type CredentialFile string +type CredentialFile struct { + Path string + StrictPermissions bool +} func (p CredentialFile) Load(ctx context.Context) ([]byte, error) { if e := ctx.Err(); e != nil { return nil, e } - return os.ReadFile(string(p)) + if e := privatefile.Check(p.Path, p.StrictPermissions); e != nil { + return nil, e + } + return os.ReadFile(p.Path) } func (p CredentialFile) Save(ctx context.Context, b []byte) error { if e := ctx.Err(); e != nil { return e } - target, e := filepath.EvalSymlinks(string(p)) + target, e := filepath.EvalSymlinks(p.Path) if e != nil { return e } - return WriteAtomic(target, b, 0600) + return WriteAtomic(target, b, p.StrictPermissions) } diff --git a/internal/storage/files_test.go b/internal/storage/files_test.go index 9ace318..6e47f46 100644 --- a/internal/storage/files_test.go +++ b/internal/storage/files_test.go @@ -15,15 +15,15 @@ func TestExclusivePublicationAndCredentialLock(t *testing.T) { var wg sync.WaitGroup for i := 0; i < 8; i++ { wg.Add(1) - go func() { defer wg.Done(); _ = CreateExclusive(p, []byte("complete identity")) }() + go func() { defer wg.Done(); _ = CreateExclusive(p, []byte("complete identity"), true) }() } wg.Wait() b, e := os.ReadFile(p) if e != nil || string(b) != "complete identity" { t.Fatal("partially published exclusive file") } - key := CredentialFile(filepath.Join(dir, "credential")) - if e = WriteAtomic(string(key), []byte("fixture"), 0600); e != nil { + key := CredentialFile{Path: filepath.Join(dir, "credential"), StrictPermissions: true} + if e = WriteAtomic(key.Path, []byte("fixture"), true); e != nil { t.Fatal(e) } unlock, e := key.Lock(context.Background()) diff --git a/internal/storage/lock_unix.go b/internal/storage/lock_unix.go index 02833ee..397e2cc 100644 --- a/internal/storage/lock_unix.go +++ b/internal/storage/lock_unix.go @@ -12,7 +12,7 @@ import ( ) func (p CredentialFile) Lock(ctx context.Context) (func(), error) { - canonical, e := filepath.EvalSymlinks(string(p)) + canonical, e := filepath.EvalSymlinks(p.Path) if e != nil { return nil, e } diff --git a/internal/storage/lock_windows.go b/internal/storage/lock_windows.go index 93aed5b..5be2dd8 100644 --- a/internal/storage/lock_windows.go +++ b/internal/storage/lock_windows.go @@ -10,7 +10,7 @@ import ( ) func (p CredentialFile) Lock(ctx context.Context) (func(), error) { - canonical, e := filepath.EvalSymlinks(string(p)) + canonical, e := filepath.EvalSymlinks(p.Path) if e != nil { return nil, e } diff --git a/internal/storage/permissions_unix_test.go b/internal/storage/permissions_unix_test.go new file mode 100644 index 0000000..5520d50 --- /dev/null +++ b/internal/storage/permissions_unix_test.go @@ -0,0 +1,38 @@ +//go:build !windows + +package storage + +import ( + "context" + "os" + "path/filepath" + "testing" +) + +func TestCredentialPermissionsWarnByDefaultAndFailWhenStrict(t *testing.T) { + path := filepath.Join(t.TempDir(), "credential") + if err := os.WriteFile(path, []byte("fixture"), 0600); err != nil { + t.Fatal(err) + } + if err := os.Chmod(path, 0644); err != nil { + t.Fatal(err) + } + soft := CredentialFile{Path: path} + if data, err := soft.Load(context.Background()); err != nil || string(data) != "fixture" { + t.Fatalf("default read blocked: %v", err) + } + info, _ := os.Stat(path) + if info.Mode().Perm() != 0644 { + t.Fatal("permission check changed the existing file") + } + strict := CredentialFile{Path: path, StrictPermissions: true} + if _, err := strict.Load(context.Background()); err == nil { + t.Fatal("strict read accepted shared permissions") + } + if err := os.Chmod(path, 0600); err != nil { + t.Fatal(err) + } + if _, err := strict.Load(context.Background()); err != nil { + t.Fatal(err) + } +} diff --git a/internal/storage/permissions_windows_test.go b/internal/storage/permissions_windows_test.go index e369a8d..e5c91ff 100644 --- a/internal/storage/permissions_windows_test.go +++ b/internal/storage/permissions_windows_test.go @@ -1,6 +1,8 @@ package storage import ( + "context" + "github.com/ShanghaitechGeekPie/geektrust/internal/privatefile" "golang.org/x/sys/windows" "os" "path/filepath" @@ -9,7 +11,7 @@ import ( func TestSecretFileHasProtectedDACL(t *testing.T) { path := filepath.Join(t.TempDir(), "secret") - if e := WriteAtomic(path, []byte("fixture"), 0600); e != nil { + if e := WriteAtomic(path, []byte("fixture"), true); e != nil { t.Fatal(e) } if b, e := os.ReadFile(path); e != nil || string(b) != "fixture" { @@ -28,3 +30,39 @@ func TestSecretFileHasProtectedDACL(t *testing.T) { t.Fatal("expected current-user and LocalSystem access only") } } + +func TestCredentialPermissionsWarnByDefaultAndFailWhenStrict(t *testing.T) { + path := filepath.Join(t.TempDir(), "credential") + if err := WriteAtomic(path, []byte("fixture"), true); err != nil { + t.Fatal(err) + } + user, err := windows.GetCurrentProcessToken().GetTokenUser() + if err != nil { + t.Fatal(err) + } + sd, err := windows.SecurityDescriptorFromString("D:P(A;;FA;;;SY)(A;;FA;;;" + user.User.Sid.String() + ")(A;;FR;;;WD)") + if err != nil { + t.Fatal(err) + } + dacl, _, err := sd.DACL() + if err != nil { + t.Fatal(err) + } + if err := windows.SetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, nil, nil, dacl, nil); err != nil { + t.Fatal(err) + } + soft := CredentialFile{Path: path} + if data, err := soft.Load(context.Background()); err != nil || string(data) != "fixture" { + t.Fatalf("default read blocked: %v", err) + } + strict := CredentialFile{Path: path, StrictPermissions: true} + if _, err := strict.Load(context.Background()); err == nil { + t.Fatal("strict read accepted Everyone access") + } + if err := privatefile.Protect(path, true); err != nil { + t.Fatal(err) + } + if _, err := strict.Load(context.Background()); err != nil { + t.Fatal(err) + } +} From 101eecea33ce6822881b097e78d4cfdb558180bc Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Wed, 7 Oct 2026 20:55:03 +0800 Subject: [PATCH 16/28] fix(auth): validate gateway certificates and protocol response codes --- .../frame/auth_envelope_regression_test.go | 22 ++++++++++ internal/frame/codec.go | 9 ++-- internal/idsauth/ecnu.go | 2 +- internal/idsauth/ecnu_flow_test.go | 29 +++++++++--- internal/sdpc/client.go | 7 --- .../tunnel/auth_envelope_regression_test.go | 36 +++++++++++++++ internal/tunnel/tcp.go | 9 ++-- internal/tunnel/tls_usage_regression_test.go | 44 +++++++++++++++++++ internal/tunnel/tunnel.go | 19 ++++++-- 9 files changed, 155 insertions(+), 22 deletions(-) create mode 100644 internal/frame/auth_envelope_regression_test.go create mode 100644 internal/tunnel/auth_envelope_regression_test.go create mode 100644 internal/tunnel/tls_usage_regression_test.go diff --git a/internal/frame/auth_envelope_regression_test.go b/internal/frame/auth_envelope_regression_test.go new file mode 100644 index 0000000..d8d77d0 --- /dev/null +++ b/internal/frame/auth_envelope_regression_test.go @@ -0,0 +1,22 @@ +package frame + +import ( + "bufio" + "bytes" + "encoding/binary" + "testing" +) + +func TestTunnelAuthenticationRequiresResponseCode(t *testing.T) { + for _, body := range []string{`{}`, `null`, `{"code":null,"data":{"deviceID":"fixture"}}`} { + t.Run(body, func(t *testing.T) { + wire := []byte{Version, CmdMethodAccept, CmdSFrame, 0} + wire = binary.BigEndian.AppendUint16(wire, uint16(len(body))) + wire = append(wire, body...) + wire = append(wire, Version, 0, 0, 1, 192, 0, 2, 1, 0, 0) + if _, err := ReadTunnelAuthReply(bufio.NewReader(bytes.NewReader(wire))); err == nil { + t.Fatal("missing response code established a tunnel") + } + }) + } +} diff --git a/internal/frame/codec.go b/internal/frame/codec.go index 03cc54c..ad8e052 100644 --- a/internal/frame/codec.go +++ b/internal/frame/codec.go @@ -311,7 +311,7 @@ func ReadTunnelAuthReply(r *bufio.Reader) (*TunnelAuthReply, error) { return nil, err } var resp struct { - Code int64 `json:"code"` + Code *int64 `json:"code"` Message string `json:"message"` Data struct { DeviceID string `json:"deviceID"` @@ -320,8 +320,11 @@ func ReadTunnelAuthReply(r *bufio.Reader) (*TunnelAuthReply, error) { if err := json.Unmarshal(payload, &resp); err != nil { return nil, fmt.Errorf("tunnel auth: decode response: %w", err) } - if resp.Code != 0 { - return nil, &TunnelAuthError{Code: resp.Code, Message: resp.Message} + if resp.Code == nil { + return nil, fmt.Errorf("tunnel auth: response missing code") + } + if *resp.Code != 0 { + return nil, &TunnelAuthError{Code: *resp.Code, Message: resp.Message} } vipHead, err := readFull(r, 4) diff --git a/internal/idsauth/ecnu.go b/internal/idsauth/ecnu.go index 6904d42..b1be3a3 100644 --- a/internal/idsauth/ecnu.go +++ b/internal/idsauth/ecnu.go @@ -253,7 +253,7 @@ func (c *ecnuClient) Login(ctx context.Context) error { return errors.New("invalid SSO finish URL") } target := base.ResolveReference(ref) - if target.Scheme != base.Scheme || target.Host != base.Host || target.User != nil || target.Fragment != "" { + if !httporigin.Same(target, base) || target.Fragment != "" { return errors.New("SSO finish URL outside credential origin") } assertion, count, err := buildAssertion(options, c.Keystore, c.Origin) diff --git a/internal/idsauth/ecnu_flow_test.go b/internal/idsauth/ecnu_flow_test.go index df2c954..340a2f1 100644 --- a/internal/idsauth/ecnu_flow_test.go +++ b/internal/idsauth/ecnu_flow_test.go @@ -26,13 +26,15 @@ func TestECNUFlow(t *testing.T) { } script := pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: der}) for _, tc := range []struct { - name string - failSave bool - suffix string + name string + failSave bool + suffix string + defaultPort bool }{ {name: "storage_failure_false"}, {name: "storage_failure_true", failSave: true}, {name: "trailing_slash", suffix: "/"}, + {name: "finish_default_https_port", defaultPort: true}, } { t.Run(tc.name, func(t *testing.T) { persisted, submitted := false, false @@ -57,7 +59,11 @@ func TestECNUFlow(t *testing.T) { options := challengeOptions() options["rpId"] = u.Hostname() options["allowCredentials"] = []any{map[string]any{"id": "cred-id-b64url", "type": "public-key"}} - json.NewEncoder(w).Encode(map[string]any{"success": true, "request": map[string]any{"requestId": "test-request", "publicKeyCredentialRequestOptions": options}, "actions": map[string]string{"finish": "/finish"}}) + finish := "/finish" + if tc.defaultPort { + finish = origin + ":443/finish" + } + json.NewEncoder(w).Encode(map[string]any{"success": true, "request": map[string]any{"requestId": "test-request", "publicKeyCredentialRequestOptions": options}, "actions": map[string]string{"finish": finish}}) case "/finish": submitted = true if !persisted { @@ -73,6 +79,19 @@ func TestECNUFlow(t *testing.T) { })) defer server.Close() origin = server.URL + hc := server.Client() + if tc.defaultPort { + actual, _ := url.Parse(server.URL) + origin = "https://" + actual.Hostname() + transport := hc.Transport + hc.Transport = identityTransportFunc(func(r *http.Request) (*http.Response, error) { + request := r.Clone(r.Context()) + endpoint := *r.URL + endpoint.Host = actual.Host + request.URL = &endpoint + return transport.RoundTrip(request) + }) + } u, _ := url.Parse(origin) fields := testKeystoreMap(t) fields["base_url"], fields["rp_id"] = origin+tc.suffix, u.Hostname() @@ -96,7 +115,7 @@ func TestECNUFlow(t *testing.T) { if err != nil { t.Fatal(err) } - err = NewClient(store, server.Client()).Login(context.Background()) + err = NewClient(store, hc).Login(context.Background()) if tc.failSave { if err == nil || submitted { t.Fatal("failed persistence did not stop authentication") diff --git a/internal/sdpc/client.go b/internal/sdpc/client.go index 33d011e..9b70339 100644 --- a/internal/sdpc/client.go +++ b/internal/sdpc/client.go @@ -239,10 +239,3 @@ func parseEnvelopeInto(raw []byte, op string, out any) error { } return nil } - -func truncate(b []byte, n int) string { - if len(b) > n { - b = b[:n] - } - return string(b) -} diff --git a/internal/tunnel/auth_envelope_regression_test.go b/internal/tunnel/auth_envelope_regression_test.go new file mode 100644 index 0000000..ed89584 --- /dev/null +++ b/internal/tunnel/auth_envelope_regression_test.go @@ -0,0 +1,36 @@ +package tunnel + +import ( + "bytes" + "encoding/binary" + "io" + "log/slog" + "testing" +) + +func TestTCPAuthenticationRequiresResponseCode(t *testing.T) { + for _, body := range []string{`{}`, `null`, `{"code":null}`} { + t.Run(body, func(t *testing.T) { + wire := binary.BigEndian.AppendUint16(nil, uint16(len(body))) + wire = append(wire, body...) + if err := readTCPProtocolResponse(bytes.NewReader(wire)); err == nil { + t.Fatal("missing response code accepted TCP authentication") + } + }) + } +} + +func TestFlowAuthenticationRequiresResponseCode(t *testing.T) { + for _, body := range []string{`{"data":{"conntrackHash":1,"connectToken":"fixture"}}`, `{"code":null,"data":{"conntrackHash":1,"connectToken":"fixture"}}`} { + t.Run(body, func(t *testing.T) { + result := make(chan authResult, 1) + tun := &Tunnel{pending: map[uint64]chan authResult{1: result}, logger: slog.New(slog.NewTextHandler(io.Discard, nil))} + tun.handleAuthResponse([]byte(body)) + select { + case <-result: + t.Fatal("missing response code authorized a flow") + default: + } + }) + } +} diff --git a/internal/tunnel/tcp.go b/internal/tunnel/tcp.go index 807983c..fd82c2e 100644 --- a/internal/tunnel/tcp.go +++ b/internal/tunnel/tcp.go @@ -369,14 +369,17 @@ func parseTCPProtocolResponse(body []byte) error { return nil } var response struct { - Code int64 `json:"code"` + Code *int64 `json:"code"` Message string `json:"message"` } if err := json.Unmarshal(body, &response); err != nil { return fmt.Errorf("decode direct TCP protocol response: %w", err) } - if response.Code != 0 { - return &TCPAuthError{Code: response.Code} + if response.Code == nil { + return errors.New("direct TCP protocol response missing code") + } + if *response.Code != 0 { + return &TCPAuthError{Code: *response.Code} } return nil } diff --git a/internal/tunnel/tls_usage_regression_test.go b/internal/tunnel/tls_usage_regression_test.go new file mode 100644 index 0000000..f887f6b --- /dev/null +++ b/internal/tunnel/tls_usage_regression_test.go @@ -0,0 +1,44 @@ +package tunnel + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "math/big" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestTOFURejectsCertificateRestrictedToClientAuthentication(t *testing.T) { + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + template := &x509.Certificate{SerialNumber: big.NewInt(1), NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}} + der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + server := httptest.NewUnstartedServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + server.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}}} + server.StartTLS() + defer server.Close() + pins := &testPinStore{pins: map[string][]byte{}} + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + conn, err := probeGatewayTLSWithDialer(ctx, strings.TrimPrefix(server.URL, "https://"), nil, nil, pins) + if err == nil { + conn.Close() + t.Fatal("client-auth-only certificate was accepted as a gateway server") + } + if len(pins.pins) != 0 { + t.Fatal("invalid server certificate enrolled a gateway pin") + } +} diff --git a/internal/tunnel/tunnel.go b/internal/tunnel/tunnel.go index 9edd641..ad93d36 100644 --- a/internal/tunnel/tunnel.go +++ b/internal/tunnel/tunnel.go @@ -162,6 +162,15 @@ func gatewayTLSConfigWithTrust(ctx context.Context, addr string, template *tls.C return verifyErr } leaf := cs.PeerCertificates[0] + if verifyErr != nil { + // The pin replaces CA trust, not the certificate's server usage or + // chain constraints. Check those against the supplied chain anchor. + fallbackRoots := x509.NewCertPool() + fallbackRoots.AddCert(cs.PeerCertificates[len(cs.PeerCertificates)-1]) + if _, err := leaf.Verify(x509.VerifyOptions{DNSName: cfg.ServerName, Roots: fallbackRoots, Intermediates: intermediates, CurrentTime: now}); err != nil { + return err + } + } // Controllers may advertise gateway IPs whose private-CA certificates // contain DNS names only. The saved key is bound to the advertised IP:port. if cfg.ServerName != "" { @@ -544,7 +553,7 @@ func (t *Tunnel) readLoop() { func (t *Tunnel) handleAuthResponse(payload []byte) { var parsed struct { - Code int64 `json:"code"` + Code *int64 `json:"code"` Message string `json:"message"` Data struct { ConnectToken string `json:"connectToken"` @@ -556,12 +565,16 @@ func (t *Tunnel) handleAuthResponse(payload []byte) { t.logger.Warn("tunnel: bad auth response", "err", err) return } + if parsed.Code == nil { + t.logger.Warn("tunnel: auth response missing code") + return + } token := parsed.Data.ConnectToken if token == "" { token = parsed.Data.Token } resp := authResult{resp: AuthResponse{ - Code: parsed.Code, + Code: *parsed.Code, Message: parsed.Message, ConnectToken: token, }} @@ -576,7 +589,7 @@ func (t *Tunnel) handleAuthResponse(payload []byte) { t.pendingMu.Unlock() if !ok { t.logger.Debug("tunnel: auth response without pending request", - "conntrack", parsed.Data.ConntrackHash, "code", parsed.Code) + "conntrack", parsed.Data.ConntrackHash, "code", *parsed.Code) return } ch <- resp // buffered slot, requester has not received yet: never blocks From 81a991e1a2ef0845e2c52808a146e2c978c8cd7b Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Wed, 7 Oct 2026 20:55:14 +0800 Subject: [PATCH 17/28] fix(runtime): validate tunnel endpoints and support custom default transports --- internal/config/config.go | 10 ++++--- .../network_validation_regression_test.go | 21 +++++++++++++++ internal/runtime/options_test.go | 26 +++++++++++++++++++ internal/runtime/runtime.go | 17 +++++++----- 4 files changed, 64 insertions(+), 10 deletions(-) create mode 100644 internal/config/network_validation_regression_test.go diff --git a/internal/config/config.go b/internal/config/config.go index a1d8412..49f301b 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -192,12 +192,16 @@ func (c *Config) validate() error { if err != nil { return fmt.Errorf("gateway %q: %w", gw, err) } + n, err := strconv.Atoi(port) + if err != nil || n < 1 || n > 65535 || host == "" || strings.ContainsAny(host, "/\\@?# \t\r\n") { + return fmt.Errorf("gateway %q must be a valid host:port", gw) + } // Normalize so downstream dialers always get host:port. - c.Gateways[i] = net.JoinHostPort(host, port) + c.Gateways[i] = net.JoinHostPort(host, strconv.Itoa(n)) } for _, d := range c.DNS { - if net.ParseIP(d) == nil { - return fmt.Errorf("dns entry %q is not an IP address", d) + if net.ParseIP(d).To4() == nil { + return fmt.Errorf("dns entry %q must be an IPv4 address", d) } } for name, l := range map[string]Listener{"inbound.socks5": c.Inbound.SOCKS5, "inbound.http": c.Inbound.HTTP} { diff --git a/internal/config/network_validation_regression_test.go b/internal/config/network_validation_regression_test.go new file mode 100644 index 0000000..66cddac --- /dev/null +++ b/internal/config/network_validation_regression_test.go @@ -0,0 +1,21 @@ +package config + +import ( + "os" + "path/filepath" + "testing" +) + +func TestLegacyConfigRejectsUnusableGatewayAndTunnelDNS(t *testing.T) { + for _, extra := range []string{`gateways=["gateway.example:abc"]`, `gateways=[":441"]`, `dns=["2001:db8::53"]`} { + t.Run(extra, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.toml") + if err := os.WriteFile(path, []byte("keystore='fixture'\n"+extra+"\n"), 0600); err != nil { + t.Fatal(err) + } + if _, err := Load(path); err == nil { + t.Fatal("unusable gateway or tunnel DNS accepted") + } + }) + } +} diff --git a/internal/runtime/options_test.go b/internal/runtime/options_test.go index 96263aa..359bc6f 100644 --- a/internal/runtime/options_test.go +++ b/internal/runtime/options_test.go @@ -40,6 +40,32 @@ func (f identityFunc) Info(context.Context) (auth.IdentityInfo, error) { func (f identityFunc) Authenticate(c context.Context, h *http.Client, r auth.IdentityRequest) error { return f(c, h, r) } + +func TestCustomDefaultHTTPTransportCanRestoreSession(t *testing.T) { + previous := http.DefaultTransport + http.DefaultTransport = fixtureTransport{} + defer func() { http.DefaultTransport = previous }() + opts := contractOptions(&contractIdentity{subject: "account"}, &contractStore{state: validState()}) + opts.Network.ControlTransport = nil + c, err := New(opts) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if _, err := c.Connect(context.Background()); err != nil { + t.Fatal(err) + } +} + +func TestOptionsRejectIPv6TunnelDNS(t *testing.T) { + opts := contractOptions(&contractIdentity{subject: "account"}, &contractStore{}) + opts.DNS.Servers = []netip.Addr{netip.MustParseAddr("2001:db8::53")} + if c, err := New(opts); err == nil { + c.Close() + t.Fatal("IPv6-only tunnel DNS accepted by the IPv4 data plane") + } +} + func TestOptionsCopiedAndProfileDefaults(t *testing.T) { s := validState() s.LoginDomain = "custom-domain" diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index 22be0ba..624e984 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -147,10 +147,10 @@ func New(opts Options) (*Runtime, error) { if opts.DNS.Servers != nil { cfg.DNS = make([]string, len(opts.DNS.Servers)) for i, x := range opts.DNS.Servers { - if !x.IsValid() { - return nil, errors.New("invalid DNS address") + if !x.Unmap().Is4() { + return nil, errors.New("tunnel DNS requires an IPv4 address") } - cfg.DNS[i] = x.String() + cfg.DNS[i] = x.Unmap().String() } } mapDomains := resolved.Profile == compatibility.ShanghaiTech @@ -160,11 +160,14 @@ func New(opts Options) (*Runtime, error) { p.Transport = opts.Network.ControlTransport var owned *http.Transport if p.Transport == nil { - owned = http.DefaultTransport.(*http.Transport).Clone() - if opts.Network.DialContext != nil { - owned.DialContext = opts.Network.DialContext + p.Transport = http.DefaultTransport + if transport, ok := http.DefaultTransport.(*http.Transport); ok { + owned = transport.Clone() + if opts.Network.DialContext != nil { + owned.DialContext = opts.Network.DialContext + } + p.Transport = owned } - p.Transport = owned } p.HTTPTimeout = opts.Network.HTTPTimeout m := tunnel.NewManager(p, opts.Logger) From 613e8e850c03dd018eeb78105bf40bc87e74e576 Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Wed, 7 Oct 2026 20:55:17 +0800 Subject: [PATCH 18/28] fix(cli): reject overlapping private file paths before startup --- cmd/geektrust/config_cmd.go | 3 ++ cmd/geektrust/init_cmd.go | 15 +++---- cmd/geektrust/main.go | 4 ++ cmd/geektrust/main_test.go | 12 +++--- .../private_paths_regression_test.go | 39 +++++++++++++++++++ 5 files changed, 58 insertions(+), 15 deletions(-) create mode 100644 cmd/geektrust/private_paths_regression_test.go diff --git a/cmd/geektrust/config_cmd.go b/cmd/geektrust/config_cmd.go index 0eba013..9b1f38f 100644 --- a/cmd/geektrust/config_cmd.go +++ b/cmd/geektrust/config_cmd.go @@ -23,6 +23,9 @@ func cmdConfig(path string, args []string) error { return e } if args[0] == "check" { + if _, e := validatePrivatePaths(path, c); e != nil { + return e + } if e = c.ValidateListeners(); e != nil { return e } diff --git a/cmd/geektrust/init_cmd.go b/cmd/geektrust/init_cmd.go index 7d7d7f3..483f2e9 100644 --- a/cmd/geektrust/init_cmd.go +++ b/cmd/geektrust/init_cmd.go @@ -22,26 +22,23 @@ type initPath struct { path string } -func validateInitPaths(configPath string, cfg *config.Config) (string, error) { +func validatePrivatePaths(configPath string, cfg *config.Config) (string, error) { paths := []initPath{ {name: "config", path: configPath}, {name: "keystore", path: cfg.Keystore}, {name: "state_file", path: cfg.StateFile}, {name: "state key", path: cfg.StateFile + ".key"}, } + if cfg.Directory != "" { + paths = append(paths, initPath{name: "device identity", path: filepath.Join(cfg.Directory, "device_id")}) + } resolved := make([]string, len(paths)) - lexical := make([]string, len(paths)) infos := make([]os.FileInfo, len(paths)) for i, item := range paths { if item.path == "" { return "", fmt.Errorf("%s path is required", item.name) } - var err error - lexical[i], err = filepath.Abs(filepath.Clean(item.path)) - if err != nil { - return "", fmt.Errorf("resolve lexical %s path: %w", item.name, err) - } var infoErr error resolved[i], infos[i], infoErr = resolveInitPath(item.path) if infoErr != nil { @@ -224,7 +221,7 @@ func cmdInit(ctx context.Context, configPath string, args []string) error { if err != nil { return err } - resolvedConfigPath, err := validateInitPaths(configPath, prepared) + resolvedConfigPath, err := validatePrivatePaths(configPath, prepared) if err != nil { return err } @@ -259,7 +256,7 @@ func cmdInit(ctx context.Context, configPath string, args []string) error { } // The binder may have created a symlink or hard link. Re-evaluate path // identity before writing the config. - resolvedConfigPath, err = validateInitPaths(configPath, prepared) + resolvedConfigPath, err = validatePrivatePaths(configPath, prepared) if err != nil { return err } diff --git a/cmd/geektrust/main.go b/cmd/geektrust/main.go index 3361bc9..c42deae 100644 --- a/cmd/geektrust/main.go +++ b/cmd/geektrust/main.go @@ -84,6 +84,10 @@ func main() { fmt.Fprintln(os.Stderr, "geektrust:", err) os.Exit(1) } + if _, err := validatePrivatePaths(configPath, cfg); err != nil { + fmt.Fprintln(os.Stderr, "geektrust:", err) + os.Exit(1) + } if cfg.Version == 1 { fmt.Fprintf(os.Stderr, "Warning: using a deprecated config (version 1). Run geektrust -config %q config migrate to preview the new format, then add --write to migrate.\n", configPath) } diff --git a/cmd/geektrust/main_test.go b/cmd/geektrust/main_test.go index 8a62c41..1f303ff 100644 --- a/cmd/geektrust/main_test.go +++ b/cmd/geektrust/main_test.go @@ -156,7 +156,7 @@ func TestValidateInitPaths(t *testing.T) { Keystore: filepath.Join(dir, "synthetic.keystore"), StateFile: filepath.Join(dir, "synthetic-state.enc"), } - if _, err := validateInitPaths(filepath.Join(dir, "config.toml"), safe); err != nil { + if _, err := validatePrivatePaths(filepath.Join(dir, "config.toml"), safe); err != nil { t.Fatalf("safe paths rejected: %v", err) } @@ -199,7 +199,7 @@ func TestValidateInitPaths(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - _, err := validateInitPaths(tt.configPath, &config.Config{ + _, err := validatePrivatePaths(tt.configPath, &config.Config{ Keystore: tt.keystore, StateFile: tt.stateFile, }) @@ -218,7 +218,7 @@ func TestValidateInitPaths(t *testing.T) { if err := os.Link(first, second); err != nil { t.Fatal(err) } - _, err := validateInitPaths(first, &config.Config{ + _, err := validatePrivatePaths(first, &config.Config{ Keystore: second, StateFile: filepath.Join(dir, "hardlink-state"), }) @@ -244,7 +244,7 @@ func TestValidateInitPaths(t *testing.T) { } } defer os.Remove(linkDir) - _, err := validateInitPaths( + _, err := validatePrivatePaths( filepath.Join(linkDir, "future"), &config.Config{ Keystore: filepath.Join(realDir, "future"), @@ -271,7 +271,7 @@ func TestValidateInitPaths(t *testing.T) { if err := os.Mkdir(privateChild, 0o700); err != nil { t.Fatal(err) } - _, err := validateInitPaths( + _, err := validatePrivatePaths( filepath.Join(privateChild, "config.toml"), &config.Config{ Keystore: filepath.Join(dir, "sticky-key"), @@ -288,7 +288,7 @@ func TestValidateInitPaths(t *testing.T) { if err := os.Mkdir(stateDir, 0o700); err != nil { t.Fatal(err) } - _, err := validateInitPaths( + _, err := validatePrivatePaths( filepath.Join(dir, "state-directory-config"), &config.Config{ Keystore: filepath.Join(dir, "state-directory-key"), diff --git a/cmd/geektrust/private_paths_regression_test.go b/cmd/geektrust/private_paths_regression_test.go new file mode 100644 index 0000000..ec372dc --- /dev/null +++ b/cmd/geektrust/private_paths_regression_test.go @@ -0,0 +1,39 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" + "testing" +) + +func TestConfigCheckRejectsPrivateFileOverlap(t *testing.T) { + for _, collision := range []string{"credential", "credential-key", "configuration", "device-identity"} { + t.Run(collision, func(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "config.toml") + credential, state := "credential", "session.enc" + switch collision { + case "credential": + state = credential + case "credential-key": + credential = state + ".key" + case "configuration": + state = "config.toml" + case "device-identity": + state = "store/device_id" + } + data := fmt.Sprintf("config_version=2\n[auth]\ndevice_id='0123456789ABCDEF0123456789ABCDEF'\n[auth.passkey]\nkeystore=%q\n[storage]\ndirectory='store'\nstate_file=%q\n", credential, state) + if err := os.WriteFile(path, []byte(data), 0600); err != nil { + t.Fatal(err) + } + if err := cmdConfig(path, []string{"check"}); err == nil { + t.Fatal("configuration check accepted overlapping private files") + } + after, err := os.ReadFile(path) + if err != nil || string(after) != data { + t.Fatal("configuration check changed the file") + } + }) + } +} From 1be1bda0475d1be322a11bb3a935590db3df8e94 Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Wed, 7 Oct 2026 20:55:21 +0800 Subject: [PATCH 19/28] fix(web): restore keyboard focus after controlled dialogs close --- web/src/components/dialogs.test.tsx | 54 ++++++++++++++++++++++++++ web/src/components/ui/alert-dialog.tsx | 22 +++++++++++ web/src/components/ui/dialog.tsx | 22 +++++++++++ 3 files changed, 98 insertions(+) create mode 100644 web/src/components/dialogs.test.tsx diff --git a/web/src/components/dialogs.test.tsx b/web/src/components/dialogs.test.tsx new file mode 100644 index 0000000..76feb8e --- /dev/null +++ b/web/src/components/dialogs.test.tsx @@ -0,0 +1,54 @@ +import { useState } from "react"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { expect, it, vi } from "vitest"; +import { Button } from "./ui/button"; +import { ConfirmDialog } from "./ConfirmDialog"; +import { EventsList } from "./EventsList"; + +it("returns keyboard focus to the activity button after Escape", async () => { + render( + , + ); + const trigger = screen.getByRole("button", { name: "查看全部" }); + trigger.focus(); + fireEvent.click(trigger); + const dialog = await screen.findByRole("dialog"); + fireEvent.keyDown(dialog, { key: "Escape" }); + await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull()); + await waitFor(() => expect(document.activeElement).toBe(trigger)); +}); + +it("cancels a destructive confirmation without acting and restores focus", async () => { + const confirm = vi.fn(); + function Example() { + const [open, setOpen] = useState(false); + return ( + <> + + + + ); + } + render(); + const trigger = screen.getByRole("button", { name: "注销本机" }); + trigger.focus(); + fireEvent.click(trigger); + await screen.findByRole("alertdialog"); + fireEvent.click(screen.getByRole("button", { name: "取消" })); + await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull()); + expect(confirm).not.toHaveBeenCalled(); + await waitFor(() => expect(document.activeElement).toBe(trigger)); +}); diff --git a/web/src/components/ui/alert-dialog.tsx b/web/src/components/ui/alert-dialog.tsx index 05560c6..7ffd726 100644 --- a/web/src/components/ui/alert-dialog.tsx +++ b/web/src/components/ui/alert-dialog.tsx @@ -47,14 +47,36 @@ function AlertDialogOverlay({ function AlertDialogContent({ className, size = "default", + onOpenAutoFocus, + onCloseAutoFocus, ...props }: React.ComponentProps & { size?: "default" | "sm"; }) { + const previousFocus = React.useRef(null); return ( { + previousFocus.current = + document.activeElement instanceof HTMLElement + ? document.activeElement + : null; + onOpenAutoFocus?.(event); + }} + onCloseAutoFocus={(event) => { + onCloseAutoFocus?.(event); + const target = previousFocus.current; + if ( + !event.defaultPrevented && + target?.isConnected && + !target.matches(":disabled") + ) { + event.preventDefault(); + target.focus(); + } + }} data-slot="alert-dialog-content" data-size={size} className={cn( diff --git a/web/src/components/ui/dialog.tsx b/web/src/components/ui/dialog.tsx index a9f8da9..2b65ef4 100644 --- a/web/src/components/ui/dialog.tsx +++ b/web/src/components/ui/dialog.tsx @@ -49,14 +49,36 @@ function DialogContent({ className, children, showCloseButton = true, + onOpenAutoFocus, + onCloseAutoFocus, ...props }: React.ComponentProps & { showCloseButton?: boolean; }) { + const previousFocus = React.useRef(null); return ( { + previousFocus.current = + document.activeElement instanceof HTMLElement + ? document.activeElement + : null; + onOpenAutoFocus?.(event); + }} + onCloseAutoFocus={(event) => { + onCloseAutoFocus?.(event); + const target = previousFocus.current; + if ( + !event.defaultPrevented && + target?.isConnected && + !target.matches(":disabled") + ) { + event.preventDefault(); + target.focus(); + } + }} data-slot="dialog-content" className={cn( "fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-6 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-[480px] data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", From 40a61bc421c51ca53824268b948cfe77d2201dde Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Wed, 7 Oct 2026 23:03:26 +0800 Subject: [PATCH 20/28] fix(session): keep rejected caches disabled after failed reauthentication --- .../session/force_login_regression_test.go | 36 +++++++++++++++++++ internal/session/provider.go | 12 ++++--- 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/internal/session/force_login_regression_test.go b/internal/session/force_login_regression_test.go index 77cdd41..416635d 100644 --- a/internal/session/force_login_regression_test.go +++ b/internal/session/force_login_regression_test.go @@ -23,6 +23,42 @@ func TestCancelledForceLoginKeepsCurrentSession(t *testing.T) { } } +func TestRejectedSessionIsNotRestoredAfterFailedLogin(t *testing.T) { + for _, forced := range []bool{false, true} { + t.Run(map[bool]string{false: "invalidated", true: "forced"}[forced], func(t *testing.T) { + p := newRestoreFixture(t, restoreHandler) + ctx := context.Background() + current, err := p.Credential(ctx) + if err != nil { + t.Fatal(err) + } + rejected := errors.New("fixture identity unavailable") + var attempts atomic.Int32 + p.Authenticate = func(context.Context, *http.Client) (string, error) { + attempts.Add(1) + return "", rejected + } + if forced { + _, err = p.ForceLogin(ctx) + } else { + if !p.InvalidateIfCurrent(current) { + t.Fatal("current session was not invalidated") + } + _, err = p.Credential(ctx) + } + if !errors.Is(err, rejected) { + t.Fatalf("first login = %v", err) + } + if _, err = p.Credential(ctx); !errors.Is(err, rejected) { + t.Fatalf("rejected cached session was restored after failed login: %v", err) + } + if attempts.Load() != 2 { + t.Fatalf("authentication attempts = %d, want 2", attempts.Load()) + } + }) + } +} + func TestConcurrentForceLoginSharesAuthentication(t *testing.T) { p := failingProvider(t) entered, release := make(chan struct{}), make(chan struct{}) diff --git a/internal/session/provider.go b/internal/session/provider.go index 6f6c095..d28a9bd 100644 --- a/internal/session/provider.go +++ b/internal/session/provider.go @@ -91,7 +91,7 @@ type Provider struct { revision uint64 cancelSession context.CancelFunc closed bool - forceLogin bool // set by Invalidate; skips restore on the next refresh + forceLogin bool // rejected caches stay disabled until a new session is published dispMu sync.Mutex dispCond *sync.Cond // lazily created on first AddObserver @@ -271,6 +271,7 @@ func (p *Provider) finishRefresh(call *refreshCall, cred *Credential, session *S err = call.leader.Err() } if err == nil { + p.forceLogin = false if p.cancelSession != nil { p.cancelSession() } @@ -465,8 +466,7 @@ func (p *Provider) CheckLoop(ctx context.Context, interval time.Duration) { // acquire restores the persisted session or performs a full login. force // (relogin reservation) skips restore regardless of the global flag. After -// Invalidate, the restore step is skipped once: the persisted session is -// the one the caller rejected. +// Invalidate, the persisted session stays disabled until a new login succeeds. func (p *Provider) acquire(ctx context.Context, force bool) (*Credential, *SessionInfo, bool, error) { if err := ctx.Err(); err != nil { return nil, nil, false, err @@ -476,8 +476,10 @@ func (p *Provider) acquire(ctx context.Context, force bool) (*Credential, *Sessi p.mu.Unlock() return nil, nil, false, err } - skipRestore := force || p.forceLogin - p.forceLogin = false + if force { + p.forceLogin = true + } + skipRestore := p.forceLogin p.mu.Unlock() if !skipRestore { From 1a6e233e64b3e98e879d80bc9681788fb93aab31 Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Wed, 7 Oct 2026 23:03:30 +0800 Subject: [PATCH 21/28] fix(cli): retain SMS input received before the prompt starts waiting --- cmd/geektrust/main.go | 66 +++++++++++++---- cmd/geektrust/sms_input_regression_test.go | 86 ++++++++++++++++++++++ 2 files changed, 139 insertions(+), 13 deletions(-) create mode 100644 cmd/geektrust/sms_input_regression_test.go diff --git a/cmd/geektrust/main.go b/cmd/geektrust/main.go index c42deae..1d3d3fc 100644 --- a/cmd/geektrust/main.go +++ b/cmd/geektrust/main.go @@ -10,6 +10,7 @@ import ( "errors" "flag" "fmt" + "io" "log/slog" "net" "net/http" @@ -308,31 +309,70 @@ func printSummary(cred *session.Credential) { len(cred.Policy.DomainRules), len(cred.Policy.SuffixRules), len(cred.Policy.IPRules), len(apps)) } -// smsPrompt reads the SMS code from stdin whenever the controller demands it. -var terminalInput struct { - once sync.Once - lines chan string +// terminalCodeInput keeps one reader and buffers the active prompt's first code. +type terminalCodeInput struct { + once sync.Once + mu sync.Mutex + lines chan string + closed bool } +var terminalInput terminalCodeInput + +// smsPrompt reads the SMS code from stdin whenever the controller demands it. func smsPrompt(ctx context.Context) (string, error) { - terminalInput.once.Do(func() { - terminalInput.lines = make(chan string) + return terminalInput.prompt(ctx, os.Stdin, os.Stderr) +} + +func (t *terminalCodeInput) prompt(ctx context.Context, input io.Reader, output io.Writer) (string, error) { + if err := ctx.Err(); err != nil { + return "", err + } + lines := make(chan string, 1) + t.mu.Lock() + if t.closed { + t.mu.Unlock() + return "", errors.New("no verification code provided") + } + if t.lines != nil { + t.mu.Unlock() + return "", errors.New("verification input already pending") + } + t.lines = lines + t.mu.Unlock() + defer func() { + t.mu.Lock() + t.lines = nil + t.mu.Unlock() + }() + t.once.Do(func() { go func() { - defer close(terminalInput.lines) - scan := bufio.NewScanner(os.Stdin) + defer func() { + t.mu.Lock() + t.closed = true + if t.lines != nil { + close(t.lines) + } + t.mu.Unlock() + }() + scan := bufio.NewScanner(input) for scan.Scan() { - select { - case terminalInput.lines <- strings.TrimSpace(scan.Text()): - default: + t.mu.Lock() + if t.lines != nil { + select { + case t.lines <- strings.TrimSpace(scan.Text()): + default: + } } + t.mu.Unlock() } }() }) - fmt.Fprintln(os.Stderr, "The controller requires SMS verification; enter the 6-digit code:") + fmt.Fprintln(output, "The controller requires SMS verification; enter the 6-digit code:") select { case <-ctx.Done(): return "", ctx.Err() - case code, ok := <-terminalInput.lines: + case code, ok := <-lines: if !ok || code == "" { return "", errors.New("no verification code provided") } diff --git a/cmd/geektrust/sms_input_regression_test.go b/cmd/geektrust/sms_input_regression_test.go new file mode 100644 index 0000000..e1b1397 --- /dev/null +++ b/cmd/geektrust/sms_input_regression_test.go @@ -0,0 +1,86 @@ +package main + +import ( + "context" + "errors" + "io" + "strings" + "testing" + "time" +) + +type noticeEOF struct { + io.Reader + done chan struct{} +} + +func (r noticeEOF) Read(b []byte) (int, error) { + n, err := r.Reader.Read(b) + if err == io.EOF { + close(r.done) + } + return n, err +} + +type blockedPromptOutput struct { + entered chan struct{} + release chan struct{} +} + +func (w blockedPromptOutput) Write(b []byte) (int, error) { + close(w.entered) + <-w.release + return len(b), nil +} + +func TestTerminalSMSKeepsCodeReceivedWhilePrintingPrompt(t *testing.T) { + input, writer := io.Pipe() + defer input.Close() + defer writer.Close() + eof := make(chan struct{}) + output := blockedPromptOutput{make(chan struct{}), make(chan struct{})} + defer func() { + select { + case <-output.release: + default: + close(output.release) + } + }() + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + result := make(chan string, 1) + prompt := &terminalCodeInput{} + go func() { + code, err := prompt.prompt(ctx, noticeEOF{input, eof}, output) + if err != nil { + code = "error: " + err.Error() + } + result <- code + }() + <-output.entered + if _, err := writer.Write([]byte("123456\n")); err != nil { + t.Fatal(err) + } + writer.Close() + <-eof + close(output.release) + if code := <-result; code != "123456" { + t.Fatalf("early SMS code lost: %s", code) + } +} + +func TestCancelledTerminalSMSDoesNotConsumeTheNextCode(t *testing.T) { + prompt := &terminalCodeInput{} + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := prompt.prompt(ctx, strings.NewReader("old input\n"), io.Discard); !errors.Is(err, context.Canceled) { + t.Fatalf("cancelled prompt = %v", err) + } + code, err := prompt.prompt(context.Background(), strings.NewReader("654321\n"), io.Discard) + if err != nil || code != "654321" { + t.Fatalf("next prompt = %q, %v", code, err) + } + if _, err := prompt.prompt(context.Background(), strings.NewReader(""), io.Discard); err == nil { + t.Fatal("closed input did not report EOF") + } +} From 77a5636faf46c60fabb84a6e85f379cc13c1582c Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Wed, 7 Oct 2026 23:07:54 +0800 Subject: [PATCH 22/28] fix(cli): reject extra login arguments before creating local identity --- cmd/geektrust/login_args_regression_test.go | 27 +++++++++++++++++++++ cmd/geektrust/main.go | 3 +++ 2 files changed, 30 insertions(+) create mode 100644 cmd/geektrust/login_args_regression_test.go diff --git a/cmd/geektrust/login_args_regression_test.go b/cmd/geektrust/login_args_regression_test.go new file mode 100644 index 0000000..4171fb1 --- /dev/null +++ b/cmd/geektrust/login_args_regression_test.go @@ -0,0 +1,27 @@ +package main + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/ShanghaitechGeekPie/geektrust/internal/config" +) + +func TestLoginRejectsExtraArgumentsBeforeCreatingIdentity(t *testing.T) { + for _, args := range [][]string{{"unexpected"}, {"-fresh", "unexpected"}} { + t.Run(strings.Join(args, " "), func(t *testing.T) { + dir := t.TempDir() + cfg := &config.Config{Version: 2, Directory: dir, BaseURL: "https://controller.example", Keystore: filepath.Join(dir, "missing.keystore"), StateFile: filepath.Join(dir, "session.enc")} + err := cmdLogin(context.Background(), cfg, newLogger("error"), args) + if err == nil || !strings.Contains(err.Error(), "usage:") { + t.Fatalf("extra login arguments = %v, want a usage error", err) + } + if _, err := os.Stat(filepath.Join(dir, "device_id")); !os.IsNotExist(err) { + t.Fatal("invalid login arguments created a device identity") + } + }) + } +} diff --git a/cmd/geektrust/main.go b/cmd/geektrust/main.go index 1d3d3fc..cb06edd 100644 --- a/cmd/geektrust/main.go +++ b/cmd/geektrust/main.go @@ -141,6 +141,9 @@ func cmdLogin(ctx context.Context, cfg *config.Config, logger *slog.Logger, args fs := flag.NewFlagSet("login", flag.ExitOnError) fresh := fs.Bool("fresh", false, "force a full login even if the persisted session is still online") fs.Parse(args) + if fs.NArg() != 0 { + return errors.New("usage: geektrust login [-fresh]") + } c, err := commandClient(cfg, logger) if err != nil { From de63737bed9d268dc8875df44b4591217edef5a7 Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Wed, 7 Oct 2026 23:33:36 +0800 Subject: [PATCH 23/28] fix(cli): detect wildcard proxy conflicts with the web panel --- .../listener_wildcard_regression_test.go | 23 +++++++++++++++++++ cmd/geektrust/main.go | 2 +- 2 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 cmd/geektrust/listener_wildcard_regression_test.go diff --git a/cmd/geektrust/listener_wildcard_regression_test.go b/cmd/geektrust/listener_wildcard_regression_test.go new file mode 100644 index 0000000..aee4f63 --- /dev/null +++ b/cmd/geektrust/listener_wildcard_regression_test.go @@ -0,0 +1,23 @@ +package main + +import ( + "testing" + + "github.com/ShanghaitechGeekPie/geektrust/internal/config" +) + +func TestWebListenConflictWithEmptyProxyHost(t *testing.T) { + for _, web := range []string{"127.0.0.1:8081", "[::1]:8081", "localhost:8081"} { + t.Run(web, func(t *testing.T) { + cfg := &config.Config{Web: config.WebConfig{Listen: web}} + cfg.Inbound.HTTP = config.Listener{Enabled: true, Listen: ":8081"} + if !webListenConflict(cfg) { + t.Fatal("panel must yield its port to a wildcard proxy listener") + } + cfg.Inbound.HTTP.Listen = ":8082" + if webListenConflict(cfg) { + t.Fatal("different ports must not conflict") + } + }) + } +} diff --git a/cmd/geektrust/main.go b/cmd/geektrust/main.go index cb06edd..f69149c 100644 --- a/cmd/geektrust/main.go +++ b/cmd/geektrust/main.go @@ -256,7 +256,7 @@ func lookupPort(s string) (int, error) { } func hostsOverlap(a, b string) bool { - if a == b { + if a == b || a == "" || b == "" { return true } ipA, ipB := listenIP(a), listenIP(b) From e50e35473b7ca000e8aff5fddf23092715d04f32 Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Wed, 7 Oct 2026 23:33:36 +0800 Subject: [PATCH 24/28] fix(proxy): finish HTTP upgrade before relaying UDP datagrams --- internal/inbound/http.go | 11 ++ .../inbound/upgrade_order_regression_test.go | 119 ++++++++++++++++++ 2 files changed, 130 insertions(+) create mode 100644 internal/inbound/upgrade_order_regression_test.go diff --git a/internal/inbound/http.go b/internal/inbound/http.go index 16f65cd..e8a1a10 100644 --- a/internal/inbound/http.go +++ b/internal/inbound/http.go @@ -103,8 +103,18 @@ func (s *Server) handleHTTPConnectUDP(ctx context.Context, client net.Conn, br * return } + ctx, stop := context.WithCancel(ctx) + defer stop() + upgraded := make(chan struct{}) var writeMu sync.Mutex table := newUDPFlowTable(ctx, s, 1, func(_ udpTarget, payload []byte) error { + // A remote peer can send data as soon as the UDP flow opens. + // Capsules must wait until the HTTP upgrade response is complete. + select { + case <-upgraded: + case <-ctx.Done(): + return ctx.Err() + } writeMu.Lock() err := writeDatagramCapsule(client, payload) writeMu.Unlock() @@ -131,6 +141,7 @@ func (s *Server) handleHTTPConnectUDP(ctx context.Context, client net.Conn, br * return } _ = client.SetDeadline(time.Time{}) + close(upgraded) s.logger.Info("http CONNECT-UDP", "target", target.key()) for { diff --git a/internal/inbound/upgrade_order_regression_test.go b/internal/inbound/upgrade_order_regression_test.go new file mode 100644 index 0000000..1a53c4a --- /dev/null +++ b/internal/inbound/upgrade_order_regression_test.go @@ -0,0 +1,119 @@ +package inbound + +import ( + "bufio" + "bytes" + "context" + "io" + "log/slog" + "net" + "net/http" + "sync" + "testing" + "time" +) + +type earlyUDPDialer struct { + mockDialer + conn net.Conn +} + +func (d *earlyUDPDialer) DialUDP(context.Context, string, int, string, string) (net.Conn, error) { + return d.conn, nil +} + +type observedUDPRead struct { + net.Conn + read chan struct{} + once sync.Once +} + +func (c *observedUDPRead) Read(p []byte) (int, error) { + n, err := c.Conn.Read(p) + if n > 0 { + c.once.Do(func() { close(c.read) }) + } + return n, err +} + +type delayedUpgradeConn struct { + net.Conn + started chan struct{} + release chan struct{} +} + +func (c *delayedUpgradeConn) Write(p []byte) (int, error) { + if bytes.HasPrefix(p, []byte("HTTP/1.1 101")) { + close(c.started) + <-c.release + } + return c.Conn.Write(p) +} + +func TestConnectUDPUpgradePrecedesEarlyDatagram(t *testing.T) { + upstream, remote := net.Pipe() + defer remote.Close() + defer upstream.Close() + read := make(chan struct{}) + dialer := &earlyUDPDialer{conn: &observedUDPRead{Conn: upstream, read: read}} + s := New(testInboundCfg(), &mockResolver{}, dialer, slog.New(slog.NewTextHandler(io.Discard, nil))) + client, server := net.Pipe() + defer client.Close() + defer server.Close() + wrapped := &delayedUpgradeConn{Conn: server, started: make(chan struct{}), release: make(chan struct{})} + var release sync.Once + defer release.Do(func() { close(wrapped.release) }) + done := make(chan struct{}) + go func() { defer close(done); s.handleHTTPConnect(context.Background(), wrapped) }() + client.SetDeadline(time.Now().Add(3 * time.Second)) + if _, err := io.WriteString(client, "GET /.well-known/masque/udp/192.0.2.1/443/ HTTP/1.1\r\nHost: proxy\r\nConnection: Upgrade\r\nUpgrade: connect-udp\r\n\r\n"); err != nil { + t.Fatal(err) + } + select { + case <-wrapped.started: + case <-time.After(time.Second): + t.Fatal("upgrade response did not start") + } + go remote.Write([]byte("early")) + select { + case <-read: + case <-time.After(time.Second): + t.Fatal("upstream datagram was not read") + } + client.SetReadDeadline(time.Now().Add(100 * time.Millisecond)) + var first [1]byte + if n, err := client.Read(first[:]); n != 0 || err == nil { + t.Fatalf("UDP data preceded the HTTP upgrade: %x, %v", first[:n], err) + } + release.Do(func() { close(wrapped.release) }) + client.SetReadDeadline(time.Now().Add(time.Second)) + reader := bufio.NewReader(client) + response, err := http.ReadResponse(reader, nil) + if err != nil { + t.Fatal(err) + } + if response.StatusCode != http.StatusSwitchingProtocols { + t.Fatal(response.Status) + } + kind, err := readQUICVarint(reader) + if err != nil || kind != 0 { + t.Fatalf("capsule kind = %d, %v", kind, err) + } + length, err := readQUICVarint(reader) + if err != nil || length != 6 { + t.Fatalf("capsule length = %d, %v", length, err) + } + value := make([]byte, length) + if _, err := io.ReadFull(reader, value); err != nil { + t.Fatal(err) + } + if !bytes.Equal(value, append([]byte{0}, []byte("early")...)) { + t.Fatalf("capsule = %x", value) + } + client.Close() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("handler did not stop") + } +} From 05ec5452ee758dfbfb4222a9ff11ee799eb0adc4 Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Wed, 7 Oct 2026 23:33:36 +0800 Subject: [PATCH 25/28] fix(resolver): cancel target lookups when their session expires --- internal/resolver/resolver.go | 12 +++ .../dial_lookup_lifetime_regression_test.go | 76 +++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 internal/runtime/dial_lookup_lifetime_regression_test.go diff --git a/internal/resolver/resolver.go b/internal/resolver/resolver.go index 2ba66c2..42a17d6 100644 --- a/internal/resolver/resolver.go +++ b/internal/resolver/resolver.go @@ -111,6 +111,18 @@ func (r *Resolver) resolve(ctx context.Context, host string, port int, protocol if err != nil { return Resolution{}, err } + if cred.Lifetime != nil { + var cancel context.CancelFunc + ctx, cancel = context.WithCancel(ctx) + stop := context.AfterFunc(cred.Lifetime, cancel) + defer func() { + stop() + cancel() + if cred.Lifetime.Err() != nil { + result, failure = Resolution{}, session.ErrSessionReplaced + } + }() + } defer func() { if failure == nil { result.Generation = cred.Generation diff --git a/internal/runtime/dial_lookup_lifetime_regression_test.go b/internal/runtime/dial_lookup_lifetime_regression_test.go new file mode 100644 index 0000000..0d6f3ab --- /dev/null +++ b/internal/runtime/dial_lookup_lifetime_regression_test.go @@ -0,0 +1,76 @@ +package runtime + +import ( + "context" + "errors" + "net/netip" + "testing" + "time" + + "github.com/ShanghaitechGeekPie/geektrust/internal/session" +) + +func TestTargetResolutionCancelsWithSession(t *testing.T) { + operations := map[string]func(*Runtime, context.Context) error{ + "tcp": func(c *Runtime, ctx context.Context) error { + conn, err := c.DialContext(ctx, "tcp", "lookup.example.invalid:443") + if conn != nil { + conn.Close() + } + return err + }, + "udp": func(c *Runtime, ctx context.Context) error { + conn, err := c.DialContext(ctx, "udp", "lookup.example.invalid:443") + if conn != nil { + conn.Close() + } + return err + }, + "proxy_tcp": func(c *Runtime, ctx context.Context) error { + _, err := c.Resolve(ctx, "lookup.example.invalid", 443) + return err + }, + "proxy_udp": func(c *Runtime, ctx context.Context) error { + _, err := c.ResolveUDP(ctx, "lookup.example.invalid", 443) + return err + }, + } + for name, operation := range operations { + t.Run(name, func(t *testing.T) { + entered := make(chan struct{}) + opts := contractOptions(&contractIdentity{subject: "account"}, &contractStore{state: validState()}) + opts.DNS.Servers = []netip.Addr{} + opts.DNS.FallbackLookup = func(ctx context.Context, _ string) ([]netip.Addr, error) { + close(entered) + <-ctx.Done() + return nil, ctx.Err() + } + c, err := New(opts) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if _, err := c.Connect(context.Background()); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + result := make(chan error, 1) + go func() { result <- operation(c, ctx) }() + select { + case <-entered: + case <-ctx.Done(): + t.Fatal("resolution did not start") + } + c.provider.Invalidate() + select { + case err := <-result: + if !errors.Is(err, session.ErrSessionReplaced) { + t.Fatalf("result = %v", err) + } + case <-time.After(time.Second): + t.Fatal("resolution continued after its session was invalidated") + } + }) + } +} From d1e33c71487bef9ea4ba75c6bf0998a2e719414e Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Wed, 7 Oct 2026 23:33:36 +0800 Subject: [PATCH 26/28] fix(auth): preserve ECNU credential persistence errors --- internal/idsauth/ecnu.go | 2 +- internal/idsauth/ecnu_flow_test.go | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/internal/idsauth/ecnu.go b/internal/idsauth/ecnu.go index b1be3a3..b7ba8ac 100644 --- a/internal/idsauth/ecnu.go +++ b/internal/idsauth/ecnu.go @@ -262,7 +262,7 @@ func (c *ecnuClient) Login(ctx context.Context) error { } c.Keystore.SetSignCount(count) if err = c.Keystore.Save(); err != nil { - return errors.New("cannot persist passkey counter") + return fmt.Errorf("cannot persist passkey counter: %w", err) } token := request["sessionToken"] if token == nil { diff --git a/internal/idsauth/ecnu_flow_test.go b/internal/idsauth/ecnu_flow_test.go index 340a2f1..1e0e7c3 100644 --- a/internal/idsauth/ecnu_flow_test.go +++ b/internal/idsauth/ecnu_flow_test.go @@ -38,6 +38,7 @@ func TestECNUFlow(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { persisted, submitted := false, false + storageErr := errors.New("storage unavailable") var origin string server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { @@ -99,7 +100,7 @@ func TestECNUFlow(t *testing.T) { blob = append(append([]byte{}, ecnuMagic...), blob[len(keystoreMagic):]...) store, err := ParseKeystore(blob, func(b []byte) error { if tc.failSave { - return errors.New("storage unavailable") + return storageErr } k, e := ParseKeystore(b, nil) if e != nil { @@ -120,6 +121,9 @@ func TestECNUFlow(t *testing.T) { if err == nil || submitted { t.Fatal("failed persistence did not stop authentication") } + if !errors.Is(err, storageErr) { + t.Fatalf("persistence error identity was lost: %v", err) + } } else if err != nil || !submitted { t.Fatalf("login failed: %v", err) } From e2f50dd3ccf54e17569cee4dfb73516ee9f7a828 Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Wed, 7 Oct 2026 23:33:36 +0800 Subject: [PATCH 27/28] fix(session): honor caller lifetime for SMS challenges --- internal/session/authentication_test.go | 2 +- internal/session/challenge_lifetime_test.go | 67 +++++++++++++++++++++ internal/session/provider.go | 7 +-- 3 files changed, 70 insertions(+), 6 deletions(-) create mode 100644 internal/session/challenge_lifetime_test.go diff --git a/internal/session/authentication_test.go b/internal/session/authentication_test.go index 5aa4f1f..20c3499 100644 --- a/internal/session/authentication_test.go +++ b/internal/session/authentication_test.go @@ -33,7 +33,7 @@ func TestCancelledChallengeDoesNotSubmitAnswer(t *testing.T) { io.WriteString(w, `{"code":0,"data":{}}`) })) defer server.Close() - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() p := &Provider{logger: slog.New(slog.NewTextHandler(io.Discard, nil)), ChallengeHandler: func(ctx context.Context, challenge auth.Challenge) (string, error) { deadline, ok := ctx.Deadline() diff --git a/internal/session/challenge_lifetime_test.go b/internal/session/challenge_lifetime_test.go new file mode 100644 index 0000000..249d0cc --- /dev/null +++ b/internal/session/challenge_lifetime_test.go @@ -0,0 +1,67 @@ +package session + +import ( + "context" + "errors" + "io" + "net/http" + "strings" + "testing" + "testing/synctest" + "time" + + "github.com/ShanghaitechGeekPie/geektrust/auth" + "github.com/ShanghaitechGeekPie/geektrust/internal/sdpc" +) + +type smsLifetimeTransport struct{ sends int } + +func (s *smsLifetimeTransport) RoundTrip(r *http.Request) (*http.Response, error) { + body := `{"code":0,"data":{"sidTicket":"fixture"}}` + if r.URL.Query().Get("action") == "sendsms" { + s.sends++ + body = `{"code":0,"data":{}}` + } + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil +} + +func TestSMSChallengeUsesCallerLifetime(t *testing.T) { + for _, lifetime := range []time.Duration{0, 5 * time.Minute, 30 * time.Second} { + t.Run(lifetime.String(), func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx := context.Background() + if lifetime != 0 { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, lifetime) + defer cancel() + } + transport := &smsLifetimeTransport{} + sc := sdpc.NewClient("https://controller.example", "Mac", "id", &http.Client{Transport: transport}) + p := &Provider{ChallengeHandler: func(call context.Context, c auth.Challenge) (string, error) { + // The first code expired; the caller is still allowed to request another. + time.Sleep(61 * time.Second) + if err := call.Err(); err != nil { + return "", err + } + info, err := c.Resend(call) + if err != nil { + return "", err + } + deadline, _ := ctx.Deadline() + if !info.Deadline.Equal(deadline) { + t.Errorf("challenge deadline = %v, caller deadline = %v", info.Deadline, deadline) + } + return "123456", nil + }} + ticket, err := p.smsFlow(ctx, sc) + if lifetime == 30*time.Second { + if !errors.Is(err, context.DeadlineExceeded) || transport.sends != 1 { + t.Fatalf("caller timeout: sends=%d, error=%v", transport.sends, err) + } + } else if err != nil || ticket != "fixture" || transport.sends != 2 { + t.Fatalf("resend after first code expires: sends=%d, ticket=%q, error=%v", transport.sends, ticket, err) + } + }) + }) + } +} diff --git a/internal/session/provider.go b/internal/session/provider.go index d28a9bd..3985114 100644 --- a/internal/session/provider.go +++ b/internal/session/provider.go @@ -686,11 +686,8 @@ func (p *Provider) smsFlow(ctx context.Context, sc *sdpc.Client) (string, error) var code string var promptErr error if p.ChallengeHandler != nil { - challengeCtx, cancel := context.WithTimeout(ctx, time.Minute) - defer cancel() - ctx = challengeCtx - expires, _ := challengeCtx.Deadline() - return p.challengeFlow(challengeCtx, sc, expires) + deadline, _ := ctx.Deadline() + return p.challengeFlow(ctx, sc, deadline) } else if p.smsHandler != nil { // Keep typed controller errors for the web layer. An expired auth // session also carries the private restart marker consumed by login. From 084aada99de5cbc9540c60561707961f36dd255f Mon Sep 17 00:00:00 2001 From: vvbbnn00 Date: Wed, 7 Oct 2026 23:33:36 +0800 Subject: [PATCH 28/28] fix(session): retain filtered compatibility gateway fallbacks --- .../runtime/gateway_fallback_filter_test.go | 45 +++++++++++++++++++ internal/session/routing.go | 4 +- 2 files changed, 46 insertions(+), 3 deletions(-) create mode 100644 internal/runtime/gateway_fallback_filter_test.go diff --git a/internal/runtime/gateway_fallback_filter_test.go b/internal/runtime/gateway_fallback_filter_test.go new file mode 100644 index 0000000..de3d7f7 --- /dev/null +++ b/internal/runtime/gateway_fallback_filter_test.go @@ -0,0 +1,45 @@ +package runtime + +import ( + "context" + "errors" + "net" + "sync/atomic" + "testing" +) + +func TestAllowedGatewayCanSelectCompatibilityFallback(t *testing.T) { + for _, filtered := range []bool{false, true} { + name := "unfiltered" + if filtered { + name = "filtered" + } + t.Run(name, func(t *testing.T) { + opts := contractOptions(&contractIdentity{subject: "account"}, &contractStore{state: validState()}) + if filtered { + opts.Network.AllowedGateways = []string{"gateway.example:441"} + } + var dials atomic.Int32 + stop := errors.New("fixture gateway reached") + opts.Network.DialContext = func(_ context.Context, network, address string) (net.Conn, error) { + dials.Add(1) + if network != "tcp" || address != "gateway.example:441" { + t.Errorf("unexpected gateway dial: %s %s", network, address) + } + return nil, stop + } + c, err := New(opts) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if _, err := c.Connect(context.Background()); err != nil { + t.Fatal(err) + } + _, err = c.DialContext(context.Background(), "tcp", "192.0.2.1:443") + if !errors.Is(err, stop) || dials.Load() != 1 { + t.Fatalf("fallback gateway not reached: dials=%d, error=%v", dials.Load(), err) + } + }) + } +} diff --git a/internal/session/routing.go b/internal/session/routing.go index b221c88..4432a52 100644 --- a/internal/session/routing.go +++ b/internal/session/routing.go @@ -19,9 +19,7 @@ func (c *Credential) GatewaysForGroup(group string) []string { assigned = c.Policy.Gateways } if len(assigned) == 0 { - if !c.GatewayOverride { - assigned = c.Gateways - } + assigned = c.Gateways } } if c.GatewayOverride {