remote

package
v1.0.0-rc.60 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 33 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package remote 是远程访问(路线图 M15)的协议与主机端:手机 App 扫码配对以后,经直连 WebSocket 或 relay 调用这台 pt-tools 的 App API v1。线格式(v1,大小冻结)写在 docs/design/remote-access.md, 测试向量在 testdata/,Go 与 App(Dart)两端共用。

分层:

  • 主机密钥(identity.go):Ed25519 向 relay 证明身份,hostId 由它推导;X25519 是 Noise 的静态密钥。
  • 加密(noise.go):Noise_IK_25519_ChaChaPoly_BLAKE2s,设备是发起方,prologue 绑定协议版本与 hostId。
  • 隧道帧(frame.go):每条 Noise 传输消息的明文是一个帧,一条会话里按请求编号复用。
  • relay 外层帧(outer.go):主机与 relay 之间的连接里按流编号转发 Noise 消息,relay 看不到明文。
  • 配对(pairing.go):一次性配对密钥,只在配对窗口里接受不认识的设备公钥。
  • 主机(host.go、session.go、relay.go):直连入口、relay 客户端、会话登记与分发;设备会话里只放行 /api/app/v1/*。
  • 设备端(client.go):Go 实现,给测试、验收与互通测试用。

Index

Constants

View Source
const (
	// MaxNoiseMessage 是一条 Noise 消息(握手消息或传输消息的密文,含认证标签)的上限
	MaxNoiseMessage = 65535
	// TagLen 是 ChaCha20-Poly1305 认证标签的长度
	TagLen = 16
	// MaxPlaintext 是一条 Noise 传输消息里明文的上限
	MaxPlaintext = MaxNoiseMessage - TagLen
	// FrameHeaderLen 是隧道帧头的长度:[type u8][req_id u32 大端]
	FrameHeaderLen = 5
	// MaxFramePayload 是一个隧道帧 payload 的上限
	MaxFramePayload = MaxPlaintext - FrameHeaderLen
	// MaxPingPayload 是 PING、PONG 的 payload 上限
	MaxPingPayload = 64
	// MaxReasonLen 是 CANCEL 与 GOAWAY 的 payload 上限
	MaxReasonLen = 256
)

各层的大小(v1 冻结)。

View Source
const (
	// GoAwayRevoked 是这台设备被撤销了
	GoAwayRevoked = "revoked"
	// GoAwayScopeChanged 是这台设备的权限改了,重连以后按新权限
	GoAwayScopeChanged = "scope_changed"
	// GoAwayDisabled 是远程访问关掉了
	GoAwayDisabled = "disabled"
	// GoAwayKeyRotated 是主机密钥换了,所有设备要重新配对
	GoAwayKeyRotated = "key_rotated"
	// GoAwayPaired 是配对完成,设备用正常会话重连
	GoAwayPaired = "paired"
	// GoAwayPairingClosed 是配对窗口关了(过期、取消或输错太多次)
	GoAwayPairingClosed = "pairing_closed"
	// GoAwayShutdown 是 pt-tools 正在退出
	GoAwayShutdown = "shutdown"
	// GoAwayProtocol 是对端违反了协议
	GoAwayProtocol = "protocol_error"
)

GOAWAY 的原因。

View Source
const (
	// HostIDLen 是 hostId 的长度:sha256(Ed25519 公钥) 的 base32 取前 26 个字符(130 位)
	HostIDLen = 26
	// KeyLen 是 X25519 公钥、私钥与配对密钥的长度
	KeyLen = 32
)
View Source
const (
	LinkVersion = 1

	// MaxRelays 是一台主机最多配置的 relay 数
	MaxRelays = 4
)

配对链接(v1):

pttools://pair?v=1&h=<hostId>&k=<主机 X25519 公钥>&s=<配对密钥>&r=<relay 地址,逗号分隔>&d=<直连地址>

k、s 是 base64url(无填充)的 32 字节;r、d 可选,但至少要有一个。参数按这个顺序写,值按查询串转义。 不认识的参数忽略(以后加参数不用升级链接版本),认识的参数重复出现时整个链接作废。

View Source
const (
	// ModeDevice 是配对过的设备:可以调用 App API
	ModeDevice = "device"
	// ModePairing 是配对窗口里不认识的设备:只能 POST /remote/v1/pair
	ModePairing = "pairing"
)

会话的种类(HostHello.Mode)。

View Source
const (
	// HelloNotPaired 是主机不认识这台设备(没有配对或已经撤销),而且现在没有配对窗口
	HelloNotPaired = "not_paired"
	// HelloUnsupported 是设备用的协议版本主机不认识
	HelloUnsupported = "unsupported_version"
	// HelloBusy 是主机的会话太多了,稍后再连
	HelloBusy = "busy"
)

主机拒绝握手时 HostHello.Error 的取值。

View Source
const (
	// OuterHeaderLen 是外层帧头的长度
	OuterHeaderLen = 5
	// MaxOuterFrame 是一个外层帧的上限:帧头加一条 Noise 消息
	MaxOuterFrame = OuterHeaderLen + MaxNoiseMessage
	// NonceLen 是 relay 认证质询的长度
	NonceLen = 32
	// MaxUnconfirmed 是主机发 ACCEPT 以前,一个流上每个方向那一条消息的上限:客户端的 Noise 握手第一条、主机拒绝握手的第二条。
	// 这之前每个方向只能发一条,relay 不计量;没有 ACCEPT 就关掉的流(握手被拒绝、解不开)不计入每天的转发量
	MaxUnconfirmed = 4096
	// AuthPayloadLen 是 AUTH 的长度:Ed25519 公钥加签名
	AuthPayloadLen = ed25519.PublicKeySize + ed25519.SignatureSize
)

relay 外层帧(v1):主机与 relay 之间的那条 WebSocket 里,每条二进制消息是一个外层帧 [type u8][stream u32 大端][payload],最大 65540 字节。stream 0 是控制(认证),客户端的流从 1 开始,由 relay 分配。 客户端与 relay 之间的 WebSocket 和直连一样,每条二进制消息就是一条 Noise 消息,relay 把它装进 DATA 转给主机。

View Source
const (
	CloseProtocol    = 4400
	CloseAuthFailed  = 4401
	CloseHostOffline = 4404
	CloseReplaced    = 4409
	CloseLimited     = 4429
	CloseDisabled    = 4503
)

relay 用的 WebSocket 关闭码(4000–4999 是应用自定义)。

View Source
const (
	PairingTTL         = 10 * time.Minute
	MaxPairingFailures = 5
)

配对:一次只有一个配对窗口(新建会替换旧的)。配对密钥 32 字节、10 分钟内有效、只能用一次,输错 5 次作废。 窗口只在内存里,pt-tools 重启以后要重新生成。

View Source
const (
	RelayConnecting = "connecting"
	RelayOnline     = "online"
	RelayOffline    = "offline"
)

relay 的连接状态。

View Source
const (
	// MaxInflight 是一条会话里同时进行的请求数上限,再多的请求直接回 429
	MaxInflight = 16
	// MaxRequestBody 是一个请求体的上限
	MaxRequestBody = 16 << 20

	// IdleTimeout 是多久没收到任何帧就断开(App 至少每 30 秒发一次 PING)
	IdleTimeout = 90 * time.Second

	// PairPath 是配对会话唯一能调用的接口
	PairPath = "/remote/v1/pair"
	// AppAPIPrefix 是设备会话能调用的接口前缀
	AppAPIPrefix = "/api/app/v1/"
)

会话(主机端):握手以后一个读者循环收帧;请求体收齐(REQ_END)以后在单独的 goroutine 里分发,回应按帧写回。

View Source
const (
	ViaDirect = "direct"
	ViaRelay  = "relay"
)

连接方式(Peer.Via、设备的最近在线方式)。

View Source
const (
	// ClientPingInterval 是设备给主机发 PING 的间隔(主机 90 秒收不到任何帧就断开)
	ClientPingInterval = 30 * time.Second
)

设备端(Go 实现):给测试、验收与跨语言互通测试用;App 用 Dart 实现同一套协议。

View Source
const (

	// HandshakeTimeout 是等每一条握手消息的上限
	HandshakeTimeout = 10 * time.Second
)
View Source
const (
	// HandshakesPerMinute 是每个 IP 每分钟最多的直连握手次数
	HandshakesPerMinute = 30
)
View Source
const (
	// MaxRelayStreams 是一条 relay 连接上同时打开的流数上限(与 relay 的默认限额一致)
	MaxRelayStreams = 16
)

relay 客户端:主机主动连 relay(wss://<relay>/v1/host/<hostId>),认证以后 relay 把客户端的连接按流转过来, 每个流是一条独立的 Noise 会话。断了按指数退避加抖动重连。

View Source
const (
	// MaxSessions 是同时在线的会话数上限(直连与 relay 合计)
	MaxSessions = 64
)
View Source
const ProtocolName = "Noise_IK_25519_ChaChaPoly_BLAKE2s"

ProtocolName 是 v1 用的 Noise 协议:设备是发起方(扫码拿到了主机的 X25519 公钥),主机是响应方。

View Source
const StreamPath = "/remote/v1/stream"

StreamPath 是直连入口相对直连地址的路径。

Variables

View Source
var (
	// ErrLink 是配对链接格式不对
	ErrLink = errors.New("配对链接不对")
	// ErrLinkVersion 是配对链接的版本不认识(App 要提示升级)
	ErrLinkVersion = errors.New("配对链接的版本不认识")
	// ErrURL 是 relay 地址或直连地址不对
	ErrURL = errors.New("地址不对")
)
View Source
var (
	// ErrHandshake 是握手没有完成
	ErrHandshake = errors.New("握手失败")
	// ErrNotPaired 是主机不认识这台设备
	ErrNotPaired = errors.New("这台设备没有配对,或者已经被撤销")
)
View Source
var (
	// ErrPairingClosed 是配对窗口已经关了(没有、过期、用过、取消或作废)
	ErrPairingClosed = errors.New("配对已经失效,请在网页上重新生成二维码")
	// ErrPairingSecret 是配对密钥不对
	ErrPairingSecret = errors.New("配对密钥不对")
)

设备的两种权限:完全控制(默认)与只读。

View Source
var (
	// ErrInvalid 是参数不对
	ErrInvalid = errors.New("参数不对")
	// ErrDeviceNotFound 是没有这台设备
	ErrDeviceNotFound = errors.New("没有这台设备")
	// ErrDeviceRevoked 是设备已经撤销,不能再改
	ErrDeviceRevoked = errors.New("这台设备已经撤销")
	// ErrDeviceActive 是设备还没撤销,不能删记录
	ErrDeviceActive = errors.New("先撤销这台设备,才能删掉记录")
	// ErrNoCipher 是没有可用的加密密钥,主机密钥没法落库
	ErrNoCipher = errors.New("没有可用的加密密钥,不能保存主机密钥")
)
View Source
var DefaultRelayURL = ""

DefaultRelayURL 是托管 relay 的地址,构建时用 -ldflags 注入;为空时没有托管 relay,要自己填。

View Source
var ErrDisabled = errors.New("远程访问没有打开")

ErrDisabled 是远程访问没有打开。

View Source
var ErrFrame = errors.New("隧道帧格式不对")

ErrFrame 是隧道帧格式不对。

View Source
var ErrGoAway = errors.New("主机关闭了会话")

ErrGoAway 是主机发了 GOAWAY,会话结束(原因见 Client.GoAway)。

View Source
var ErrOuter = errors.New("relay 外层帧格式不对")

ErrOuter 是外层帧格式不对。

Functions

func AppendFrame

func AppendFrame(dst []byte, f Frame) ([]byte, error)

AppendFrame 把帧编码以后追加到 dst。

func AppendOuter

func AppendOuter(dst []byte, f OuterFrame) ([]byte, error)

AppendOuter 把外层帧编码以后追加到 dst。

func ClosePayload

func ClosePayload(code uint16, reason string) []byte

ClosePayload 是 CLOSE 的内容:u16 关闭码(大端)加原因;原因超长时截断在字符边界上。

func DecodeKey

func DecodeKey(s string) ([]byte, error)

DecodeKey 读回 EncodeKey 的结果,长度必须是 32 字节。

func EncodeKey

func EncodeKey(b []byte) string

EncodeKey 是 32 字节的值(公钥、配对密钥)在链接与接口里的写法:base64url,无填充。

func GenerateKeypair

func GenerateKeypair(rng io.Reader) (noise.DHKey, error)

GenerateKeypair 生成一把 X25519 密钥(主机的 Noise 密钥与设备密钥都用它)。rng 为 nil 时用 crypto/rand。

func HostIDOf

func HostIDOf(pub ed25519.PublicKey) string

HostIDOf 由 Ed25519 公钥推导 hostId:lower(base32(sha256(pub)))[:26],标准字母表、无填充。

func KeypairFromPrivate

func KeypairFromPrivate(priv []byte) (noise.DHKey, error)

KeypairFromPrivate 由 X25519 私钥算出公钥。

func NormalizeDeviceName

func NormalizeDeviceName(raw string) (string, error)

NormalizeDeviceName 去掉首尾空白,最多 64 个字符,不能有控制字符;空名字换成「未命名设备」。

func NormalizeDirectURL

func NormalizeDirectURL(raw string) (string, error)

NormalizeDirectURL 检查并规整直连地址:http:// 或 https://,可以带反向代理的子路径;去掉末尾的 /。

func NormalizeRelayURL

func NormalizeRelayURL(raw string) (string, error)

NormalizeRelayURL 检查并规整 relay 地址:ws:// 或 wss://,可以带路径前缀;去掉末尾的 /。

func NormalizeScopes

func NormalizeScopes(in []string) ([]string, error)

NormalizeScopes 检查设备的权限:只读(app:read)或完全控制(app:read app:write)。

func ParseClosePayload

func ParseClosePayload(p []byte) (code uint16, reason string)

ParseClosePayload 读 CLOSE 的内容;空内容的关闭码是 0。

func Prologue

func Prologue(hostID string) []byte

Prologue 是握手的 prologue:"pt-tools-remote-v1" || hostId。两边不一致时握手失败。

func RelayAuthMessage

func RelayAuthMessage(hostID string, nonce []byte, origin string) []byte

RelayAuthMessage 是主机向 relay 证明身份时签名的内容:"pt-tools-relay-v1" || hostId || nonce || relay origin。 签进 origin,别的 relay 拿到这个签名也冒充不了这台主机。

func RelayOrigin

func RelayOrigin(raw string) (string, error)

RelayOrigin 是 relay 地址的 origin:scheme://主机[:端口],小写,去掉默认端口(ws 的 80、wss 的 443)。 主机按它连上的地址签名,relay 按自己对外的地址校验。

func ValidHostID

func ValidHostID(s string) bool

ValidHostID 报告 s 是不是格式正确的 hostId(26 个 a–z、2–7)。

func VerifyRelayAuth

func VerifyRelayAuth(hostID string, nonce []byte, origin string, payload []byte) error

VerifyRelayAuth 是 relay 端的校验:公钥推导出的 hostId 要对得上,签名要对。

Types

type Cipher

type Cipher interface {
	Encrypt(plain string) (string, error)
	Decrypt(text string) (string, error)
}

Cipher 加解密落库的主机密钥(生产用 ConfigStore 的 AES 密钥,和站点 Cookie 同一把)。

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client 是设备端的一条会话,实现 http.RoundTripper:请求经隧道发给主机。

func Connect

func Connect(ctx context.Context, raw MsgConn, cfg ClientConfig) (*Client, error)

Connect 在 raw 上握手;主机不认识这台设备时返回 ErrNotPaired。

func (*Client) Close

func (c *Client) Close()

Close 关掉会话。

func (*Client) Done

func (c *Client) Done() <-chan struct{}

Done 在会话结束时关闭。

func (*Client) Err

func (c *Client) Err() error

Err 是会话结束的原因。

func (*Client) GoAway

func (c *Client) GoAway() string

GoAway 是主机关会话时给的原因(没有时为空)。

func (*Client) HostVersion

func (c *Client) HostVersion() string

HostVersion 是主机报的 pt-tools 版本。

func (*Client) Mode

func (c *Client) Mode() string

Mode 是会话的种类:device 或 pairing。

func (*Client) Pair

func (c *Client) Pair(ctx context.Context, secret []byte, name string) (Device, error)

Pair 在配对会话里提交配对密钥与设备名,返回主机记下的设备。之后主机会用 GOAWAY paired 关掉这条会话。

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) error

Ping 发一个 PING(回的 PONG 不等)。

func (*Client) RoundTrip

func (c *Client) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip 经隧道发一个请求。请求的 URL 只用路径与查询串;回应体读完或关掉之前,这个请求一直占着一个编号。

type ClientConfig

type ClientConfig struct {
	HostID  string
	HostKey []byte
	// Device 是这台设备的 X25519 密钥
	Device noise.DHKey
	// Client 是 App 的名字与版本,握手时告诉主机
	Client string
	// Random 是握手临时密钥的随机源,nil 时用 crypto/rand(测试向量用固定的)
	Random io.Reader
}

ClientConfig 是设备连主机的参数。

type ClientHello

type ClientHello struct {
	V int `json:"v"`
	// Client 是 App 的名字与版本,只用来记日志
	Client string `json:"client,omitempty"`
}

ClientHello 是设备放在第一条握手消息里的内容(加密,只有主机读得到)。

type Config

type Config struct {
	Store *Store
	// Dispatcher 处理设备会话里的 App API 请求
	Dispatcher Dispatcher
	// OnPaired 在新设备配对成功后调用(发「新设备已配对」通知)
	OnPaired func(ctx context.Context, d Device)
	// Audit 记下配对的结果;deviceID 为 0 表示还没有设备(密钥不对)
	Audit  func(ctx context.Context, deviceID uint, command, result string)
	Logger *zap.SugaredLogger
	// Version 是 pt-tools 的版本,握手时告诉设备
	Version string
	// HTTPClient 连 relay 用(继承代理设置);为空时用 http.DefaultClient
	HTTPClient *http.Client
	// IdleTimeout 是会话多久没收到任何帧就断开;0 时用 IdleTimeout(90 秒)
	IdleTimeout time.Duration
	Now         func() time.Time
}

Config 是主机的依赖。

type Device

type Device struct {
	ID          uint       `json:"id"`
	Name        string     `json:"name"`
	Scopes      []string   `json:"scopes"`
	CreatedAt   time.Time  `json:"created_at"`
	LastSeenAt  *time.Time `json:"last_seen_at,omitempty"`
	LastSeenVia string     `json:"last_seen_via,omitempty"`
	RevokedAt   *time.Time `json:"revoked_at,omitempty"`
}

Device 是配对过的设备(不含公钥)。

func (Device) Has

func (d Device) Has(scope string) bool

Has 报告设备有没有这个权限范围。

type DeviceStatus

type DeviceStatus struct {
	Device
	Online    bool   `json:"online"`
	OnlineVia string `json:"online_via,omitempty"`
}

DeviceStatus 是设备列表里的一项:设备加上现在在不在线。

type Dispatcher

type Dispatcher interface {
	ServeRemote(w http.ResponseWriter, r *http.Request, p Peer)
}

Dispatcher 处理设备会话里的请求。请求只会是 /api/app/v1/* 的路径,只带白名单里的头(没有 Cookie 与 Authorization); 实现要按 Peer.Device 的权限范围鉴权(web 包把它当成远程设备主体交给 App API)。

type Frame

type Frame struct {
	Type FrameType
	// ID 是请求编号:请求与回应的帧不为 0,PING、PONG、GOAWAY 为 0
	ID      uint32
	Payload []byte
}

Frame 是一个隧道帧:每条 Noise 传输消息的明文恰好是一个帧。

func ParseFrame

func ParseFrame(b []byte) (Frame, error)

ParseFrame 解码一个帧。Payload 引用 b 的内容,不复制。

type FrameType

type FrameType uint8

FrameType 是隧道帧的类型。

const (
	FrameReqHead  FrameType = 0x01
	FrameReqBody  FrameType = 0x02
	FrameReqEnd   FrameType = 0x03
	FrameCancel   FrameType = 0x04
	FrameRespHead FrameType = 0x11
	FrameRespBody FrameType = 0x12
	FrameRespEnd  FrameType = 0x13
	FramePing     FrameType = 0x20
	FramePong     FrameType = 0x21
	FrameGoAway   FrameType = 0x30
)

隧道帧的类型。REQ_* 由设备发,RESP_* 由主机发,CANCEL、PING、PONG 两边都发,GOAWAY 只由主机发。

type GoAway

type GoAway struct {
	Reason string `json:"reason"`
}

GoAway 是 GOAWAY 的内容(JSON):主机随后关闭这条会话。

type Host

type Host struct {
	// contains filtered or unexported fields
}

Host 是主机端:直连入口、relay 客户端、配对窗口与会话登记。

func New

func New(cfg Config) *Host

New 建主机;Start 之前远程访问是关着的。

func (*Host) CancelPairing

func (h *Host) CancelPairing()

CancelPairing 关掉配对窗口与窗口里的配对会话。

func (*Host) Close

func (h *Host) Close()

Close 关掉主机:断开 relay 与全部会话(发 GOAWAY shutdown),最多等 5 秒。

func (*Host) DeleteDevice

func (h *Host) DeleteDevice(ctx context.Context, id uint) error

DeleteDevice 删掉撤销了的设备的记录。

func (*Host) Devices

func (h *Host) Devices(ctx context.Context) ([]DeviceStatus, error)

Devices 列出设备与在线状态。

func (*Host) Enabled

func (h *Host) Enabled() bool

Enabled 报告远程访问现在是不是打开着。

func (*Host) Overview

func (h *Host) Overview(ctx context.Context) (Overview, error)

Overview 读设置与状态。

func (*Host) PairingStatus

func (h *Host) PairingStatus() PairingStatus

PairingStatus 是配对窗口的状态。

func (*Host) Reload

func (h *Host) Reload(ctx context.Context) error

Reload 按库里的设置重新配置:关掉时断开全部会话与 relay;主机密钥换了时断开全部会话;relay 按列表增减。

func (*Host) RevokeDevice

func (h *Host) RevokeDevice(ctx context.Context, id uint) (Device, error)

RevokeDevice 撤销设备并立即断开它的会话;之后它的握手会被拒绝。

func (*Host) RotateKeys

func (h *Host) RotateKeys(ctx context.Context) (Overview, error)

RotateKeys 换一套主机密钥:撤销所有设备,断开全部会话,relay 用新的 hostId 重连。

func (*Host) ServeHTTP

func (h *Host) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP 是直连入口 /remote/v1/stream:远程访问关着时 404,每个 IP 每分钟最多 30 次握手。 IP 是连接的对端地址,不读 X-Forwarded-For(没有反向代理时可以随意伪造);部署在反向代理之后时所有设备合用代理的额度。

func (*Host) Start

func (h *Host) Start(ctx context.Context) error

Start 按库里的设置启动(打开着就生成或读出密钥、连上 relay)。

func (*Host) StartPairing

func (h *Host) StartPairing(_ context.Context, scopes []string, direct string) (PairingTicket, error)

StartPairing 开一个配对窗口(替换旧的)。direct 不为空时用它做链接里的直连地址,否则用设置里的。 拿着 h.mu:和改设置串行,链接里的 relay 就是主机正在连的;之后 relay 变了由 applyLocked 作废这个窗口。

func (*Host) UpdateDevice

func (h *Host) UpdateDevice(ctx context.Context, id uint, name *string, scopes []string) (Device, error)

UpdateDevice 改设备的名字或权限;权限变了时立即断开这台设备的会话,重连以后按新权限。

func (*Host) UpdateSettings

func (h *Host) UpdateSettings(ctx context.Context, in Settings) (Overview, error)

UpdateSettings 保存设置并重新配置。打开时先确认主机密钥生成得了,免得设置写成打开、主机却起不来。

type HostHello

type HostHello struct {
	V int `json:"v"`
	// Mode 是会话的种类(ModeDevice 或 ModePairing)
	Mode string `json:"mode,omitempty"`
	// Host 是 pt-tools 的版本
	Host string `json:"host,omitempty"`
	// Error 不为空时主机随后关闭连接
	Error string `json:"error,omitempty"`
}

HostHello 是主机放在第二条握手消息里的内容(加密,只有设备读得到)。

type HostKeys

type HostKeys struct {
	// Sign 向 relay 证明这台主机拥有 hostId
	Sign ed25519.PrivateKey
	// Noise 是 Noise 握手里主机的静态密钥(X25519)
	Noise noise.DHKey
}

HostKeys 是这台 pt-tools 的主机密钥。两把都只在内存与加密以后的库里出现,轮换以后所有设备要重新配对。

func GenerateHostKeys

func GenerateHostKeys(rng io.Reader) (*HostKeys, error)

GenerateHostKeys 生成一套新的主机密钥。rng 为 nil 时用 crypto/rand。

func ParseHostKeys

func ParseHostKeys(b []byte) (*HostKeys, error)

ParseHostKeys 读回 Marshal 的结果。

func (*HostKeys) HostID

func (k *HostKeys) HostID() string

HostID 是这套密钥的 hostId。

func (*HostKeys) Marshal

func (k *HostKeys) Marshal() ([]byte, error)

Marshal 把主机密钥写成 JSON。结果是私钥,调用方加密以后才能落库。

func (*HostKeys) RelayAuth

func (k *HostKeys) RelayAuth(nonce []byte, origin string) []byte

RelayAuth 是主机对质询的回答(AUTH 的内容):Ed25519 公钥加签名。

func (*HostKeys) SignPublic

func (k *HostKeys) SignPublic() ed25519.PublicKey

SignPublic 是签名密钥的公钥。

type MsgConn

type MsgConn interface {
	// ReadMsg 读下一条消息。ctx 结束时连接会被关掉
	ReadMsg(ctx context.Context) ([]byte, error)
	// WriteMsg 写一条消息;返回以后 b 可以复用
	WriteMsg(ctx context.Context, b []byte) error
	// Close 关闭连接;code、reason 是给对端看的关闭原因(不保证送达),不阻塞
	Close(code int, reason string)
}

func DialDirect

func DialDirect(ctx context.Context, direct string, client *http.Client) (MsgConn, error)

DialDirect 连上主机的直连入口:direct 是配对链接里的直连地址(http:// 或 https://),换成 ws:// 或 wss:// 再加上 /remote/v1/stream。 client 为 nil 时用 http.DefaultClient。

func DialRelay

func DialRelay(ctx context.Context, relay, hostID string, client *http.Client) (MsgConn, error)

DialRelay 作为客户端连上 relay:relay/v1/client/<hostId>。

type OuterFrame

type OuterFrame struct {
	Type    OuterType
	Stream  uint32
	Payload []byte
}

OuterFrame 是一个外层帧。

func ParseOuter

func ParseOuter(b []byte) (OuterFrame, error)

ParseOuter 解码一个外层帧。Payload 引用 b 的内容,不复制。

type OuterType

type OuterType uint8

OuterType 是外层帧的类型。

const (
	// OuterChallenge 是 relay 发给主机的认证质询(stream 0,32 字节随机数)
	OuterChallenge OuterType = 0x01
	// OuterAuth 是主机的回答(stream 0):Ed25519 公钥加签名
	OuterAuth OuterType = 0x02
	// OuterReady 是 relay 确认认证通过(stream 0,不带内容)
	OuterReady OuterType = 0x03
	// OuterOpen 是 relay 通知主机有新的客户端流(不带内容)
	OuterOpen OuterType = 0x10
	// OuterData 是一条 Noise 消息,两个方向都有
	OuterData OuterType = 0x11
	// OuterClose 是关掉一个流,两个方向都有;内容可以是空,或者 u16 关闭码加 UTF-8 原因
	OuterClose OuterType = 0x12
	// OuterAccept 是主机告诉 relay 这个流的握手通过了(会话种类 device 或 pairing),不带内容;relay 从这里起计入每天的转发量
	OuterAccept OuterType = 0x13
)

外层帧的类型。

type Overview

type Overview struct {
	Settings
	// HostID 与 HostKey(X25519 公钥)在第一次打开远程访问以后才有
	HostID       string `json:"host_id,omitempty"`
	HostKey      string `json:"host_key,omitempty"`
	DefaultRelay string `json:"default_relay,omitempty"`
	// ActiveRelays 是实际在用的 relay:自己填的,或者没填时的托管 relay;关掉 relay 时为空
	ActiveRelays []string      `json:"active_relays"`
	RelayStatus  []RelayStatus `json:"relay_status"`
	Sessions     int           `json:"sessions"`
	StreamPath   string        `json:"stream_path"`
}

Overview 是给网页看的设置与状态。

type PairError

type PairError struct {
	Status  int
	Code    string
	Message string
}

PairError 是配对被拒绝。

func (*PairError) Error

func (e *PairError) Error() string
type PairingLink struct {
	HostID  string
	HostKey []byte
	Secret  []byte
	Relays  []string
	Direct  string
}

PairingLink 是配对二维码与链接里的内容。

func ParseLink(raw string) (PairingLink, error)

ParseLink 读配对链接并检查每一项。

func (PairingLink) String

func (l PairingLink) String() string

String 写出链接。

type PairingState

type PairingState string

PairingState 是配对窗口的状态。

const (
	PairingNone    PairingState = "none"
	PairingWaiting PairingState = "waiting"
	PairingPaired  PairingState = "paired"
	PairingExpired PairingState = "expired"
	// PairingClosed 是取消了,或者输错太多次作废了
	PairingClosed PairingState = "closed"
)

配对窗口的状态。

type PairingStatus

type PairingStatus struct {
	State     PairingState `json:"state"`
	ExpiresAt *time.Time   `json:"expires_at,omitempty"`
	Scopes    []string     `json:"scopes,omitempty"`
	Failures  int          `json:"failures"`
	// Device 是配对成功的设备
	Device *Device `json:"device,omitempty"`
}

PairingStatus 是配对窗口给网页看的状态。

type PairingTicket

type PairingTicket struct {
	Link      string    `json:"link"`
	ExpiresAt time.Time `json:"expires_at"`
	Scopes    []string  `json:"scopes"`
	HostID    string    `json:"host_id"`
}

PairingTicket 是新开的配对窗口:链接只在这里给一次。

type Peer

type Peer struct {
	Device Device
	// Via 是连接方式:direct 或 relay
	Via string
}

Peer 是设备会话的另一端。

type RelayStatus

type RelayStatus struct {
	URL string `json:"url"`
	// State 是 connecting(正在连)、online(已连上)或 offline(断开,等着重连)
	State   string    `json:"state"`
	Error   string    `json:"error,omitempty"`
	Since   time.Time `json:"since"`
	Streams int       `json:"streams"`
}

RelayStatus 是一个 relay 的连接状态。

type RequestHead

type RequestHead struct {
	Method  string            `json:"method"`
	Path    string            `json:"path"`
	Headers map[string]string `json:"headers,omitempty"`
}

RequestHead 是 REQ_HEAD 的内容(JSON)。Path 是以 / 开头的路径,可以带查询串;Headers 只有白名单里的头会被转发。

type ResponseHead

type ResponseHead struct {
	Status  int               `json:"status"`
	Headers map[string]string `json:"headers,omitempty"`
}

ResponseHead 是 RESP_HEAD 的内容(JSON)。

type Settings

type Settings struct {
	Enabled bool `json:"enabled"`
	// Relays 是自己填的 relay;为空时用内置的托管 relay(见 EffectiveRelays)
	Relays    []string `json:"relays"`
	DirectURL string   `json:"direct_url"`
	// RelayDisabled 为真时不用任何 relay(只直连),填过的 Relays 留着
	RelayDisabled bool `json:"relay_disabled"`
}

Settings 是远程访问的设置。

func NormalizeSettings

func NormalizeSettings(in Settings) (Settings, error)

NormalizeSettings 检查并规整设置:relay 地址去重、最多 4 个;直连地址可以为空。

func (Settings) EffectiveRelays

func (s Settings) EffectiveRelays() []string

EffectiveRelays 是实际要连、也写进配对链接的 relay:关掉 relay 时没有;自己填了就只用自己填的; 没填时用构建时内置的托管 relay(DefaultRelayURL,没有或者地址不对时就是不用 relay)。

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store 读写远程访问的设置、主机密钥与设备表。

func NewStore

func NewStore(db *gorm.DB, cipher Cipher) *Store

NewStore 用 db 与 cipher 建 Store。cipher 为 nil 时不能生成主机密钥(远程访问开不了)。

func (*Store) ActiveDeviceByKey

func (s *Store) ActiveDeviceByKey(ctx context.Context, pub []byte) (*Device, error)

ActiveDeviceByKey 按公钥找没撤销的设备,没有时返回 nil。

func (*Store) CreateDevice

func (s *Store) CreateDevice(ctx context.Context, name string, pub []byte, scopes []string) (Device, error)

CreateDevice 记下配对成功的设备。同一把公钥已经有没撤销的设备时拒绝(那台设备握手时就是正常会话,走不到配对)。

func (*Store) DeleteDevice

func (s *Store) DeleteDevice(ctx context.Context, id uint) error

DeleteDevice 删掉撤销了的设备的记录。

func (*Store) Device

func (s *Store) Device(ctx context.Context, id uint) (Device, error)

Device 读一台设备。

func (*Store) Devices

func (s *Store) Devices(ctx context.Context) ([]Device, error)

Devices 列出所有设备(没撤销的在前,各自按编号)。

func (*Store) HostKeys

func (s *Store) HostKeys(ctx context.Context, create bool) (*HostKeys, error)

HostKeys 读出主机密钥;还没有时 create 为真就生成一套存下来,否则返回 nil。

func (*Store) RevokeDevice

func (s *Store) RevokeDevice(ctx context.Context, id uint) (Device, error)

RevokeDevice 撤销设备(已经撤销的不变)。

func (*Store) RotateHostKeys

func (s *Store) RotateHostKeys(ctx context.Context) (*HostKeys, error)

RotateHostKeys 换一套主机密钥,并撤销所有设备(它们记着旧的主机公钥,已经连不上了)。

func (*Store) SaveSettings

func (s *Store) SaveSettings(ctx context.Context, in Settings) (Settings, error)

SaveSettings 校验并保存设置,返回规整以后写进去的设置(不读回来:写成功以后不能因为读失败让调用方以为没写)。

func (*Store) Settings

func (s *Store) Settings(ctx context.Context) (Settings, error)

Settings 返回当前设置。

func (*Store) TouchDevice

func (s *Store) TouchDevice(ctx context.Context, id uint, via string, at time.Time) error

TouchDevice 记下设备最近一次连上的时间与方式(direct 或 relay)。

func (*Store) UpdateDevice

func (s *Store) UpdateDevice(ctx context.Context, id uint, name *string, scopes []string) (Device, bool, error)

UpdateDevice 改名字或权限(nil 表示不改)。返回改后的设备与权限有没有变;撤销了的设备不能改。

Directories

Path Synopsis
Package relayserver 是 relay 的 Go 自建版(路线图 M16):只做转发,看不到明文。
Package relayserver 是 relay 的 Go 自建版(路线图 M16):只做转发,看不到明文。
Package relaytest 是 relay 的一致性测试(黑盒):Go 自建版与 Cloudflare 版跑同一套用例, 对着一个已经起好的 relay(ws:// 或 wss:// 地址)连主机与客户端,只看线上的行为。
Package relaytest 是 relay 的一致性测试(黑盒):Go 自建版与 Cloudflare 版跑同一套用例, 对着一个已经起好的 relay(ws:// 或 wss:// 地址)连主机与客户端,只看线上的行为。
Command testhost 是手机 App(apps/mobile)互通测试用的主机:真正的 internal/remote 主机端(直连入口与 relay 客户端), App API 换成固定的回应,加一台进程内的 Go relay(relayserver)。
Command testhost 是手机 App(apps/mobile)互通测试用的主机:真正的 internal/remote 主机端(直连入口与 relay 客户端), App API 换成固定的回应,加一台进程内的 Go relay(relayserver)。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL