Skip to content

Refactor SDK interfaces, introduce v2 configuration, and fix session and transport issues - #5

Merged
vvbbnn00 merged 29 commits into
mainfrom
dev
Oct 10, 2026
Merged

vvbbnn00 merged 29 commits into
mainfrom
dev

Conversation

@vvbbnn00

@vvbbnn00 vvbbnn00 commented Oct 10, 2026 •

Copy link
Copy Markdown
Member

SDK 接口变更

模块与认证接口

模块路径从 geektrust 改为 github.com/ShanghaitechGeekPie/geektrust。公开入口包括 client、auth 和 compatibility;下游需要更新依赖及 import,并适配以下定义。被移除的类型和方法未提供兼容别名。

v0.2.1-rc1 本 PR 迁移方式
client.Authenticator / client.AuthenticatorFunc auth.IdentityProvider 实现 Info(ctx) (auth.IdentityInfo, error) 和 Authenticate(ctx, *http.Client, auth.IdentityRequest) error;认证结果不再通过返回用户名表达
client.PasskeyAuthenticator{Store: ...} auth.NewPasskey(store) (*auth.Passkey, error) 凭据存储实现 auth.CredentialStore,再把 Passkey 放入 Options.Auth.Identity
client.InspectPasskey / client.PasskeyInfo auth.InspectPasskey / auth.IdentityInfo Origin 对应 Issuer,Username 对应 Subject,保留 Kind
client.ValidatePasskey 移除 调用 auth.InspectPasskey,检查返回的 error
凭据与会话共用 client.BlobStore 分为 auth.CredentialStore 与 client.SessionStore 凭据的 Load / Save 签名保持不变;会话存储增加作用域及 Delete
Options.PromptSMS func(context.Context) (string, error) Options.Auth.OnChallenge auth.Handler 回调改为 func(context.Context, auth.Challenge) (string, error),根据挑战类型处理输入

IdentityInfo 包含 Issuer、Subject、Kind。SDK 在首次操作时读取身份元数据;同一 Client 的身份发生变化后,调用方需要创建新 Client。IdentityRequest.AllowInteraction 告知身份提供方当前操作是否允许交互。

短信挑战提供 ChallengeInfo.ID、Method、本地 Deadline、可选的服务端 ServerExpiresAt、LastFailure,以及 Challenge.Resend func(context.Context) (auth.ChallengeInfo, error)。当前挑战方法为 auth.SMS。取消、过期或替换后的挑战不可继续使用。Connect、Authenticate 可以进入交互流程;后台检查、数据连接和解析遇到交互要求时返回 auth.ErrInteractionRequired。

client.Options 字段变更

原字段 新定义 行为说明
ControllerURL、DeviceID、Logger 保留 设备 ID 仍为持久化的 32 位大写十六进制值,由宿主管理
Authenticator Auth.Identity 类型改为 auth.IdentityProvider
PromptSMS Auth.OnChallenge 使用带挑战信息的回调
ClientMode bool Auth.Mode client.SessionMode false 对应 BrowserMode,true 对应 DesktopMode;SDK 的零值仍为 BrowserMode
LoginDomain Auth.LoginDomain 登录域由认证设置管理
Platform Compatibility.Protocol.ControllerPlatform 表示控制器协议值,不代表宿主操作系统
AppID Compatibility.Fallbacks.ApplicationID 仅用于兼容兜底,匹配到的控制器资源规则优先
Gateways []string Network.AllowedGateways []string 或 Compatibility.Fallbacks.Gateways 前者筛选候选线路,后者在缺少线路信息时提供兼容兜底;二者均不等同于旧线路覆盖
DNS []string DNS.Servers []netip.Addr 改用地址类型,隧道 DNS 仅接受 IPv4
DisableSystemResolver bool 移除;通过 DNS.FallbackLookup 指定额外解析来源 SDK 默认只使用控制器 DNS,不再隐式查询公共 DNS 和系统 DNS
Transport Network.ControlTransport 保留 http.RoundTripper 类型
DialContext Network.DialContext 保留原函数签名
GatewayTLSConfig Network.GatewayTLS.Config 保留 *tls.Config 类型,拒绝关闭证书验证
GatewayTrustStore Network.GatewayTLS.PinStore,配合 Mode pin 存储接口改为原子检查或登记,见下文
SessionStore 仍名为 SessionStore,接口改为 client.SessionStore 按 SessionScope 隔离,并支持删除

新增 Network.DialTimeout、Network.HTTPTimeout,以及 CheckTarget func(context.Context, client.Target) error。Target 包含 Generation、Network、Host、IP、Port、Purpose;ApplicationTarget 与 DNSQueryTarget 区分应用流量和基础 DNS 查询。该回调只能进一步限制访问权限。

Compatibility.Protocol.Process 可提供 compatibility.ProcessMetadata{Name, Platform, Path}。Compatibility.Fallbacks.MissingGatewayGroup 和 StreamToL3 分别控制缺少网关组时的兼容行为及流式 TCP 到 L3 的回退。

空值语义:

  • Compatibility.Profile 默认为 compatibility.Auto,识别已知控制器,未知控制器使用 Generic。也可显式选择 ShanghaiTech、ECNU、Generic。
  • Compatibility.Fallbacks == nil 使用适配默认值;&compatibility.Fallbacks{} 关闭全部兜底。上科大适配继续提供所需的证书身份及缺字段兜底;通用适配不会默认开启流式 TCP 到 L3 的回退。
  • Network.AllowedGateways == nil 不额外筛选;显式空列表拒绝全部线路。筛选作用于控制器或兼容适配得到的候选线路。
  • DNS.Servers == nil 使用控制器下发的 DNS;显式空列表禁用隧道 DNS。需要其他解析来源时提供 DNS.FallbackLookup。

存储与 TLS 信任定义

新的会话存储接口为:

type SessionStore interface {
    Load(context.Context, SessionScope) ([]byte, error)
    Save(context.Context, SessionScope, []byte) error
    Delete(context.Context, SessionScope) error
}

SessionScope 包含 ControllerURL、IdentityIssuer、IdentitySubject、IdentityKind、DeviceID、Mode、LoginDomain。存储实现必须据此分开记录;Save 必须原子且持久。SDK 在恢复前也会检查缓存归属。旧版本缺少作用域元数据的缓存会触发重新认证,不会直接复用旧 Cookie。

原 GatewayTrustStore.LoadPin / SavePin 改为:

type GatewayPinStore interface {
    CheckOrEnroll(context.Context, GatewayIdentity, [32]byte) (bool, error)
}

GatewayIdentity 包含控制器 URL、网关地址和证书 ServerName。默认 VerifyCA 使用 CA 校验;选择 VerifyCAOrTOFU 时必须提供 PinStore。CA 校验成功时不强制检查 pin;未知 CA 的兜底仍检查证书身份、有效期及服务器用途,并要求存储原子完成检查或首次登记。

Client 方法、状态及返回类型

原定义 新定义或行为
Connect(ctx) (Info, error) / Authenticate(ctx) (Info, error) 返回 SessionInfo;保留 Gateways、DNS、Resources,增加 Generation、Username、DisplayName
Info.Capabilities 从会话结果移除,改为调用 client.ImplementedCapabilities();Capabilities.IPv4ICMP 改名为 IPv4ICMPEcho
TransportInfo 保留 Gateway、VirtualIPv4,增加 Generation
Events() <-chan Event 改为 Status() Status 和 Subscribe(ctx) <-chan Event
Event{Kind, Time} / EventKind 及其常量 改为 Event{Time, Status};根据 Status.State 处理 Idle、Authenticating、Ready、InteractionRequired、Failed、Closed
ExchangePacket(ctx, packet) / PacketTransport 移除旧方法及接口,改为 ExchangeICMPEcho(ctx, packet);输入仍是完整 IPv4 包,仅支持未分片的 ICMP Echo
DialContext / LookupContextHost / OpenTransport / NewDeviceID / Close 保留方法签名;会话替换或失效会取消相关操作并关闭旧连接,调用方负责重连

