PasteFerry (隔空贴): clipboard and file sync across macOS, Windows and Linux. Direct-first, end-to-end encrypted. Optional official access: no server to host. Independent self-hosting remains available.
Dart airdrop-alternativeclipboardclipboard-sharingclipboard-synccopy-pastecross-platformend-to-end-encryptionfile-syncfile-transferfluttergolanglinuxmacosnat-traversalp2pself-hostedtailscaleuniversal-clipboardwebrtcwindows
fix(core): retire closed official relay tunnels immediately
baiyuze7c86afc07a1f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 64cfff0..a0c1cf4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,6 +21,11 @@ relay access. LAN and custom servers continue to work independently.- **Dependencies**: update the Go toolchain and networking dependencies and fixa dependency initialization race found by concurrency checks.+### Fixes++- Retire closed official relay tunnels immediately so clipboard updates made+ after a quota interruption enter the retry queue instead of a stale channel.+### Upgrade notes- **Mac, Windows and Linux apps**: both peers need 2.1.0 for official gatewaydiff --git a/client-core/internal/gateway/gateway_test.go b/client-core/internal/gateway/gateway_test.goindex 8a5a2d4..43a1eeb 100644--- a/client-core/internal/gateway/gateway_test.go+++ b/client-core/internal/gateway/gateway_test.go@@ -198,7 +198,7 @@ func TestGatewayTURNBlackBox(t *testing.T) {t.Fatal(err)}defer db.Close()- if _, err = db.Exec(`UPDATE settings SET body='{"daily_limit":0,"rate_bps":2000000,"global_limit":1000000000,"paused":false}' WHERE id=1`); err != nil {+ if _, err = db.Exec(`UPDATE settings SET body=json_set(body,'$.daily_limit',0) WHERE id=1`); err != nil {t.Fatal(err)}time.Sleep(1200 * time.Millisecond)diff --git a/client-core/internal/gateway/net.go b/client-core/internal/gateway/net.goindex a03bb8b..e8f7465 100644--- a/client-core/internal/gateway/net.go+++ b/client-core/internal/gateway/net.go@@ -20,10 +20,11 @@ import (// Net only exists for a relay-only PeerConnection. It is not a system proxy.type Net struct {transport.Net- client *Client- session string- turn *net.UDPAddr- ctx context.Context+ client *Client+ session string+ turn *net.UDPAddr+ ctx context.Context+ OnClosed func(error)}func (c *Client) Network(ctx context.Context, session, turnAddress string) (*Net, error) {@@ -41,7 +42,7 @@ func (n *Net) ListenPacket(network, address string) (net.PacketConn, error) {if network != "udp4" && network != "udp" {return nil, errors.New("official relay supports UDP4 only")}- return n.client.openPacket(n.ctx, n.session, n.turn)+ return n.client.openPacket(n.ctx, n.session, n.turn, n.OnClosed)}func (n *Net) DialUDP(network string, local, remote *net.UDPAddr) (transport.UDPConn, error) {return nil, errors.New("official relay does not permit direct UDP dialing")@@ -68,9 +69,10 @@ type packetConn struct {readDeadline, writeDeadline time.Timechanged chan struct{}once sync.Once+ onClosed func(error)}-func (c *Client) openPacket(ctx context.Context, session string, remote *net.UDPAddr) (*packetConn, error) {+func (c *Client) openPacket(ctx context.Context, session string, remote *net.UDPAddr, onClosed ...func(error)) (*packetConn, error) {c.mu.Lock()a, ok := c.access[session]enabled, root := c.enabled, c.root@@ -133,6 +135,9 @@ func (c *Client) openPacket(ctx context.Context, session string, remote *net.UDP}connCtx, stop := context.WithCancel(ctx)p := &packetConn{client: c, session: session, ws: ws, local: local, remote: remote, ctx: connCtx, cancel: func() { stop(); stopRoot(); cancelRoot() }, packets: make(chan []byte, 128), changed: make(chan struct{})}+ if len(onClosed) > 0 {+ p.onClosed = onClosed[0]+ }c.mu.Lock()if !c.enabled || root.Err() != nil {c.mu.Unlock()@@ -151,6 +156,10 @@ func (p *packetConn) receive() {for {kind, b, err := p.ws.Read(p.ctx)if err != nil {+ if p.ctx.Err() != nil {+ return+ }+ reason := "service_unavailable"status := websocket.CloseStatus(err)if status == websocket.StatusPolicyViolation {u := p.client.Usage()@@ -163,6 +172,12 @@ func (p *packetConn) receive() {}}p.client.update(u)+ reason = u.Reason+ }+ // ICE may otherwise keep a closed relay selected for many seconds.+ // Notify the owning connection so new offers are queued for retry.+ if p.onClosed != nil {+ go p.onClosed(&Error{Code: reason})}return}diff --git a/client-core/internal/gateway/net_test.go b/client-core/internal/gateway/net_test.gonew file mode 100644index 0000000..3163453--- /dev/null+++ b/client-core/internal/gateway/net_test.go@@ -0,0 +1,55 @@+package gateway++import (+ "context"+ "encoding/json"+ "errors"+ "net"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/baiyuze/pasteferry/client-core/internal/identity"+ "github.com/coder/websocket"+)++func TestTunnelClosureImmediatelyNotifiesOwningConnection(t *testing.T) {+ closeTunnel := make(chan struct{})+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ ws, err := websocket.Accept(w, r, nil)+ if err != nil {+ return+ }+ defer ws.CloseNow()+ b, _ := json.Marshal(map[string]string{"local_address": "127.0.0.1:12345", "turn_address": "127.0.0.1:3478"})+ if ws.Write(r.Context(), websocket.MessageText, b) != nil {+ return+ }+ <-closeTunnel+ _ = ws.Close(websocket.StatusPolicyViolation, "quota_exhausted")+ }))+ defer server.Close()+ c, err := NewClient(identity.FromSeed(make([]byte, 32)), server.URL, nil)+ if err != nil {+ t.Fatal(err)+ }+ defer c.Close()+ c.access["fixture"] = Access{Token: "test-only-token", ExpiresAt: time.Now().Add(time.Hour).Unix()}+ closed := make(chan error, 1)+ p, err := c.openPacket(context.Background(), "fixture", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 3478}, func(err error) { closed <- err })+ if err != nil {+ t.Fatal(err)+ }+ defer p.Close()+ close(closeTunnel)+ select {+ case err = <-closed:+ var e *Error+ if !errors.As(err, &e) || e.Code != "quota_exhausted" || c.Usage().Reason != "quota_exhausted" {+ t.Fatalf("lost immediate quota closure: %v", err)+ }+ case <-time.After(2 * time.Second):+ t.Fatal("closed relay waited for ICE timeout")+ }+}diff --git a/client-core/internal/transport/p2p/official.go b/client-core/internal/transport/p2p/official.goindex ba43760..804c625 100644--- a/client-core/internal/transport/p2p/official.go+++ b/client-core/internal/transport/p2p/official.go@@ -182,6 +182,7 @@ func (m *Manager) startOfficial(deviceID, id string, initial *pb.SignalMessage,m.officialFailed(deviceID, a, err)return}+ network.OnClosed = func(err error) { m.officialFailed(deviceID, a, err) }p, err := NewPeer(PeerOptions{DeviceID: deviceID, SelfID: m.selfID, Logger: m.log, ICEServers: servers, ForceRelay: true, Net: network,SendSignal: func(ctx context.Context, msg *pb.SignalMessage) error {msg.GatewayCapable = true@@ -289,6 +290,10 @@ func (m *Manager) officialFailed(id string, a *officialAttempt, err error) {}}m.mu.Lock()+ if m.relays[id] != a || a.ctx != nil && a.ctx.Err() != nil {+ m.mu.Unlock()+ return+ }if m.relays[id] == a {var ge *gateway.Errorif errors.As(err, &ge) {diff --git a/client-core/internal/transport/p2p/official_test.go b/client-core/internal/transport/p2p/official_test.goindex 9b7534e..6bc36fb 100644--- a/client-core/internal/transport/p2p/official_test.go+++ b/client-core/internal/transport/p2p/official_test.go@@ -137,6 +137,27 @@ func TestOfficialQuotaRecoveryAfterTransportClosure(t *testing.T) {t.Fatal("new allowance did not permit a retry")}}++func TestStaleOfficialClosureDoesNotCancelReplacement(t *testing.T) {+ id := identity.FromSeed(make([]byte, 32))+ c, err := gateway.NewClient(id, "http://127.0.0.1:1", nil)+ if err != nil {+ t.Fatal(err)+ }+ defer c.Close()+ m := NewManager(ManagerOptions{SelfID: id.DeviceID, Gateway: c, Official: func() bool { return true }, DisableEgressProbe: true})+ defer m.Close()+ oldCtx, oldCancel := context.WithCancel(context.Background())+ defer oldCancel()+ currentCtx, currentCancel := context.WithCancel(context.Background())+ defer currentCancel()+ old := &officialAttempt{id: "old", ctx: oldCtx, cancel: oldCancel}+ m.relays["peer"] = &officialAttempt{id: "replacement", ctx: currentCtx, cancel: currentCancel}+ m.officialFailed("peer", old, &gateway.Error{Code: "quota_exhausted"})+ if currentCtx.Err() != nil || c.Usage().Reason != "" {+ t.Fatal("stale tunnel closure poisoned the replacement")+ }+}func TestOfficialDirectThenGatewayTURN(t *testing.T) {binary := os.Getenv("PF_GATEWAY_TEST_BINARY")if binary == "" {diff --git a/design/official-gateway.md b/design/official-gateway.mdindex 8e0cd69..74968e6 100644--- a/design/official-gateway.md+++ b/design/official-gateway.md@@ -143,8 +143,14 @@ are not extra charges. Bill forwarded encrypted payload bytes, includingencryption overhead; file size and usage therefore differ. Normal boundedTURN/STUN/ICE control exchanges are not charged to the device data quota.-Global budget: 1,000,000,000 outbound tunnel datagram bytes/day, including-control. This measures the gateway application boundary, not TCP/TLS headers,+Recommended conservative global budgets: 17 GB per Beijing calendar day and+550 GB per Beijing calendar month, with either limit stopping relay. Both+measure outbound tunnel datagram bytes, including control. A monthly reset+occurs at 00:00 Beijing time on the first day of the next month. Exhaustion+uses the existing `global_exhausted` code; no new client capability is needed.+An owner usage snapshot uses the next monthly reset when the monthly budget+is exhausted. These are configurable hosting policies, not client constants.+This measures the gateway application boundary, not TCP/TLS headers,TCP retransmissions or the hosting provider's bill. Per-group in-memoryenforcement uses bounded durable reservations and idempotent settlement;never perform a SQLite transaction per packet. Exhaustion blocks existing