diff --git a/docs/reference.md b/docs/reference.md index d1e093f00..4fcffb43e 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -3317,6 +3317,18 @@ binary, the version in the signed message, each file's hash from the signed list. A release read this way must be signed whatever its version. The Stable channel and a `MAGPIE_UPDATE_FEED` of your own don't fall back. +Settings → Network → *Update source* (`"updateSource"` in settings.json, +`magpie settings set updateSource github`, this computer's own) chooses where an +update comes from. Automatic (empty, the default) is what is described here: +usemagpie.ai, then GitHub. `site` (usemagpie.ai only) never goes to GitHub, +for the release or for a file. `github` (GitHub only) reads the release from +`yetone/magpie-releases` without asking the feed, and downloads files from +github.com (through a `--mirror` when one is given, then GitHub's API route); +usemagpie.ai is not asked. On the Stable channel the list of releases is only +the site's, so `github` still reads it from the feed and downloads from +GitHub. A `MAGPIE_UPDATE_FEED` of your own is never overridden. Every source +is held to the same signature and hashes (`Release.verify`). + Release files are downloaded from usemagpie.ai's copy on Cloudflare R2 (`usemagpie.ai/files//`). Every five minutes the site copies the newest release and the Stable one from GitHub into R2, which takes a file diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 64d2b8108..9bc6b0f44 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -20766,6 +20766,7 @@ function renderProxy(s, keep) { }); renderProxyCheck(s, row); renderPluginProxy(s, keep); + import("./updatesource.js").then(() => updateSourcePick(s, keep), statusErr); } const proxyState = { custom: false }; // plugin downloads' proxy (JonahFu on X); plugins' vendor requests follow the one above @@ -22742,7 +22743,7 @@ function dockChoice(s) { // prefsKeep is what the settings page sends of s, all of it each time. function prefsKeep(s) { - return { theme: s.theme, colorblind: !!s.colorblind, reduceMotion: !!s.reduceMotion, noBird: !!s.noBird, lang: s.lang, tray: s.tray, dock: !!s.dock, dockWindow: !!s.dockWindow, dockNever: !!s.dockNever, lightweight: s.lightweight, keepAwake: !!s.keepAwake, keepAwakeDisplay: !!s.keepAwakeDisplay, noWSLAgents: !!s.noWSLAgents, quitNoAsk: !!s.quitNoAsk, restoreOnQuit: !!s.restoreOnQuit, proxy: s.proxy || "", pluginProxy: s.pluginProxy || "", updateProxy: s.updateProxy || "", + return { theme: s.theme, colorblind: !!s.colorblind, reduceMotion: !!s.reduceMotion, noBird: !!s.noBird, lang: s.lang, tray: s.tray, dock: !!s.dock, dockWindow: !!s.dockWindow, dockNever: !!s.dockNever, lightweight: s.lightweight, keepAwake: !!s.keepAwake, keepAwakeDisplay: !!s.keepAwakeDisplay, noWSLAgents: !!s.noWSLAgents, quitNoAsk: !!s.quitNoAsk, restoreOnQuit: !!s.restoreOnQuit, proxy: s.proxy || "", pluginProxy: s.pluginProxy || "", updateProxy: s.updateProxy || "", updateSource: s.updateSource || "", sessionTerminal: s.sessionTerminal || "", uiFont: s.uiFont || null, codeFont: s.codeFont || null, otel: s.otel || {}, diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 09003ec17..3fea31ac9 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1235,6 +1235,9 @@ const I18N = { "Updates go through the proxy above": "更新走上面的代理", "Updates go direct": "更新直连", "Updates go through {proxy}": "更新走 {proxy}", + "Update source": "更新源", + "usemagpie.ai only": "仅 usemagpie.ai", + "GitHub only": "仅 GitHub", "Plugins, npm and GitHub go through {proxy}": "插件、npm 和 GitHub 走 {proxy}", "Following HTTPS_PROXY, {proxy}": "跟随 HTTPS_PROXY:{proxy}", "Ask Cloudflare through the proxy and direct, and compare the addresses the two leave from": "通过代理和直连各请求一次 Cloudflare,比较两者的出口地址", @@ -6371,6 +6374,9 @@ const I18N = { "Updates go through the proxy above": "更新走上面的代理", "Updates go direct": "更新直連", "Updates go through {proxy}": "更新走 {proxy}", + "Update source": "更新來源", + "usemagpie.ai only": "僅 usemagpie.ai", + "GitHub only": "僅 GitHub", "Plugins, npm and GitHub go through {proxy}": "外掛、npm 和 GitHub 走 {proxy}", "Following HTTPS_PROXY, {proxy}": "跟隨 HTTPS_PROXY:{proxy}", "Ask Cloudflare through the proxy and direct, and compare the addresses the two leave from": "透過代理和直連各請求一次 Cloudflare,比較兩者的出口位址", @@ -11478,6 +11484,9 @@ const I18N = { "Updates go through the proxy above": "アップデートは上のプロキシを使います", "Updates go direct": "アップデートは直接接続します", "Updates go through {proxy}": "アップデートは {proxy} を使います", + "Update source": "アップデート元", + "usemagpie.ai only": "usemagpie.ai のみ", + "GitHub only": "GitHub のみ", "Plugins, npm and GitHub go through {proxy}": "プラグイン、npm、GitHub は {proxy} を使います", "Following HTTPS_PROXY, {proxy}": "HTTPS_PROXY に従う:{proxy}", "Ask Cloudflare through the proxy and direct, and compare the addresses the two leave from": "プロキシ経由と直接で Cloudflare に 1 回ずつ問い合わせ、出口のアドレスを比べます", @@ -16600,6 +16609,9 @@ const I18N = { "Updates go through the proxy above": "Updates gehen über den Proxy oben", "Updates go direct": "Updates gehen direkt", "Updates go through {proxy}": "Updates gehen über {proxy}", + "Update source": "Update-Quelle", + "usemagpie.ai only": "Nur usemagpie.ai", + "GitHub only": "Nur GitHub", "Plugins, npm and GitHub go through {proxy}": "Plugins, npm und GitHub gehen über {proxy}", "Following HTTPS_PROXY, {proxy}": "Folgt HTTPS_PROXY, {proxy}", "Ask Cloudflare through the proxy and direct, and compare the addresses the two leave from": "Fragt Cloudflare einmal über den Proxy und einmal direkt und vergleicht die Adressen, von denen beide ausgehen", diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html index 436487fa2..157fc1b9a 100644 --- a/internal/gui/assets/index.html +++ b/internal/gui/assets/index.html @@ -370,6 +370,10 @@
App updates
+
+
Update source
+ +
Proxies
diff --git a/internal/gui/assets/updatesource.js b/internal/gui/assets/updatesource.js new file mode 100644 index 000000000..a6ce3d80d --- /dev/null +++ b/internal/gui/assets/updatesource.js @@ -0,0 +1,20 @@ +// Settings › Network's Update source (RootSir and Sakugar_ on X): where an +// update is read and downloaded from, one menu button as the language's is. +// app.js imports this when the page is drawn, so it weighs nothing on the +// core. "" is automatic; site never goes to GitHub, github never to +// usemagpie.ai. +window.updateSourcePick = function updateSourcePick(s, keep) { + const names = { "": "Automatic", site: "usemagpie.ai only", github: "GitHub only" }; + const b = $("#updateSourcePick"); + const chosen = s.updateSource in names ? s.updateSource : ""; + b.dataset.value = chosen; + b.setAttribute("aria-label", t("Update source")); + b.replaceChildren(el("span", "", t(names[chosen])), svg(CHEV, 11, 1.6)); + b.onclick = (e) => { + e.stopPropagation(); + if (b.classList.contains("open")) return closeProtoMenu(); + openProtoMenu(b, Object.entries(names).map(([v, name]) => ({ v, name, note: "" })), chosen, (v) => { + if (v !== chosen) savePrefs({ ...keep, updateSource: v }); + }, "Update source", "sess-menu", "right"); + }; +}; diff --git a/internal/gui/tests/settings-update-source.test.cjs b/internal/gui/tests/settings-update-source.test.cjs new file mode 100644 index 000000000..29b401a52 --- /dev/null +++ b/internal/gui/tests/settings-update-source.test.cjs @@ -0,0 +1,102 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Update source (RootSir and Sakugar_ on X): Settings › Network has a menu +// button under App updates' proxy. Automatic, usemagpie.ai only and GitHub +// only each save updateSource alone (""/"site"/"github"), in the app's menu +// and in every language. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +function server(lang, posts) { + let cur = { + theme: "light", lang, tray: "panel", currency: "usd", textSize: 100, + proxy: "direct", proxyNow: "", proxySource: "off", pluginProxy: "", updateProxy: "", + trayUsageEvery: 3, version: "test", dir: "/test", lanURLs: [], + visionModels: [], imageGenModels: [], workbuddyCheckins: [], + fx: { rate: 7.2, at: new Date().toISOString(), stale: false }, + }; + return async (route) => { + const req = route.request(), url = new URL(req.url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = ${JSON.stringify({ lang, theme: "light", web: true })};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" }, fx: cur.fx }); + if (url.pathname === "/api/settings") { + if (req.method() === "POST") { + const body = req.postDataJSON(); + posts.push(body); + // as settings.Save: the custom copy is the server's, set from the value + cur = { ...cur, ...body }; + } + return json(cur); + } + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + return route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const labels = { + en: { row: "Update source", auto: "Automatic", site: "usemagpie.ai only", github: "GitHub only", saved: "Saved" }, + zh: { row: "更新源", auto: "自动", site: "仅 usemagpie.ai", github: "仅 GitHub", saved: "已保存" }, + "zh-TW": { row: "更新來源", auto: "自動", site: "僅 usemagpie.ai", github: "僅 GitHub", saved: "已儲存" }, + ja: { row: "アップデート元", auto: "自動", site: "usemagpie.ai のみ", github: "GitHub のみ", saved: "保存しました" }, + de: { row: "Update-Quelle", auto: "Automatisch", site: "Nur usemagpie.ai", github: "Nur GitHub", saved: "Gespeichert" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(labels)) { + const l = labels[lang]; + for (const width of [1100, 420]) { + test(`${engine} ${lang} ${width}px: the update source is picked from the app's menu`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const context = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(4000); + page.setDefaultNavigationTimeout(60000); + const posts = [], errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, posts)); + await page.goto("http://magpie.test/?view=settings&tab=network"); + const row = page.locator("#updateSourceRow"); + await row.getByText(l.row, { exact: true }).waitFor(); + assert.equal(await row.locator("select").count(), 0, "no native select"); + const pick = page.locator("#updateSourcePick"); + assert.equal(await pick.textContent(), l.auto); + const choose = async (name, want) => { + const count = posts.length; + const response = page.waitForResponse((r) => r.url().endsWith("/api/settings") && r.request().method() === "POST"); + await pick.click(); + await page.locator(".proto-menu").waitFor(); + assert.equal(await page.locator(".proto-menu .pm-item").count(), 3); + await page.locator(".proto-menu").getByRole("menuitemradio", { name, exact: true }).click(); + await response; + await page.waitForFunction((word) => document.querySelector("#status")?.textContent.includes(word), l.saved); + assert.equal(posts.length, count + 1, "save once"); + assert.equal(posts.at(-1).updateSource, want); + assert.equal(posts.at(-1).updateProxy, "", "the update proxy stays as it was"); + assert.equal(posts.at(-1).proxy, "direct", "the global proxy stays as it was"); + await page.waitForFunction((word) => document.querySelector("#updateSourcePick")?.textContent === word, name); + }; + await choose(l.github, "github"); + await choose(l.site, "site"); + await choose(l.auto, ""); + // the menu ticks the one chosen + await pick.click(); + assert.equal(await page.locator(".proto-menu .pm-item.on").textContent(), l.auto); + await page.keyboard.press("Escape"); + const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + assert(over <= 0, `the page scrolls sideways by ${over}px`); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/settings/settings.go b/internal/settings/settings.go index 9d23f4637..39c830360 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -153,6 +153,14 @@ type Settings struct { UpdateProxy string `json:"updateProxy,omitempty"` // UpdateProxyCustom is UpdateProxy's ProxyCustom. UpdateProxyCustom string `json:"updateProxyCustom,omitempty"` + // UpdateSource is where magpie's update is read and downloaded from + // (RootSir and Sakugar_ on X: usemagpie.ai's download is slow, or + // github.com is the one that works). "" is automatic: usemagpie.ai, + // then GitHub when it can't be reached; UpdateSourceSite never goes to + // GitHub; UpdateSourceGitHub never to usemagpie.ai (Stable's release + // list excepted, which only the site has). The release is held to its + // signature whichever source gave it. This computer's own (KeepOwn). + UpdateSource string `json:"updateSource,omitempty"` // Proxies are the proxies kept by name (NamedProxy); a proxy choice // "@"+id anywhere (Proxy, PluginProxy, a provider's, a key's, an // account's) uses one. This computer's own (KeepOwn). @@ -1275,6 +1283,12 @@ const AnyProvider = "*/" // at once. const UpdateStable = "stable" +// The values of Settings.UpdateSource; "" is automatic. +const ( + UpdateSourceSite = "site" + UpdateSourceGitHub = "github" +) + // What a reply's model name says (ReplyModel): the model asked for is "". const ( ReplyAsked = "asked" // read as "" @@ -1622,6 +1636,7 @@ func (s *Settings) KeepOwn(cur Settings) { s.ProxyCustom, s.Proxies, s.ProxyNames = cur.ProxyCustom, cur.Proxies, cur.ProxyNames s.PluginProxy, s.PluginProxyCustom = cur.PluginProxy, cur.PluginProxyCustom s.UpdateProxy, s.UpdateProxyCustom = cur.UpdateProxy, cur.UpdateProxyCustom + s.UpdateSource = cur.UpdateSource s.WindowMaximised, s.KeepAwake, s.KeepAwakeDisplay = cur.WindowMaximised, cur.KeepAwake, cur.KeepAwakeDisplay s.WindowAt = cur.WindowAt s.TrayUsages, s.TrayUsage, s.TrayUsageEvery, s.TrayNoLogos, s.TrayNoBird, s.TrayPace, s.TrayNoCost = cur.TrayUsages, cur.TrayUsage, cur.TrayUsageEvery, cur.TrayNoLogos, cur.TrayNoBird, cur.TrayPace, cur.TrayNoCost @@ -2505,6 +2520,11 @@ func saveOwn(s Settings, recording, reads bool) error { if s.UpdateProxy != "" && s.UpdateProxy != "direct" && !IsProxyRef(s.UpdateProxy) { s.UpdateProxyCustom = s.UpdateProxy } + switch s.UpdateSource { + case "", UpdateSourceSite, UpdateSourceGitHub: + default: + return fmt.Errorf("the update source must be site or github, not %q", s.UpdateSource) + } s.Vision = strings.TrimSpace(s.Vision) if s.Vision != "" && s.Vision != "off" && !strings.Contains(s.Vision, "/") { return fmt.Errorf("the vision model must be a model's id such as openai/gpt-5-mini, or off, not %q", s.Vision) diff --git a/internal/settingsapi/settingsapi.go b/internal/settingsapi/settingsapi.go index 6f48a8dc6..2cdc8792c 100644 --- a/internal/settingsapi/settingsapi.go +++ b/internal/settingsapi/settingsapi.go @@ -37,7 +37,7 @@ var Keys = []string{ // usage and alerts "currency", "chineseUnits", "dayStart", "usageAlert", "balanceAlert", "resetReminder", "turnDoneAlert", "maskAlert", // network - "proxy", "pluginProxy", "updateProxy", + "proxy", "pluginProxy", "updateProxy", "updateSource", // privacy "redact", "redactPersonal", "redactKinds", "redactWords", "redactWordsAnyCase", "redactWordsWhole", "redactShape", "noStats", "noUsageStats", "otel", @@ -68,6 +68,7 @@ var Choices = map[string][]string{ "trayUsageEvery": ints(settings.TrayEvery), "dayStart": {"0", "1", "2", "3", "4", "5", "6"}, "updateChannel": {settings.UpdateStable}, + "updateSource": {settings.UpdateSourceSite, settings.UpdateSourceGitHub}, "updateEvery": ints(settings.UpdateEveries), "searchFirst": {settings.SearchFirstModel, settings.SearchFirstAPI}, "replyModel": settings.ReplyModels, diff --git a/internal/settingsapi/settingsapi_test.go b/internal/settingsapi/settingsapi_test.go index d800420b3..01b63e84d 100644 --- a/internal/settingsapi/settingsapi_test.go +++ b/internal/settingsapi/settingsapi_test.go @@ -240,6 +240,7 @@ func TestRefusedValueWritesNothing(t *testing.T) { "searcher": `"nobody/nothing"`, "usageAlert": `101`, "updateChannel": `"nightly"`, + "updateSource": `"cloudflare"`, } { cur := settings.Load() body, err := Body(cur, key, json.RawMessage(value)) diff --git a/internal/update/fallback.go b/internal/update/fallback.go index 37ea632c0..1ddfa7e61 100644 --- a/internal/update/fallback.go +++ b/internal/update/fallback.go @@ -11,6 +11,7 @@ import ( "strings" "time" + "github.com/yetone/magpie/internal/settings" "github.com/yetone/magpie/internal/source" ) @@ -45,7 +46,15 @@ const maxSmall = 1 << 20 // fallsBack says whether a failed feed goes on to GitHub: the default // feed, not the Stable channel, and not an ask already cancelled. func fallsBack(ctx context.Context) bool { - return ctx.Err() == nil && Feed() == siteFeed && !Stable() + return ctx.Err() == nil && Feed() == siteFeed && !Stable() && Source() == "" +} + +// githubOnly says whether the release is read from GitHub alone, with no +// try at the feed: Settings' GitHub only, on the default feed and not on +// Stable (whose release only the site knows; its files still come from +// GitHub). +func githubOnly() bool { + return Feed() == siteFeed && !Stable() && Source() == settings.UpdateSourceGitHub } // githubLatest is the newest release as GitHub gives it, verified. diff --git a/internal/update/source.go b/internal/update/source.go new file mode 100644 index 000000000..b4dca14d6 --- /dev/null +++ b/internal/update/source.go @@ -0,0 +1,19 @@ +package update + +import "github.com/yetone/magpie/internal/settings" + +// Source is Settings' update source, "" when it is automatic: the +// usemagpie.ai feed, then GitHub when the feed can't be reached +// (fallback.go). settings.UpdateSourceSite never goes to GitHub, and +// settings.UpdateSourceGitHub never to usemagpie.ai (RootSir and Sakugar_ +// on X: the site's download is slow). Whichever it is, the release goes +// through Release.verify: the same ed25519 signature over SHA256SUMS, the +// version inside it and every file's hash from it. MAGPIE_UPDATE_FEED, a +// test's feed, is never overridden by it. +func Source() string { + switch s := settings.Load().UpdateSource; s { + case settings.UpdateSourceSite, settings.UpdateSourceGitHub: + return s + } + return "" +} diff --git a/internal/update/source_test.go b/internal/update/source_test.go new file mode 100644 index 000000000..da37020f8 --- /dev/null +++ b/internal/update/source_test.go @@ -0,0 +1,210 @@ +package update + +import ( + "context" + "crypto/ed25519" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "sync/atomic" + "testing" + + "github.com/yetone/magpie/internal/settings" +) + +func sourceFor(t *testing.T, src string) { + t.Helper() + before := settings.Load() + s := before + s.UpdateSource = src + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { settings.Save(before) }) +} + +// liveFeed makes the site answer: its feed names the release signed with +// w's key, and its file is on the site's own address, with the github.com +// address beside it. It counts what it is asked. +func liveFeed(t *testing.T, w *fallbackWorld, version string) (feed, file *atomic.Int32) { + t.Helper() + feed, file = new(atomic.Int32), new(atomic.Int32) + var site *httptest.Server + site = httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/latest": + feed.Add(1) + h := sha256.Sum256(w.body) + json.NewEncoder(rw).Encode(Release{Version: version, Signed: &Signed{Sums: w.sums, Sig: w.sig}, + Assets: map[string]Asset{w.asset: {URL: site.URL + "/dl/" + w.asset, Size: int64(len(w.body)), SHA256: hex.EncodeToString(h[:]), + GitHub: fmt.Sprintf("%s/%s/releases/download/v%s/%s", w.srv.URL, releaseRepo, version, w.asset)}}}) + case "/dl/" + w.asset: + file.Add(1) + rw.Write(w.body) + default: + http.NotFound(rw, r) + } + })) + t.Cleanup(site.Close) + siteFeed = site.URL + "/api/latest" + return +} + +// GitHub only: the feed isn't asked, the release comes from GitHub and the +// file is downloaded from GitHub, though the site answers. +func TestSourceGitHubNeverAsksTheSite(t *testing.T) { + w := newFallbackWorld(t, "0.1.4000") + feed, file := liveFeed(t, w, "0.1.4000") + sourceFor(t, settings.UpdateSourceGitHub) + rel, err := Latest(context.Background()) + if err != nil { + t.Fatal(err) + } + if feed.Load() != 0 || w.apiHits.Load() == 0 { + t.Fatalf("feed asked %d, GitHub API %d", feed.Load(), w.apiHits.Load()) + } + staged, err := stageBinaryFor(context.Background(), rel.Assets[w.asset], filepath.Join(t.TempDir(), "magpie")) + if err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(staged); string(b) != string(w.body) || file.Load() != 0 || w.dlHits.Load() != 1 { + t.Fatalf("file from the site %d, from GitHub %d", file.Load(), w.dlHits.Load()) + } +} + +// GitHub only, with the file named by the site's feed (Stable reads its +// release from the site): the download still starts at github.com. +func TestSourceGitHubDownloadsAFeedFileFromGitHub(t *testing.T) { + w := newFallbackWorld(t, "0.1.4000") + _, file := liveFeed(t, w, "0.1.4000") + rel, err := Latest(context.Background()) // automatic: the site's feed + if err != nil { + t.Fatal(err) + } + sourceFor(t, settings.UpdateSourceGitHub) + if _, err := stageBinaryFor(context.Background(), rel.Assets[w.asset], filepath.Join(t.TempDir(), "magpie")); err != nil { + t.Fatal(err) + } + if file.Load() != 0 || w.dlHits.Load() != 1 { + t.Fatalf("site %d, GitHub %d", file.Load(), w.dlHits.Load()) + } +} + +// Automatic (the default) and the site only both use the site while it answers. +func TestSourceSiteAndAutomaticUseTheSite(t *testing.T) { + for _, src := range []string{"", settings.UpdateSourceSite} { + t.Run("source "+src, func(t *testing.T) { + w := newFallbackWorld(t, "0.1.4000") + feed, file := liveFeed(t, w, "0.1.4000") + sourceFor(t, src) + rel, err := Latest(context.Background()) + if err != nil { + t.Fatal(err) + } + if _, err := stageBinaryFor(context.Background(), rel.Assets[w.asset], filepath.Join(t.TempDir(), "magpie")); err != nil { + t.Fatal(err) + } + if feed.Load() != 1 || file.Load() != 1 || w.apiHits.Load() != 0 || w.dlHits.Load() != 0 { + t.Fatalf("feed %d, site file %d, GitHub API %d, GitHub file %d", feed.Load(), file.Load(), w.apiHits.Load(), w.dlHits.Load()) + } + }) + } +} + +// The site only never goes on to GitHub: not for the release when the +// feed is down, and not for the file when the site's copy fails. +func TestSourceSiteNeverFallsBackToGitHub(t *testing.T) { + w := newFallbackWorld(t, "0.1.4000") + sourceFor(t, settings.UpdateSourceSite) + if _, err := Latest(context.Background()); err == nil { + t.Fatal("the site's feed was down and a release came") + } + if w.apiHits.Load() != 0 { + t.Fatal("GitHub was asked for the release") + } + site := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { http.Error(rw, "busy", 503) })) + defer site.Close() + h := sha256.Sum256(w.body) + a := Asset{URL: site.URL + "/f", SHA256: hex.EncodeToString(h[:]), Size: int64(len(w.body)), + GitHub: fmt.Sprintf("%s/%s/releases/download/v0.1.4000/%s", w.srv.URL, releaseRepo, w.asset)} + if err := download(context.Background(), a, filepath.Join(t.TempDir(), "f")); err == nil { + t.Fatal("the site's file failed and a download came") + } + if w.dlHits.Load() != 0 { + t.Fatal("GitHub was asked for the file") + } + // automatic goes on to GitHub for it + sourceFor(t, "") + if err := download(context.Background(), a, filepath.Join(t.TempDir(), "f")); err != nil || w.dlHits.Load() != 1 { + t.Fatalf("automatic: %v, GitHub file %d", err, w.dlHits.Load()) + } +} + +// A release read from GitHub by choice is held to the signature as one +// read as a fallback is: every bad one is refused, with no file taken. +func TestSourceGitHubRefusesWhatIsNotSigned(t *testing.T) { + for _, bad := range []string{"wrong key", "other sums", "no sig", "junk", "old unsigned"} { + t.Run(bad, func(t *testing.T) { + w := newFallbackWorld(t, "0.1.4000") + liveFeed(t, w, "0.1.4000") // a good feed, which GitHub only doesn't use + sourceFor(t, settings.UpdateSourceGitHub) + switch bad { + case "wrong key": + _, priv, _ := ed25519.GenerateKey(nil) + w.sig = base64.StdEncoding.EncodeToString(ed25519.Sign(priv, []byte("magpie release 0.1.4000\n"+w.sums))) + case "other sums": + h := sha256.Sum256([]byte("evil")) + w.sums = hex.EncodeToString(h[:]) + " " + w.asset + "\n" + case "no sig": + w.sig = "" + case "junk": + w.sig = "not base64!!" + case "old unsigned": + w.sig = "" + } + if rel, err := Latest(context.Background()); err == nil { + t.Fatalf("accepted %+v", rel) + } + if w.dlHits.Load() != 0 { + t.Fatal("a file was downloaded") + } + }) + } +} + +// A feed of MAGPIE_UPDATE_FEED and the Stable channel are the site's +// whatever the source says; the file of a feed release that names no +// github.com address is downloaded from where it is. +func TestSourceGitHubKeepsACustomFeed(t *testing.T) { + w := newFallbackWorld(t, "0.1.4000") + feed, _ := liveFeed(t, w, "0.1.4000") + t.Setenv("MAGPIE_UPDATE_FEED", siteFeed+"?mine") + sourceFor(t, settings.UpdateSourceGitHub) + if _, err := Latest(context.Background()); err != nil || feed.Load() != 1 || w.apiHits.Load() != 0 { + t.Fatalf("err %v, feed %d, GitHub API %d", err, feed.Load(), w.apiHits.Load()) + } +} + +func TestUpdateSourceSettings(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("HOME", t.TempDir()) + if err := settings.Save(settings.Settings{UpdateSource: "cloudflare"}); err == nil { + t.Fatal("an unknown source was saved") + } + for _, v := range []string{"", "site", "github"} { + if err := settings.Save(settings.Settings{UpdateSource: v}); err != nil || settings.Load().UpdateSource != v { + t.Fatalf("%q: %v", v, err) + } + } + from := settings.Settings{Theme: "dark", UpdateSource: "site"} + from.KeepOwn(settings.Settings{UpdateSource: "github"}) + if from.UpdateSource != "github" || from.Theme != "dark" { + t.Fatalf("KeepOwn: %+v", from) + } +} diff --git a/internal/update/update.go b/internal/update/update.go index a99ef8b64..288c036ff 100644 --- a/internal/update/update.go +++ b/internal/update/update.go @@ -141,6 +141,9 @@ func LatestEvery(ctx context.Context, lang string) (*Release, error) { } func latestAt(ctx context.Context, feed, lang string) (*Release, error) { + if githubOnly() { + return githubLatest(ctx, lang) + } if !fallsBack(ctx) { return latestFrom(ctx, feed, lang) } @@ -1220,6 +1223,16 @@ func download(ctx context.Context, a Asset, path string) error { on, viaAPI := a, false toGitHub := a.GitHub != "" && a.GitHub != a.URL toAPI := mirrorOf(ctx) == "" + // Settings' update source (source.go): GitHub only starts at github.com + // and goes on to its API route; the site only goes to no other + switch Source() { + case settings.UpdateSourceGitHub: + if toGitHub { + on.URL, toGitHub = a.GitHub, false + } + case settings.UpdateSourceSite: + toGitHub, toAPI = false, false + } var before []string // each route left, and how it failed for try := 0; try <= len(retryWaits); try++ { if try > 0 {