新增接口:

  • ForgetSession(ctx) error:使当前会话失效并删除对应缓存。
  • Shutdown(ctx) error:关闭 Client 并等待自有任务,调用方可用 context 限制等待。
  • TrustedDevices(ctx) (TrustedDeviceList, error)、TrustCurrentDevice(ctx) error、UntrustDevices(ctx, ids) error、LogoutDevice(ctx, id) error:公开授信设备查询和管理能力。
  • client.Error、ErrorInfo、ErrorKind:提供 Kind、Op、Code、Message,支持 errors.As;保留 ErrClosed、ErrDenied、ErrDatagramTooLarge 及 errors.Is 判断。

Status 快照包含 Revision、Generation、State、Compatibility、Session、LastError。每个订阅者使用独立的有界队列,慢订阅者可能跳过中间状态,应以收到的最新快照为准。Ready 表示控制器会话与当前资源可用,ImplementedCapabilities() 表示实现范围,均不保证某个目标已获授权或已连通。

New 只验证和复制设置,首次操作才读取身份并启动会话工作。宿主仍负责凭据、设备 ID、持久化和外部网络对象的生命周期。SDK 不创建 TUN、监听器或目录,不修改系统路由、DNS 或 ACL。IPv6 目标仍未实现;UDP 保留数据报边界,payload 上限仍为 1372 字节。

新 SDK 初始化示例

以下 credentials 实现 auth.CredentialStore,sessions 实现新的 client.SessionStore,prompt 使用 auth.Handler 签名;controllerURL、deviceID 由宿主提供。

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,
    Auth: client.AuthOptions{
        Identity:    identity,
        Mode:        client.DesktopMode,
        OnChallenge: prompt,
    },
    SessionStore: sessions,
})
if err != nil {
    return err
}
defer c.Close()
if _, err := c.Connect(ctx); err != nil {
    return err
}

配置文件变更

版本 2 字段映射

新配置使用 config_version = 2,从顶层字段改为分组。上科大最小配置为:

config_version = 2

[auth.passkey]
keystore = "./ids-passkey.keystore"

升级现有安装时应迁移旧配置,保留原设备 ID;上面的最小示例主要用于新安装。

v0.2.1-rc1 配置 版本 2 配置 说明
无版本字段 config_version = 2 未设置版本字段时继续按旧格式读取
base_url controller.url 默认仍为上科大控制器;现在要求 HTTPS origin,旧格式也执行此校验
platform controller.platform 默认 Mac;允许其他合法的控制器协议值,不再只接受 Mac
隐式学校适配 controller.compatibility auto / shanghaitech / ecnu / generic
keystore auth.passkey.keystore 凭据文件路径
device_id auth.device_id 可显式保留原 ID;省略时读取或创建平台持久目录中的设备身份
client_type auth.mode auto / client / browser;auto 在上科大适配下选择 client,其他适配选择 browser
login_domain auth.login_domain 登录域;上科大默认值由适配提供
app_id routing.fallback_app_id 仅在需要修改兼容兜底时填写
gateways routing.gateway_filter 语义从覆盖线路改为筛选线路,不能直接替换
dns dns.servers 继续覆盖隧道 DNS;省略或空列表使用控制器 DNS,与 SDK 的显式空列表语义不同
固定的解析顺序 dns.strategy 默认 auto 保留公共 DNS、系统 DNS、隧道 DNS 的既有顺序;controller 只走控制器 DNS;system 只用系统解析
state_file storage.state_file 非空值指定会话文件;留空使用 storage.directory/session.enc,密钥仍为会话文件旁的 .key
无持久目录字段 storage.directory 默认使用平台用户持久目录,保存设备身份及默认会话文件
无权限策略开关 storage.strict_permissions 默认 false,权限检查或设置问题输出警告;true 时阻止操作。旧格式可使用新增的顶层 strict_permissions
log_level logging.level 保留 debug / info / warn / error
[inbound.socks5] enabled/listen [proxy.socks5] listen 省略时默认启用 127.0.0.1:1080;空字符串禁用
[inbound.http] enabled/listen [proxy.http] listen 省略时默认启用 127.0.0.1:8080;空字符串禁用
[web] enabled/listen [web] listen 省略时默认启用 127.0.0.1:8081;空字符串禁用,仍仅允许回环地址
无显式网关 TLS 配置 tls.gateway.server_name / tls.gateway.ca_file 按需指定证书身份或附加 CA;上科大的默认证书身份由适配提供

