跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

link.go

229 行 · 8.5 KB历史下载
1// Package remotelink authenticates an already paired peer and carries TLS over
2// binary WebSocket messages. The relay is not trusted with plaintext or peer
3// identity. Pairing, persistent identity storage, and application integration
4// (including Claude Desktop) are outside this package.
5package remotelink
6
7import (
8 "context"
9 "crypto"
10 "crypto/ecdsa"
11 "crypto/ed25519"
12 "crypto/elliptic"
13 "crypto/rand"
14 "crypto/sha256"
15 "crypto/subtle"
16 "crypto/tls"
17 "crypto/x509"
18 "crypto/x509/pkix"
19 "encoding/base64"
20 "errors"
21 "fmt"
22 "math/big"
23 "strings"
24 "time"
25
26 "github.com/gorilla/websocket"
27)
28
29const (
30 // Protocol is the required TLS application protocol.
31 Protocol = "cage-remote/1"
32 // MaxMessageSize limits each incoming WebSocket binary message, including
33 // all its fragments. Outbound messages are at most 32 KiB.
34 MaxMessageSize = 64 << 10
35 handshakeTimeout = 15 * time.Second
36)
37
38// Identity contains a TLS certificate and its public-key fingerprint. Pin uses
39// "sha256:" followed by standard, padded Base64 of SHA-256(SPKI DER).
40// Keep Certificate.PrivateKey private; exchange pins through the pairing flow.
41type Identity struct {
42 Certificate tls.Certificate
43 Pin string
44}
45
46// NewIdentity creates a temporary Ed25519 identity valid for 24 hours. It is
47// intended for transport validation, not production identity persistence.
48func NewIdentity() (*Identity, error) {
49 _, private, err := ed25519.GenerateKey(rand.Reader)
50 if err != nil {
51 return nil, fmt.Errorf("generate identity key: %w", err)
52 }
53 return IdentityFromKey(private)
54}
55
56// IdentityFromKey issues a short-lived certificate for an existing device key.
57// The peer pin remains stable when this certificate is renewed.
58func IdentityFromKey(key ed25519.PrivateKey) (*Identity, error) {
59 if len(key) != ed25519.PrivateKeySize {
60 return nil, errors.New("invalid Ed25519 identity key")
61 }
62 return IdentityFromSigner(key)
63}
64
65// IdentityFromSigner also supports non-exportable P-256 device keys. TLS and
66// certificate issuance call Sign on the supplied signer; the private key need
67// not be readable by the application.
68func IdentityFromSigner(signer crypto.Signer) (*Identity, error) {
69 if signer == nil {
70 return nil, errors.New("device identity signer is required")
71 }
72 public := signer.Public()
73 switch key := public.(type) {
74 case ed25519.PublicKey:
75 if len(key) != ed25519.PublicKeySize {
76 return nil, errors.New("invalid Ed25519 identity public key")
77 }
78 case *ecdsa.PublicKey:
79 if key == nil || key.Curve != elliptic.P256() {
80 return nil, errors.New("device ECDSA signer must use P-256")
81 }
82 default:
83 return nil, errors.New("device identity signer must use Ed25519 or P-256")
84 }
85 serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
86 if err != nil {
87 return nil, fmt.Errorf("generate certificate serial: %w", err)
88 }
89 now := time.Now()
90 template := &x509.Certificate{
91 SerialNumber: serial,
92 Subject: pkix.Name{CommonName: "Cage temporary remote identity"},
93 NotBefore: now.Add(-time.Minute), NotAfter: now.Add(24 * time.Hour),
94 KeyUsage: x509.KeyUsageDigitalSignature,
95 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
96 }
97 der, err := x509.CreateCertificate(rand.Reader, template, template, public, signer)
98 if err != nil {
99 return nil, fmt.Errorf("create identity certificate: %w", err)
100 }
101 leaf, err := x509.ParseCertificate(der)
102 if err != nil {
103 return nil, fmt.Errorf("parse identity certificate: %w", err)
104 }
105 digest := sha256.Sum256(leaf.RawSubjectPublicKeyInfo)
106 return &Identity{
107 Certificate: tls.Certificate{Certificate: [][]byte{der}, PrivateKey: signer, Leaf: leaf},
108 Pin: "sha256:" + base64.StdEncoding.EncodeToString(digest[:]),
109 }, nil
110}
111
112// Client performs a mutually authenticated TLS 1.3 client handshake. expectedPin
113// must be the server identity established by pairing, never supplied by the
114// relay. Client takes exclusive ownership of ws and closes it on any failure.
115// ctx applies to the handshake only; a successful connection outlives ctx.
116func Client(ctx context.Context, ws *websocket.Conn, identity *Identity, expectedPin string) (*tls.Conn, error) {
117 return handshake(ctx, ws, identity, expectedPin, false, false)
118}
119
120// Server is the server counterpart of Client. expectedPin must identify the
121// already paired client. It has the same ownership and context rules as Client.
122func Server(ctx context.Context, ws *websocket.Conn, identity *Identity, expectedPin string) (*tls.Conn, error) {
123 return handshake(ctx, ws, identity, expectedPin, true, false)
124}
125
126// ServerAfterJoin allows up to two minutes for the other device to enter a
127// relay room. The normal handshake deadline starts when its first binary
128// message arrives. The caller owns the room invitation and its expiry.
129func ServerAfterJoin(ctx context.Context, ws *websocket.Conn, identity *Identity, expectedPin string) (*tls.Conn, error) {
130 return handshake(ctx, ws, identity, expectedPin, true, true)
131}
132
133func peerVerifier(pin string) (func(tls.ConnectionState) error, error) {
134 encoded, ok := strings.CutPrefix(pin, "sha256:")
135 digest, err := base64.StdEncoding.DecodeString(encoded)
136 if !ok || err != nil || len(digest) != sha256.Size || base64.StdEncoding.EncodeToString(digest) != encoded {
137 return nil, errors.New("peer pin must be sha256: followed by padded Base64 of a SHA-256 SPKI digest")
138 }
139 return func(state tls.ConnectionState) error {
140 if state.Version != tls.VersionTLS13 || state.NegotiatedProtocol != Protocol {
141 return errors.New("peer did not negotiate the required TLS version and application protocol")
142 }
143 if len(state.PeerCertificates) == 0 {
144 return errors.New("peer did not provide an identity certificate")
145 }
146 certificate := state.PeerCertificates[0]
147 now := time.Now()
148 if now.Before(certificate.NotBefore) || !now.Before(certificate.NotAfter) {
149 return errors.New("peer identity certificate is outside its validity period")
150 }
151 actual := sha256.Sum256(certificate.RawSubjectPublicKeyInfo)
152 if subtle.ConstantTimeCompare(actual[:], digest) != 1 {
153 return errors.New("peer identity does not match the paired public key")
154 }
155 return nil
156 }, nil
157}
158
159func handshake(ctx context.Context, ws *websocket.Conn, identity *Identity, expectedPin string, server, waitForJoin bool) (_ *tls.Conn, err error) {
160 if ws == nil {
161 return nil, errors.New("WebSocket connection is required")
162 }
163 defer func() {
164 if err != nil {
165 _ = ws.Close()
166 }
167 }()
168 verify, err := peerVerifier(expectedPin)
169 if err != nil {
170 return nil, err
171 }
172 if identity == nil || len(identity.Certificate.Certificate) == 0 || identity.Certificate.PrivateKey == nil {
173 return nil, errors.New("local identity certificate and private key are required")
174 }
175 config := &tls.Config{
176 MinVersion: tls.VersionTLS13, MaxVersion: tls.VersionTLS13,
177 NextProtos: []string{Protocol},
178 Certificates: []tls.Certificate{identity.Certificate},
179 VerifyConnection: verify,
180 SessionTicketsDisabled: true,
181 }
182 stream := newWebSocketConn(ws)
183 if waitForJoin {
184 wait, cancel := context.WithTimeout(ctx, 2*time.Minute)
185 stop := context.AfterFunc(wait, func() { _ = stream.Close() })
186 kind, first, readErr := ws.NextReader()
187 stop()
188 waitErr := wait.Err()
189 cancel()
190 if waitErr != nil {
191 return nil, fmt.Errorf("waiting for paired device: %w", waitErr)
192 }
193 if readErr != nil || kind != websocket.BinaryMessage {
194 return nil, errors.New("peer did not send a binary TLS handshake")
195 }
196 // NextReader has consumed the message header only. The first TLS record
197 // remains in the bounded WebSocket reader used by webSocketConn.Read.
198 stream.reader = first
199 }
200 var connection *tls.Conn
201 if server {
202 config.ClientAuth = tls.RequireAnyClientCert
203 connection = tls.Server(stream, config)
204 } else {
205 // Paired public keys replace Web PKI trust. VerifyConnection is mandatory
206 // and checks the exact key, certificate validity, TLS version, and ALPN.
207 config.InsecureSkipVerify = true
208 connection = tls.Client(stream, config)
209 }
210 ctx, cancel := context.WithTimeout(ctx, handshakeTimeout)
211 defer cancel()
212 deadline, _ := ctx.Deadline()
213 if err := stream.SetDeadline(deadline); err != nil {
214 return nil, fmt.Errorf("set handshake deadline: %w", err)
215 }
216 stop := context.AfterFunc(ctx, func() { _ = stream.Close() })
217 err = connection.HandshakeContext(ctx)
218 stop()
219 if ctx.Err() != nil {
220 return nil, fmt.Errorf("remote TLS handshake: %w", ctx.Err())
221 }
222 if err != nil {
223 return nil, fmt.Errorf("remote TLS handshake: %w", err)
224 }
225 if err := stream.SetDeadline(time.Time{}); err != nil {
226 return nil, fmt.Errorf("clear handshake deadline: %w", err)
227 }
228 return connection, nil
229}