Skip to content

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.

feat(core): check pasteferry.cc for updates as well

baiyuze2487a90ba3d4
diff --git a/client-core/cmd/pasteferryd/updates.go b/client-core/cmd/pasteferryd/updates.go
index 48fe053..aee694b 100644
--- a/client-core/cmd/pasteferryd/updates.go
+++ b/client-core/cmd/pasteferryd/updates.go
@@ -6,6 +6,7 @@ import (
"log/slog"
"github.com/baiyuze/pasteferry/client-core/internal/config"
+ "github.com/baiyuze/pasteferry/client-core/internal/notifications"
"github.com/baiyuze/pasteferry/client-core/internal/rpc"
"github.com/baiyuze/pasteferry/client-core/internal/update"
pb "github.com/baiyuze/pasteferry/proto/gen/pasteferry/v1"
@@ -21,6 +22,12 @@ func newUpdater(root string, loadCfg func() config.Config, changed func()) *upda
svc.AutoCheck = func() bool { return !loadCfg().UpdateCheckDisabled }
svc.Skipped = func() string { return loadCfg().UpdateSkipVersion }
svc.Changed = changed
+ svc.Checker.Stamp.Lang = func() string {
+ if l := loadCfg().Language; l != "" {
+ return l
+ }
+ return notifications.SystemLanguage()
+ }
if r := svc.LastResult(); r != nil {
slog.Info("上一次自动更新", "from", r.From, "to", r.To, "ok", r.OK, "err", r.Error)
}
diff --git a/client-core/internal/notifications/notifications.go b/client-core/internal/notifications/notifications.go
index 7906f82..6ce97b8 100644
--- a/client-core/internal/notifications/notifications.go
+++ b/client-core/internal/notifications/notifications.go
@@ -333,6 +333,9 @@ var catalog = func() map[string]map[string]string {
return c
}()
+// SystemLanguage 是系统界面语言,如 zh-Hans、en。
+func SystemLanguage() string { return systemLanguage() }
+
func translate(lang, key string) string {
switch {
case strings.HasPrefix(lang, "zh-Hant-HK") || strings.HasPrefix(lang, "zh-HK"):
diff --git a/client-core/internal/update/check.go b/client-core/internal/update/check.go
index 6b12b9c..d5dc5c3 100644
--- a/client-core/internal/update/check.go
+++ b/client-core/internal/update/check.go
@@ -8,6 +8,7 @@ import (
"fmt"
"io"
"net/http"
+ "net/url"
"os"
"path/filepath"
"time"
@@ -17,11 +18,13 @@ import (
type Source struct {
Name string `json:"name"`
Manifest string `json:"manifest"`
+ // Params 为真时清单地址附带版本与平台参数(签名地址不带)
+ Params bool `json:"params,omitempty"`
}
-// DefaultSources 同时请求,谁先返回有效清单用谁:国内用户通常是 Gitee 先到,
-// 之后也先从 Gitee 下载安装包。
+// DefaultSources 同时请求,谁先返回有效清单用谁。
var DefaultSources = []Source{
+ {Name: "pasteferry", Manifest: "https://pasteferry.cc/updates/latest.json", Params: true},
{Name: "github", Manifest: "https://raw.githubusercontent.com/baiyuze/pasteferry/main/updates/latest.json"},
{Name: "gitee", Manifest: "https://gitee.com/baiyuze/pasteferry/raw/main/updates/latest.json"},
}
@@ -58,8 +61,9 @@ type Checker struct {
HTTP *http.Client
Sources []Source
Keys []ed25519.PublicKey
- // Settle 是第一份有效清单到了之后,再等其他地址多久:两边版本不同时用新的那份
+ // Settle 是第一份有效清单到了之后,再等其他地址多久:几处版本不同时用新的那份
Settle time.Duration
+ Stamp *Stamp
}
func NewHTTPClient() *http.Client {
@@ -128,7 +132,17 @@ func (c *Checker) Check(ctx context.Context) (*Found, error) {
}
func (c *Checker) fetch(ctx context.Context, s Source) (*Manifest, error) {
- raw, err := c.get(ctx, s.Manifest)
+ u := s.Manifest
+ var commit func(bool)
+ if s.Params && c.Stamp != nil {
+ var q url.Values
+ q, commit = c.Stamp.Query()
+ u += "?" + q.Encode()
+ }
+ raw, err := c.get(ctx, u)
+ if commit != nil {
+ commit(err == nil)
+ }
if err != nil {
return nil, err
}
@@ -147,7 +161,6 @@ func (c *Checker) get(ctx context.Context, url string) ([]byte, error) {
if err != nil {
return nil, err
}
- // 只是一次普通的下载:不带设备 ID、版本号之类的任何标识
req.Header.Set("User-Agent", "PasteFerry")
resp, err := c.HTTP.Do(req)
if err != nil {
diff --git a/client-core/internal/update/service.go b/client-core/internal/update/service.go
index e75a99a..fa40767 100644
--- a/client-core/internal/update/service.go
+++ b/client-core/internal/update/service.go
@@ -51,9 +51,11 @@ func NewService(current, root string, log *slog.Logger) (*Service, error) {
return nil, err
}
client := NewHTTPClient()
+ target := DetectTarget()
+ stamp := &Stamp{Path: filepath.Join(root, "update-state.json"), Identity: filepath.Join(root, "identity.json"), Version: v.String(), Target: target}
s := &Service{
- Current: v, Root: root, Target: DetectTarget(), HTTP: client, Log: log,
- Checker: &Checker{HTTP: client, Sources: LoadSources(root), Keys: PublicKeys()},
+ Current: v, Root: root, Target: target, HTTP: client, Log: log,
+ Checker: &Checker{HTTP: client, Sources: LoadSources(root), Keys: PublicKeys(), Stamp: stamp},
files: map[string]string{},
}
s.result = ReadResult(root)
diff --git a/client-core/internal/update/stamp.go b/client-core/internal/update/stamp.go
new file mode 100644
index 0000000..e785074
--- /dev/null
+++ b/client-core/internal/update/stamp.go
@@ -0,0 +1,183 @@
+package update
+
+import (
+ "encoding/json"
+ "net/url"
+ "os"
+ "runtime"
+ "strings"
+ "sync"
+ "time"
+)
+
+// Stamp 记着上次检查更新的日期,生成请求官网服务器时附带的参数。
+type Stamp struct {
+ Path string // 数据目录里的 update-state.json
+ Identity string // identity.json:首次运行时写下,用它的时间作为安装日期
+ Version string
+ Target Target
+ Lang func() string
+ Now func() time.Time
+
+ mu sync.Mutex
+ loaded bool
+ state stampFile
+ fresh bool // 状态文件还不存在
+}
+
+type stampFile struct {
+ FirstRun string `json:"first_run"`
+ LastCheck string `json:"last_check"`
+}
+
+const dayLayout = "2006-01-02"
+
+func (s *Stamp) now() time.Time {
+ if s.Now != nil {
+ return s.Now()
+ }
+ return time.Now()
+}
+
+func (s *Stamp) load(today string) {
+ if s.loaded {
+ return
+ }
+ s.loaded = true
+ if raw, err := os.ReadFile(s.Path); err == nil && json.Unmarshal(raw, &s.state) == nil && s.state.FirstRun != "" {
+ return
+ }
+ s.fresh = true
+ s.state = stampFile{FirstRun: today}
+ if st, err := os.Stat(s.Identity); err == nil {
+ s.state.FirstRun = st.ModTime().In(time.Local).Format(dayLayout)
+ }
+}
+
+func (s *Stamp) save() {
+ raw, _ := json.Marshal(s.state)
+ tmp := s.Path + ".tmp"
+ if os.WriteFile(tmp, raw, 0o600) == nil {
+ _ = os.Rename(tmp, s.Path)
+ }
+}
+
+func isoWeek(t time.Time) [2]int {
+ y, w := t.ISOWeek()
+ return [2]int{y, w}
+}
+
+// Query 返回这次请求的参数。commit(true) 在请求成功后记下日期;commit(false) 撤销,
+// 让下一次检查重新算。两次检查同时进行时,只有一次会带上「当天首次」。
+func (s *Stamp) Query() (url.Values, func(ok bool)) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ now := s.now().In(time.Local)
+ today := now.Format(dayLayout)
+ s.load(today)
+ prev, prevFresh := s.state, s.fresh
+
+ flags := ""
+ last, err := time.ParseInLocation(dayLayout, s.state.LastCheck, time.Local)
+ switch {
+ case s.state.LastCheck == "":
+ flags = "dwm"
+ if s.fresh && daysBetween(s.state.FirstRun, today) <= 1 {
+ flags = "ndwm"
+ }
+ case err != nil || today < s.state.LastCheck:
+ // 本机时钟被调回过:这次不算新的一天
+ case today != s.state.LastCheck:
+ flags = "d"
+ if isoWeek(now) != isoWeek(last) {
+ flags += "w"
+ }
+ if now.Format("2006-01") != last.Format("2006-01") {
+ flags += "m"
+ }
+ }
+ if flags != "" {
+ s.state.LastCheck = today
+ }
+ s.fresh = false
+
+ q := url.Values{}
+ q.Set("v", s.Version)
+ q.Set("os", runtime.GOOS)
+ q.Set("arch", runtime.GOARCH)
+ q.Set("pkg", packageKind(s.Target))
+ if s.Lang != nil {
+ q.Set("lang", langCode(s.Lang()))
+ }
+ q.Set("f", flags)
+ q.Set("a", ageBucket(daysBetween(s.state.FirstRun, today)))
+ return q, func(ok bool) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if ok {
+ s.save()
+ return
+ }
+ if s.state.LastCheck == today && prev.LastCheck != today {
+ s.state, s.fresh = prev, prevFresh
+ }
+ }
+}
+
+func daysBetween(a, b string) int {
+ x, err1 := time.ParseInLocation(dayLayout, a, time.Local)
+ y, err2 := time.ParseInLocation(dayLayout, b, time.Local)
+ if err1 != nil || err2 != nil || y.Before(x) {
+ return 0
+ }
+ return int(y.Sub(x).Hours()/24 + 0.5)
+}
+
+func ageBucket(days int) string {
+ switch {
+ case days <= 0:
+ return "0"
+ case days <= 7:
+ return "1"
+ case days <= 30:
+ return "2"
+ case days <= 90:
+ return "3"
+ }
+ return "4"
+}
+
+func packageKind(t Target) string {
+ if t.Blocker == BlockerDev {
+ return "dev"
+ }
+ switch t.Kind {
+ case KindMacApp:
+ return "dmg"
+ case KindWindowsSetup:
+ return "exe"
+ case KindWindowsPortable:
+ return "zip"
+ case KindLinuxDeb:
+ return "deb"
+ case KindLinuxTar:
+ return "tar"
+ }
+ return "other"
+}
+
+func langCode(l string) string {
+ switch {
+ case strings.HasPrefix(l, "zh-Hant-HK") || strings.HasPrefix(l, "zh-HK"):
+ return "zh-Hant-HK"
+ case strings.HasPrefix(l, "zh-Hant") || strings.HasPrefix(l, "zh-TW"):
+ return "zh-Hant-TW"
+ case strings.HasPrefix(l, "zh"):
+ return "zh-Hans"
+ case strings.HasPrefix(l, "ja"):
+ return "ja"
+ case strings.HasPrefix(l, "en"):
+ return "en"
+ }
+ return "other"
+}
diff --git a/client-core/internal/update/stamp_test.go b/client-core/internal/update/stamp_test.go
new file mode 100644
index 0000000..7bee767
--- /dev/null
+++ b/client-core/internal/update/stamp_test.go
@@ -0,0 +1,178 @@
+package update
+
+import (
+ "context"
+ "crypto/ed25519"
+ "crypto/rand"
+ "encoding/base64"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+func newStamp(t *testing.T, installed time.Time) (*Stamp, *time.Time) {
+ t.Helper()
+ dir := t.TempDir()
+ id := filepath.Join(dir, "identity.json")
+ if err := os.WriteFile(id, []byte("{}"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chtimes(id, installed, installed); err != nil {
+ t.Fatal(err)
+ }
+ now := installed
+ return &Stamp{Path: filepath.Join(dir, "update-state.json"), Identity: id, Version: "2.6.1",
+ Target: Target{Kind: KindMacApp}, Lang: func() string { return "zh-Hans" }, Now: func() time.Time { return now }}, &now
+}
+
+func check(t *testing.T, s *Stamp, ok bool) (string, string) {
+ t.Helper()
+ q, commit := s.Query()
+ commit(ok)
+ return q.Get("f"), q.Get("a")
+}
+
+func TestStampNewInstallAndDays(t *testing.T) {
+ day := func(s string) time.Time {
+ v, _ := time.ParseInLocation("2006-01-02 15:04", s, time.Local)
+ return v
+ }
+ s, now := newStamp(t, day("2026-10-28 09:00")) // a Wednesday
+ if f, a := check(t, s, true); f != "ndwm" || a != "0" {
+ t.Fatalf("first check %q %q", f, a)
+ }
+ q, commit := s.Query()
+ commit(true)
+ if q.Get("f") != "" || q.Get("v") != "2.6.1" || q.Get("pkg") != "dmg" || q.Get("lang") != "zh-Hans" || q.Get("os") == "" || q.Get("arch") == "" {
+ t.Fatalf("same day %v", q)
+ }
+ *now = day("2026-10-29 08:00") // same week
+ if f, a := check(t, s, true); f != "d" || a != "1" {
+ t.Fatalf("next day %q %q", f, a)
+ }
+ *now = day("2026-11-02 08:00") // Monday, new week and month
+ if f, _ := check(t, s, true); f != "dwm" {
+ t.Fatalf("new week and month %q", f)
+ }
+ *now = day("2026-11-09 08:00")
+ if f, _ := check(t, s, true); f != "dw" {
+ t.Fatalf("new week %q", f)
+ }
+ // Clock turned back: not a new day.
+ *now = day("2026-11-05 08:00")
+ if f, _ := check(t, s, true); f != "" {
+ t.Fatalf("clock back %q", f)
+ }
+ // A failed request is not remembered.
+ *now = day("2026-11-10 08:00")
+ if f, _ := check(t, s, false); f != "d" {
+ t.Fatalf("failed %q", f)
+ }
+ if f, _ := check(t, s, true); f != "d" {
+ t.Fatalf("retry after failure %q", f)
+ }
+ *now = day("2027-03-01 08:00")
+ if _, a := check(t, s, true); a != "4" {
+ t.Fatalf("age bucket %q", a)
+ }
+}
+
+func TestStampUpgradeIsNotAnInstall(t *testing.T) {
+ installed := time.Now().AddDate(0, 0, -40)
+ s, now := newStamp(t, installed)
+ *now = time.Now()
+ if f, a := check(t, s, true); f != "dwm" || a != "3" {
+ t.Fatalf("upgrade %q %q", f, a)
+ }
+ // The state survives a restart.
+ s2 := &Stamp{Path: s.Path, Identity: s.Identity, Version: "2.6.1", Now: s.Now}
+ if f, _ := check(t, s2, true); f != "" {
+ t.Fatalf("after restart %q", f)
+ }
+}
+
+func TestStampConcurrentChecksCountOnce(t *testing.T) {
+ s, _ := newStamp(t, time.Now().AddDate(0, 0, -3))
+ var mu sync.Mutex
+ daily := 0
+ var wg sync.WaitGroup
+ for i := 0; i < 8; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ q, commit := s.Query()
+ if strings.Contains(q.Get("f"), "d") {
+ mu.Lock()
+ daily++
+ mu.Unlock()
+ }
+ commit(true)
+ }()
+ }
+ wg.Wait()
+ if daily != 1 {
+ t.Fatalf("counted %d times", daily)
+ }
+}
+
+func TestOnlyParamSourceCarriesParams(t *testing.T) {
+ pub, priv, _ := ed25519.GenerateKey(rand.Reader)
+ body := `{"latest":"9.9.9"}`
+ sig := base64.StdEncoding.EncodeToString(ed25519.Sign(priv, []byte(body)))
+ var mu sync.Mutex
+ var seen []string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ seen = append(seen, r.URL.String())
+ mu.Unlock()
+ if strings.HasSuffix(r.URL.Path, ".sig") {
+ _, _ = w.Write([]byte(sig))
+ return
+ }
+ _, _ = w.Write([]byte(body))
+ }))
+ defer srv.Close()
+ s, _ := newStamp(t, time.Now())
+ c := &Checker{HTTP: srv.Client(), Keys: []ed25519.PublicKey{pub}, Stamp: s, Sources: []Source{
+ {Name: "pasteferry", Manifest: srv.URL + "/a/latest.json", Params: true},
+ {Name: "github", Manifest: srv.URL + "/b/latest.json"},
+ }}
+ for _, src := range c.Sources {
+ _, _ = c.fetch(context.Background(), src)
+ }
+ want := map[string]bool{}
+ for _, u := range seen {
+ want[u] = true
+ if strings.Contains(u, "?") && !strings.HasPrefix(u, "/a/latest.json?") {
+ t.Fatalf("params on %s", u)
+ }
+ }
+ if !want["/a/latest.json.sig"] || !want["/b/latest.json"] || !want["/b/latest.json.sig"] {
+ t.Fatalf("requests %v", seen)
+ }
+ found := false
+ for u := range want {
+ if strings.HasPrefix(u, "/a/latest.json?") && strings.Contains(u, "v=2.6.1") && strings.Contains(u, "f=ndwm") {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatalf("no parameters on the first source: %v", seen)
+ }
+}
+
+func TestLangCodeAndPackage(t *testing.T) {
+ for in, want := range map[string]string{"zh-Hans": "zh-Hans", "zh": "zh-Hans", "zh-Hant-TW": "zh-Hant-TW", "zh-Hant-HK": "zh-Hant-HK", "ja": "ja", "en": "en", "fr": "other"} {
+ if got := langCode(in); got != want {
+ t.Errorf("%s → %s", in, got)
+ }
+ }
+ if packageKind(Target{Kind: KindMacApp, Blocker: BlockerDev}) != "dev" || packageKind(Target{Kind: KindLinuxTar}) != "tar" {
+ t.Fatal("package kind")
+ }
+}