需要注意的行为差异

  • 版本 2 的相对路径以配置文件所在目录为基准;旧格式继续沿用工作目录基准。迁移命令会把凭据和会话路径写成绝对路径,保留当前实际位置。
  • 旧格式非空 gateways 会覆盖线路;版本 2 的 gateway_filter 只筛选已有候选线路。版本 2 省略 gateway_filter 表示不额外筛选,显式 gateway_filter = [] 表示拒绝全部线路。
  • 版本 2 通过 listen = "" 禁用代理或面板,不再使用 enabled。旧格式仍识别原来的开关。
  • 版本 2 拒绝未知字段和新旧字段混用;旧格式的未知字段可通过 config check 查看警告。网关地址和 DNS 配置会执行更严格的校验,隧道 DNS 只接受 IPv4。
  • init 生成版本 2 配置;缺省设备身份只在启动客户端时创建。config check / show 不创建身份或重写配置。
  • 权限策略不改变内容校验:无效格式及实际读写失败仍会报错。CLI 可通过 CA 文件信任私有 CA;VerifyCAOrTOFU 和原子 pin 存储属于 SDK 接口。

检查与迁移

./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

migrate 默认只输出预览。--write 先创建 config.toml.v1.bak,再替换配置并重新加载检查;已有备份不会被覆盖。原设备 ID、认证模式、凭据及会话路径会保留,迁移命令不会删除或重置 Passkey、签名计数器及原加密缓存。

如果旧配置包含非空 gateways,自动迁移会拒绝执行,需要人工选择新的筛选规则。保留缓存文件不代表能直接恢复旧会话:旧缓存缺少新增的身份及控制器归属信息,首次升级连接需要重新认证。

其他改动

  • 修复 TCP 分帧读取、写入及关闭行为,HTTP Upgrade 完成前不转发 UDP 数据报。
  • 把连接、解析、控制器请求与短信挑战绑定到调用方及会话生命周期,修复失效缓存重用、强制重登排队和筛选后兼容网关丢失的问题。
  • 限制认证和控制器重定向的来源,校验协议响应码、响应封装及网关证书用途。
  • 修复 CLI 短信输入、登录参数、私有文件路径重叠及代理监听冲突;修复发布包解压路径处理。
  • 使用 shadcn UI 重建 Web 面板,加入主题切换,修复对话框关闭后的焦点恢复及确认文字显示。
  • 构建要求改为 Go 1.26.8+;完整 Web 面板需要 Node 22.22+。更新网络依赖及跨平台 CI。

2018wzh and others added 29 commits October 3, 2026 01:48
…ntegration

Complete importable SDK, explicit compatibility and authentication hooks
…etime

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.
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.
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.
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.
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.
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.
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.
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.
Enable logging comments independently of newline bytes and run the example through both LF and CRLF inputs. Remove an obsolete placeholder replacement.
…abled

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.
Copilot AI balanced review requested due to automatic review settings October 10, 2026 11:53

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@vvbbnn00 vvbbnn00 changed the title 重构 SDK 与版本 2 配置,并修复会话和传输行为 Refactor SDK interfaces, introduce v2 configuration, and fix session and transport issues Oct 10, 2026
@vvbbnn00
vvbbnn00 merged commit 815a250 into main Oct 10, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants