diff --git a/docs/reference.md b/docs/reference.md index c6cd87aaf..d37cdf446 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -3106,6 +3106,17 @@ magpie update --mirror https://mirror.example/ No mirror is used unless you give one, and the SHA-256 every download is checked against still comes from usemagpie.ai, never from the mirror. +When github.com's download address fails (it answered 504 for every release +file for hours on 2026-11-08) and no mirror is set, the app, `magpie update` +and the installer download the same file through GitHub's API +(`api.github.com/repos/yetone/magpie-releases/releases/assets/`, asked +with `Accept: application/octet-stream`). The file is checked as before: the +feed's SHA-256, and on the Mac the installed app's signing team. A mirror you +set keeps precedence, and no API route is tried through it. While the +download address fails, usemagpie.ai's feed points each file at +`usemagpie.ai/dl//`, which redirects to the API's address, so an +older magpie can update too. + Mac releases are signed and notarised; the Windows and Linux builds are not signed yet (Windows SmartScreen may ask before the first run). Every build keeps itself current: the app diff --git a/internal/update/apiroute.go b/internal/update/apiroute.go new file mode 100644 index 000000000..b85b2a0fb --- /dev/null +++ b/internal/update/apiroute.go @@ -0,0 +1,97 @@ +package update + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + + "github.com/yetone/magpie/internal/source" +) + +// GitHub's API route to a release's file. github.com's download address +// (…/releases/download//) can answer 504 on every try while +// the same file is served through the API: on 2026-11-08 github.com gave +// 504 for every magpie release's file for hours, while +// api.github.com/repos///releases/assets/, asked with +// Accept: application/octet-stream, redirected to the file at once. A +// download whose github.com address is busy goes on there (download): the +// same bytes, checked against the feed's hash, and on the Mac against the +// installed app's team, exactly as before. A mirror the user gave keeps +// precedence: through one, no API route is tried. + +// githubWeb and githubAPI are GitHub's addresses; vars for tests. +var ( + githubWeb = "https://github.com" + githubAPI = "https://api.github.com" +) + +// apiRoute is the API address of a's file: the feed's (Asset.API), else +// the one GitHub's API lists for the release a.URL names. "" with a nil +// error when a's file isn't on GitHub (a test's server, a feed pointed +// elsewhere). +func apiRoute(ctx context.Context, a Asset) (string, error) { + if a.API != "" { + return a.API, nil + } + rest, ok := strings.CutPrefix(a.URL, githubWeb+"/") + if !ok { + return "", nil + } + // //releases/download// + p := strings.Split(rest, "/") + if len(p) != 6 || p[2] != "releases" || p[3] != "download" { + return "", nil + } + req, err := http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("%s/repos/%s/%s/releases/tags/%s", githubAPI, p[0], p[1], p[4]), nil) + if err != nil { + return "", err + } + req.Header.Set("Accept", "application/vnd.github+json") + res, err := source.Do(client, req) + if err != nil { + return "", err + } + defer res.Body.Close() + if res.StatusCode != 200 { + return "", fmt.Errorf("GitHub's API about %s: %s", p[4], res.Status) + } + var rel struct { + Assets []struct { + URL string `json:"url"` + Name string `json:"name"` + } `json:"assets"` + } + if err := json.NewDecoder(res.Body).Decode(&rel); err != nil { + return "", fmt.Errorf("GitHub's API about %s: %w", p[4], err) + } + for _, x := range rel.Assets { + if x.Name == p[5] && strings.HasPrefix(x.URL, githubAPI+"/") { + return x.URL, nil + } + } + return "", fmt.Errorf("GitHub's API lists no %s in %s", p[5], p[4]) +} + +// busyErr reports whether err is a host's busy answer (busyStatus), not +// a connection that broke. +func busyErr(err error) bool { + var s statusError + return errors.As(err, &s) +} + +// viaAPIKey marks a try made through GitHub's API route: no mirror, and +// the file asked for as bytes (Accept: application/octet-stream) rather +// than its description. +type viaAPIKey struct{} + +func withAPIRoute(ctx context.Context) context.Context { + return context.WithValue(ctx, viaAPIKey{}, true) +} + +func onAPIRoute(ctx context.Context) bool { + v, _ := ctx.Value(viaAPIKey{}).(bool) + return v +} diff --git a/internal/update/apiroute_test.go b/internal/update/apiroute_test.go new file mode 100644 index 000000000..550d72076 --- /dev/null +++ b/internal/update/apiroute_test.go @@ -0,0 +1,143 @@ +package update + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" +) + +// fakeGitHub is github.com and api.github.com in one server, as on +// 2026-11-08: the release's download address answers 504 on every try, +// while the API's asset address, asked for the bytes, redirects to them. +type fakeGitHub struct { + srv *httptest.Server + direct, tags, asset, blob atomic.Int32 + body []byte + served []byte // what the blob sends; body unless a test changes it + sum string + assetWithoutOctetStreamAsked atomic.Int32 +} + +func newFakeGitHub(t *testing.T) *fakeGitHub { + t.Helper() + g := &fakeGitHub{body: []byte(strings.Repeat("magpie release ", 8192))} + g.served = g.body + s := sha256.Sum256(g.body) + g.sum = hex.EncodeToString(s[:]) + g.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/yetone/magpie-releases/releases/download/v0.1.9/magpie.zip": + g.direct.Add(1) + w.WriteHeader(http.StatusGatewayTimeout) + case "/repos/yetone/magpie-releases/releases/tags/v0.1.9": + g.tags.Add(1) + fmt.Fprintf(w, `{"tag_name":"v0.1.9","assets":[{"url":"%[1]s/repos/yetone/magpie-releases/releases/assets/6","name":"SHA256SUMS"},{"url":"%[1]s/repos/yetone/magpie-releases/releases/assets/7","name":"magpie.zip","uploader":{"url":"%[1]s/users/x"}}]}`, g.srv.URL) + case "/repos/yetone/magpie-releases/releases/assets/7": + g.asset.Add(1) + if r.Header.Get("Accept") != "application/octet-stream" { + // GitHub describes the file instead + g.assetWithoutOctetStreamAsked.Add(1) + fmt.Fprint(w, `{"name":"magpie.zip"}`) + return + } + http.Redirect(w, r, "/blob/magpie.zip?sig=x", http.StatusFound) + case "/blob/magpie.zip": + g.blob.Add(1) + w.Write(g.served) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(g.srv.Close) + oldWeb, oldAPI := githubWeb, githubAPI + githubWeb, githubAPI = g.srv.URL, g.srv.URL + t.Cleanup(func() { githubWeb, githubAPI = oldWeb, oldAPI }) + quickRetries(t) + return g +} + +func (g *fakeGitHub) asset0() Asset { + return Asset{URL: g.srv.URL + "/yetone/magpie-releases/releases/download/v0.1.9/magpie.zip", SHA256: g.sum} +} + +// github.com's download address answers 504 on every try: the download +// goes on through GitHub's API route, looked up from the release's tag, +// and the file is the release's, checked against the feed's hash. +func TestDownloadGoesThroughTheAPIWhenGitHubIsBusy(t *testing.T) { + g := newFakeGitHub(t) + path := filepath.Join(t.TempDir(), "magpie.zip") + if err := download(context.Background(), g.asset0(), path); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(path); string(b) != string(g.body) { + t.Fatalf("file has %d bytes, want the release's %d", len(b), len(g.body)) + } + // the address that 504s isn't asked again and again first + if n := g.direct.Load(); n != 1 { + t.Fatalf("download address asked %d times, want 1", n) + } + if g.tags.Load() != 1 || g.asset.Load() != 1 || g.blob.Load() != 1 { + t.Fatalf("tags %d, asset %d, blob %d; want 1 each", g.tags.Load(), g.asset.Load(), g.blob.Load()) + } + if n := g.assetWithoutOctetStreamAsked.Load(); n != 0 { + t.Fatalf("asset asked %d times without Accept: application/octet-stream", n) + } +} + +// The feed's own API address is used as it is: no lookup of the tag, +// which costs one of GitHub's 60 anonymous asks an hour. +func TestDownloadTakesTheFeedsAPIAddress(t *testing.T) { + g := newFakeGitHub(t) + a := g.asset0() + a.API = g.srv.URL + "/repos/yetone/magpie-releases/releases/assets/7" + path := filepath.Join(t.TempDir(), "magpie.zip") + if err := download(context.Background(), a, path); err != nil { + t.Fatal(err) + } + if g.tags.Load() != 0 || g.blob.Load() != 1 { + t.Fatalf("tags %d, blob %d; want 0 and 1", g.tags.Load(), g.blob.Load()) + } +} + +// The API route is only another way to the same bytes: a file that comes +// through it changed fails its hash and is not kept. +func TestAPIRouteFileIsCheckedLikeAnyOther(t *testing.T) { + g := newFakeGitHub(t) + g.served = []byte(strings.Repeat("not magpie ", 8192)) + path := filepath.Join(t.TempDir(), "magpie.zip") + err := download(context.Background(), g.asset0(), path) + if err == nil || !strings.Contains(err.Error(), "does not match its checksum") { + t.Fatalf("err = %v, want a checksum failure", err) + } + if _, serr := os.Stat(path); !os.IsNotExist(serr) { + t.Fatalf("a file that failed its hash was kept: %v", serr) + } + if g.blob.Load() == 0 { + t.Fatal("the API route was never tried") + } +} + +// A mirror the user gave keeps precedence: the download goes through it +// alone, and GitHub's API is never asked. +func TestMirrorKeepsPrecedenceOverTheAPIRoute(t *testing.T) { + g := newFakeGitHub(t) + ctx := WithMirror(context.Background(), "https://mirror.example/") + err := download(ctx, g.asset0(), filepath.Join(t.TempDir(), "magpie.zip")) + if err == nil { + t.Fatal("download went through") + } + if g.tags.Load() != 0 || g.asset.Load() != 0 { + t.Fatalf("GitHub's API asked through a mirror: tags %d, asset %d", g.tags.Load(), g.asset.Load()) + } + if n := g.direct.Load(); n != int32(len(retryWaits)+1) { + t.Fatalf("download address asked %d times, want every try (%d)", n, len(retryWaits)+1) + } +} diff --git a/internal/update/update.go b/internal/update/update.go index 72139ec0d..8bc20b3f1 100644 --- a/internal/update/update.go +++ b/internal/update/update.go @@ -64,6 +64,9 @@ type Asset struct { URL string `json:"url"` Size int64 `json:"size"` SHA256 string `json:"sha256"` + // API is GitHub's API address of the file, asked when URL is busy + // (apiroute.go); a feed without it has it looked up from URL. + API string `json:"api,omitempty"` } // client asks the feed and downloads a release through the proxy the rest @@ -1139,7 +1142,12 @@ func download(ctx context.Context, a Asset, path string) error { if err := clearFile(path); err != nil { return err } - var err error + var err, direct error + // on, the tries go through GitHub's API route (apiroute.go): once + // the address itself answered busy, which trying it again didn't get + // past on 2026-11-08, or for the last try after connections that + // broke. Never through a mirror the user gave. + on, tried := a, false for try := 0; try <= len(retryWaits); try++ { if try > 0 { step(ctx, StepRetry) @@ -1150,9 +1158,21 @@ func download(ctx context.Context, a Asset, path string) error { } } step(ctx, StepDownload) - if err = fetch(ctx, a, path); err == nil || ctx.Err() != nil || !Network(err) { + tctx := ctx + if on.URL != a.URL { + tctx = withAPIRoute(ctx) + } + if err = fetch(tctx, on, path); err == nil || ctx.Err() != nil || !Network(err) { break } + if !tried && mirrorOf(ctx) == "" && (busyErr(err) || try == len(retryWaits)-1) { + tried = true + if api, aerr := apiRoute(ctx, a); api != "" { + on.URL, direct = api, err + } else if aerr != nil { + err = fmt.Errorf("%w (GitHub's API route couldn't be found: %v)", err, aerr) + } + } // the tries after a connection that broke go over HTTP/1.1: a // proxy that cuts HTTP/2 streams part way cuts every try made // over it the same way, while HTTP/1.1 through it holds @@ -1160,6 +1180,9 @@ func download(ctx context.Context, a Asset, path string) error { ctx = netproxy.OverHTTP1(ctx) } if err != nil { + if direct != nil { + err = fmt.Errorf("%w, and through api.github.com: %v", direct, err) + } if cerr := clearFile(path); cerr != nil { err = errors.Join(err, cerr) } @@ -1239,7 +1262,10 @@ func Network(err error) bool { return errors.As(err, new(*NetError)) } func fetch(ctx context.Context, a Asset, path string) error { // through a mirror when one is given (mirror.go): the hash checked // below is still the feed's - u := mirrored(mirrorOf(ctx), a.URL) + u := a.URL + if !onAPIRoute(ctx) { + u = mirrored(mirrorOf(ctx), a.URL) + } mirror := strings.TrimSuffix(u, a.URL) name := filepath.Base(path) var have int64 @@ -1290,6 +1316,11 @@ func fetch(ctx context.Context, a Asset, path string) error { if have > 0 { req.Header.Set("Range", fmt.Sprintf("bytes=%d-", have)) } + if onAPIRoute(ctx) { + // the file itself; GitHub redirects to it, and Go's client + // carries Accept and Range to where it is + req.Header.Set("Accept", "application/octet-stream") + } res, err = source.Do(fileClient(), req) if err != nil { if ctx.Err() != nil { diff --git a/site/install.test.mjs b/site/install.test.mjs index 16456a2f6..630fecd6e 100644 --- a/site/install.test.mjs +++ b/site/install.test.mjs @@ -9,6 +9,27 @@ import { fileURLToPath } from "node:url"; const installer = fileURLToPath(new URL("./public/install.sh", import.meta.url)); +// assetId and TAGS: GitHub's API's ids for the release's files, and its +// description of the release as it prints it (indented, nested objects) +const assetId = (name) => 700 + ["magpie-cli-linux-arm64", "magpie-linux-arm64", "magpie-cli-android-arm64"].indexOf(name); +const TAGS = JSON.stringify( + { + url: "https://api.github.com/repos/yetone/magpie-releases/releases/1", + tag_name: "vtest", + author: { login: "x", url: "https://api.github.com/users/x" }, + assets: ["SHA256SUMS", "magpie-cli-linux-arm64", "magpie-linux-arm64", "magpie-cli-android-arm64"].map((name) => ({ + url: `https://api.github.com/repos/yetone/magpie-releases/releases/assets/${name === "SHA256SUMS" ? 699 : assetId(name)}`, + id: 1, + name, + label: "", + uploader: { login: "github-actions[bot]", url: "https://api.github.com/users/github-actions%5Bbot%5D" }, + browser_download_url: `https://github.com/yetone/magpie-releases/releases/download/vtest/${name}`, + })), + }, + null, + 2, +); + // systemPath: a folder of links to what the script runs, without sudo, for // a computer that has none function systemPath(dir) { @@ -21,7 +42,7 @@ function systemPath(dir) { return sys; } -function install(t, { termux = true, arch = "aarch64", override = false, prefixOnly = false, missing = false, corrupt = false, desktop = false, github = false, args = [], env: extra = {}, tamper = "", libs = desktop, cli = !desktop, distro = "ID=ubuntu\nID_LIKE=debian\n", sessions = [], login = "", tty = false, uid = 1000, sudo = true, pmFails = false, payload = "test binary\n" } = {}) { +function install(t, { termux = true, arch = "aarch64", override = false, prefixOnly = false, missing = false, corrupt = false, desktop = false, github = false, api = false, args = [], env: extra = {}, tamper = "", libs = desktop, cli = !desktop, distro = "ID=ubuntu\nID_LIKE=debian\n", sessions = [], login = "", tty = false, uid = 1000, sudo = true, pmFails = false, payload = "test binary\n" } = {}) { const dir = mkdtempSync(join(tmpdir(), "magpie-install-")); t.after(() => rmSync(dir, { recursive: true, force: true })); const tools = join(dir, "tools"); @@ -40,6 +61,7 @@ function install(t, { termux = true, arch = "aarch64", override = false, prefixO for (const name of new Set([file, `magpie-cli-linux-${cpu}`, `magpie-linux-${cpu}`])) { if (missing && name === file) continue; assets[name] = { url: github ? `https://github.com/yetone/magpie-releases/releases/download/vtest/${name}` : `https://download.invalid/${name}`, sha256: corrupt ? "0".repeat(64) : createHash("sha256").update(payload).digest("hex") }; + if (api) assets[name].api = `https://api.github.com/repos/yetone/magpie-releases/releases/assets/${assetId(name)}`; } const requests = join(dir, "requests"); writeFileSync(join(tools, "uname"), `#!/bin/sh\ncase "$1" in -m) echo '${arch}';; -s) echo Linux;; esac\n`, { mode: 0o755 }); @@ -100,6 +122,9 @@ fs.appendFileSync(process.env.INSTALL_REQUESTS, url + String.fromCharCode(10)); fs.appendFileSync(process.env.INSTALL_ARGS, JSON.stringify(args) + String.fromCharCode(10)); const tamper = process.env.INSTALL_TAMPER; if (url.endsWith("/api/latest")) process.stdout.write(process.env.INSTALL_FEED); +else if (process.env.INSTALL_DOWN && url.startsWith(process.env.INSTALL_DOWN)) process.exit(22); +else if (url.includes("/releases/tags/")) process.stdout.write(process.env.INSTALL_TAGS); +else if (url.includes("/releases/assets/") && !args.includes("Accept: application/octet-stream")) fs.writeFileSync(args[args.indexOf("-o") + 1], "{}"); else fs.writeFileSync(args[args.indexOf("-o") + 1], tamper && url.startsWith(tamper) ? "changed by the mirror" : process.env.INSTALL_PAYLOAD); `, { mode: 0o755 }); const env = { @@ -132,6 +157,7 @@ else fs.writeFileSync(args[args.indexOf("-o") + 1], tamper && url.startsWith(tam INSTALL_PAYLOAD: payload, INSTALL_ARGS: join(dir, "args"), INSTALL_TAMPER: tamper, + INSTALL_TAGS: TAGS, MAGPIE_PROXY: "", MAGPIE_MIRROR: "", ...extra, @@ -599,3 +625,35 @@ test("--gui installs WebKitGTK at a terminal too; --tui, MAGPIE_CLI=1 and a head assert.equal(r.pm, "", JSON.stringify(opts)); } }); + +// 2026-11-08: github.com answered 504 for every release file while GitHub's +// API served them. The file is then asked for through the API (the feed's +// api, else looked up from the release's tag), and checked the same way. +test("github.com failing, the file comes through GitHub's API, checked against the site's SHA-256", (t) => { + for (const api of [false, true]) { + const r = install(t, { termux: false, github: true, api, env: { INSTALL_DOWN: "https://github.com/" } }); + assert.equal(r.status, 0, r.stderr); + assert.equal(readFileSync(join(r.bin, "magpie"), "utf8"), r.payload); + const asked = r.requests.trim().split("\n"); + assert.deepEqual(asked, [ + "https://usemagpie.ai/api/latest", + "https://github.com/yetone/magpie-releases/releases/download/vtest/magpie-cli-linux-arm64", + ...(api ? [] : ["https://api.github.com/repos/yetone/magpie-releases/releases/tags/vtest"]), + "https://api.github.com/repos/yetone/magpie-releases/releases/assets/700", + ], String(api)); + assert.ok(r.calls.at(-1).includes("Accept: application/octet-stream"), JSON.stringify(r.calls.at(-1))); + assert.match(r.stdout, /through GitHub's API/); + } + // the API's file is checked as any other + const bad = install(t, { termux: false, github: true, corrupt: true, env: { INSTALL_DOWN: "https://github.com/" } }); + assert.notEqual(bad.status, 0); + assert.match(bad.stderr, /does not match its checksum/); + assert.equal(readFileSync(join(bad.bin, "magpie"), "utf8"), "old installation"); +}); + +test("a mirror given keeps precedence: it failing, GitHub's API is not asked", (t) => { + const r = install(t, { termux: false, github: true, api: true, args: ["--mirror", "https://gh.mirror.example/"], env: { INSTALL_DOWN: "https://gh.mirror.example/" } }); + assert.notEqual(r.status, 0); + assert.match(r.stderr, /could not download https:\/\/gh\.mirror\.example\//); + assert.doesNotMatch(r.requests, /api\.github\.com/); +}); diff --git a/site/public/install.sh b/site/public/install.sh index f9029a351..cd9cd7ce0 100644 --- a/site/public/install.sh +++ b/site/public/install.sh @@ -120,6 +120,19 @@ case "$(uname -m)" in *) arch= ;; esac +# apiroute : GitHub's API address of a release file whose +# github.com address is , read from the release's description with +# sed alone (no jq); nothing when isn't a GitHub release file +apiroute() { + repo=$(printf '%s' "$1" | sed -n 's|^https://github\.com/\([^/]*/[^/]*\)/releases/download/[^/]*/[^/]*$|\1|p') + tag=$(printf '%s' "$1" | sed -n 's|^https://github\.com/[^/]*/[^/]*/releases/download/\([^/]*\)/[^/]*$|\1|p') + [ -n "$repo" ] && [ -n "$tag" ] || return 0 + # one asset's own fields (url, id, name) come before its first nested + # object, so cutting at each { leaves them on one line + get -H 'Accept: application/vnd.github+json' "https://api.github.com/repos/$repo/releases/tags/$tag" 2>/dev/null | tr -d '\n' | tr '{' '\n' | + sed -n "s|.*\"url\": *\"\(https://api\.github\.com/repos/$repo/releases/assets/[0-9]*\)\".*\"name\": *\"$2\".*|\1|p" | head -n 1 +} + tmp= # fetch : the newest release's downloaded into $tmp and # checked against the SHA-256 the site gives, never a mirror's @@ -134,6 +147,7 @@ fetch() { # The feed is one line of JSON; pull this file's url and hash out of it. entry=$(printf '%s' "$feed" | sed -n "s/.*\"$file\":{\([^}]*\)}.*/\1/p") url=$(printf '%s' "$entry" | sed -n 's/.*"url":"\([^"]*\)".*/\1/p') + api=$(printf '%s' "$entry" | sed -n 's/.*"api":"\([^"]*\)".*/\1/p') sum=$(printf '%s' "$entry" | sed -n 's/.*"sha256":"\([^"]*\)".*/\1/p') version=$(printf '%s' "$feed" | sed -n 's/.*"version":"\([^"]*\)".*/\1/p') if [ "$os" = android ] && { [ -z "$url" ] || [ -z "$sum" ]; }; then @@ -147,7 +161,17 @@ fetch() { esac if [ "$from" != "$url" ]; then say "downloading magpie $version ($file) through $mirror" else say "downloading magpie $version ($file)"; fi - get -o "$tmp/$file" "$from" || die "could not download $from" + if ! get -o "$tmp/$file" "$from"; then + # github.com's download address can fail (504 on every try, for hours + # on 2026-11-08) while GitHub's API serves the same file: asked for + # there, checked against the same SHA-256 below. A mirror given keeps + # precedence: through one, nothing else is tried. + [ "$from" = "$url" ] || die "could not download $from" + [ -n "$api" ] || api=$(apiroute "$url" "$file") + [ -n "$api" ] || die "could not download $url" + say "that failed; downloading it through GitHub's API instead" + get -H 'Accept: application/octet-stream' -o "$tmp/$file" "$api" || die "could not download $url, nor through $api" + fi if command -v sha256sum >/dev/null; then got=$(sha256sum "$tmp/$file" | cut -d' ' -f1) else got=$(shasum -a 256 "$tmp/$file" | cut -d' ' -f1); fi if [ "$got" != "$sum" ]; then diff --git a/site/worker.js b/site/worker.js index cb8d7fbe9..aca3601b8 100644 --- a/site/worker.js +++ b/site/worker.js @@ -2,7 +2,7 @@ // worker turns the newest one into the update feed the app reads and into // download links that never go stale. // -// /api/latest {version, notes, url, published, assets: {name: {url, size, sha256}}} +// /api/latest {version, notes, url, published, assets: {name: {url, api, size, sha256}}} // /api/latest?channel=stable // the same for Settings' Stable channel: a release a // week, an urgent one at once ("The Stable channel" @@ -32,6 +32,8 @@ // /download/windows the Windows app (x64); /download/windows-arm64 // /download/linux the Linux app (x86-64); /download/linux-arm64 // /download/ any file of the newest release, by name +// /dl// a release's file through GitHub's API, the feed's +// url while github.com's download address fails // /r/... the pages' PostHog snippet, passed on to PostHog // (relay, below) so a blocker that knows its host // doesn't drop the count @@ -48,6 +50,7 @@ import { PARTNERS } from "./partners.js"; import { SPONSORS } from "./sponsors.js"; const REPO = "yetone/magpie-releases"; +const SITE = "https://usemagpie.ai"; const TTL = 300; // seconds the newest release is remembered const SHORT = { @@ -127,6 +130,8 @@ export default { return json({ releases: pick }, 200, cacheFor(got)); } if (url.pathname === "/api/icon") return icon(url.searchParams.get("url")); + const dl = url.pathname.match(/^\/dl\/(v[0-9][0-9A-Za-z.+-]*)\/([0-9A-Za-z._+-]+)$/); + if (dl) return detour(ctx, env, dl[1], dl[2]); if (url.pathname.startsWith(RELAY)) return relay(req, url); if (url.pathname === "/download" || url.pathname.startsWith("/download/")) { const want = url.pathname.split("/")[2] || "mac-arm64"; @@ -432,8 +437,10 @@ async function latest(ctx, env) { if (hit && hit.rel && hit.rel.version) return hit; const full = await fromAPI(env); if (full) { - const got = { rel: full, degraded: false }; - remember(ctx, "latest", got, TTL); + // a feed sending the files by /dl is kept briefly: github.com's own + // address is given again as soon as it answers + const got = { rel: full, degraded: detoured(full) }; + remember(ctx, "latest", got, got.degraded ? BRIEF : TTL); remember(ctx, "latest-good", full, KEEP); return got; } @@ -474,16 +481,84 @@ async function fromAPI(env, path = "releases/latest") { } const gh = await res.json(); const tag = gh.tag_name; - const sums = await checksums(tag); - if (!sums) return null; + const listed = gh.assets.find((a) => a.name === "SHA256SUMS"); + const got = await checksums(tag, env, listed && listed.url); + if (!got) return null; const rel = { version: tag.replace(/^v/, ""), notes: gh.body || "", url: gh.html_url, published: gh.published_at, assets: {} }; for (const a of gh.assets) { if (a.name === "SHA256SUMS") continue; - rel.assets[a.name] = { url: a.browser_download_url, size: a.size, sha256: sums[a.name] || "" }; + // api: the file's address in GitHub's API, which an app asks when + // url is busy. With github.com's download address failing (504 for + // hours on 2026-11-08), url is the site's /dl, which redirects + // through the API: an app too old to know api follows it, and still + // checks the file against sha256. + const url = got.direct ? a.browser_download_url : `${SITE}/dl/${tag}/${encodeURIComponent(a.name)}`; + rel.assets[a.name] = { url, api: a.url, size: a.size, sha256: got.sums[a.name] || "" }; } return rel; } +// detoured: whether rel's files go by the site's /dl +function detoured(rel) { + return Object.values(rel.assets || {}).some((a) => a.url && a.url.startsWith(SITE + "/dl/")); +} + +// located is where GitHub's API sends an ask for a release file's bytes +// (Accept: application/octet-stream): a signed address on GitHub's asset +// host, good for some minutes, or null. The redirect is read, not +// followed, so no Authorization goes to the asset host. +async function located(apiURL, env) { + const headers = { ...UA, Accept: "application/octet-stream" }; + if (env && env.GITHUB_TOKEN) headers.Authorization = `Bearer ${env.GITHUB_TOKEN}`; + let res; + try { + res = await fetch(apiURL, { headers, redirect: "manual" }); + } catch (e) { + console.log("github asset", e); + return null; + } + const to = res.headers.get("Location") || ""; + let host = ""; + try { + host = new URL(to).hostname; + } catch {} + if (res.status < 300 || res.status > 399 || !to.startsWith("https://") || !(host.endsWith(".githubusercontent.com") || host === "github.com")) { + console.log("github asset", res.status, to.slice(0, 80)); + return null; + } + return to; +} + +// detour is /dl//: a redirect to the release's file by way of +// GitHub's API (located), for when github.com's download address fails. +// Where GitHub's API sends is kept five minutes, and each release's list +// of files an hour, so a worker IP's 60 anonymous asks an hour go far. +// The file is checked by whoever downloads it, against the feed's hash. +async function detour(ctx, env, tag, name) { + const key = `dl/${tag}/${name}`; + let to = await cached(key); + if (typeof to !== "string" || !to) { + let files = await cached(`dl-files/${tag}`); + if (!files || typeof files !== "object") { + let res = null; + try { + res = await api(`releases/tags/${tag}`, env); + } catch (e) { + console.log("github api", tag, e); + } + if (!res || !res.ok) return new Response("GitHub didn't say where the file is; try again in a minute\n", { status: 502, headers: NO_STORE }); + files = {}; + for (const a of (await res.json()).assets || []) files[a.name] = a.url; + remember(ctx, `dl-files/${tag}`, files, 3600); + } + if (!files[name]) return new Response("not found\n", { status: 404 }); + to = await located(files[name], env); + if (!to) return new Response("GitHub didn't hand out the file; try again in a minute\n", { status: 502, headers: NO_STORE }); + remember(ctx, key, to, 300); + } + return new Response(null, { status: 302, headers: { Location: to, ...NO_STORE } }); +} + async function fromPages() { let res; try { @@ -505,8 +580,9 @@ async function fromPages() { // date from entry ({notes, published}) where there is one: every file, its // size unknown (0). null when SHA256SUMS can't be read. async function fromSums(tag, entry) { - const sums = await checksums(tag); - if (!sums) return null; + const got = await checksums(tag); + if (!got) return null; + const sums = got.sums; const url = `https://github.com/${REPO}/releases/tag/${tag}`; const rel = { version: tag.replace(/^v/, ""), notes: entry ? entry.notes : "", url, published: entry ? entry.published : null, assets: {} }; for (const [name, sha256] of Object.entries(sums)) { @@ -645,7 +721,8 @@ async function stable(ctx, env, now) { const pick = stableOf(ix.list.map((r) => ({ version: r.v, published: r.p, urgent: !!r.u })), now); if (!pick) return null; const tag = "v" + pick.version; - let rel = await fromAPI(env, "releases/tags/" + tag), degraded = false; + let rel = await fromAPI(env, "releases/tags/" + tag); + let degraded = !!rel && detoured(rel); if (!rel) { // the API said no: the files from SHA256SUMS, the notes from the ledger const [entry] = await fromLedger(env, null, null, pick.version, 1); @@ -903,22 +980,35 @@ function newer(a, b) { return x.pre > y.pre; } -// checksums reads a release's SHA256SUMS: {file name: hash}. -async function checksums(tag) { - let r; +// checksums reads a release's SHA256SUMS: {sums: {file name: hash}, +// direct}, or null. direct says github.com's download address gave it; +// when that fails, viaAPI (the file's address in GitHub's API) is asked. +async function checksums(tag, env, viaAPI) { + let r = null; try { r = await fetch(`https://github.com/${REPO}/releases/download/${tag}/SHA256SUMS`, { headers: UA }); } catch (e) { console.log("SHA256SUMS", e); - return null; } - if (!r.ok) return null; + let direct = !!r && r.ok; + if (!direct) { + if (r) console.log("SHA256SUMS", r.status); + const to = viaAPI && (await located(viaAPI, env)); + if (!to) return null; + try { + r = await fetch(to, { headers: UA }); + } catch (e) { + console.log("SHA256SUMS through the API", e); + return null; + } + if (!r.ok) return null; + } const sums = {}; for (const line of (await r.text()).split("\n")) { const [hash, name] = line.trim().split(/\s+\*?/); if (hash && name) sums[name] = hash; } - return sums; + return { sums, direct }; } // ---- icons ------------------------------------------------------------------ diff --git a/site/worker.test.mjs b/site/worker.test.mjs index a550c65b4..c39d81d34 100644 --- a/site/worker.test.mjs +++ b/site/worker.test.mjs @@ -23,6 +23,9 @@ globalThis.caches = { // pagesDown for github.com itself failing too. seen keeps each API ask's // headers. let apiDown = false, pagesDown = false; +// downloadsDown: github.com's download address answering 504 while the +// API serves the same files (2026-11-08) +let downloadsDown = false; const seen = []; const FEED = ` @@ -69,11 +72,22 @@ globalThis.fetch = async (u, init = {}) => { if (u.startsWith("https://api.github.com/")) { seen.push(new Headers(init.headers)); if (apiDown) return new Response('{"message":"API rate limit exceeded"}', { status: 403 }); + const asset = u.match(/\/releases\/assets\/(\d+)$/); + if (asset) { + if (new Headers(init.headers).get("Accept") !== "application/octet-stream") return Response.json({ id: +asset[1] }); + return new Response(null, { status: 302, headers: { Location: `https://release-assets.githubusercontent.com/a/${asset[1]}?sig=1` } }); + } } else if (pagesDown) return new Response("unicorn", { status: 503 }); + if (downloadsDown && u.includes("/releases/download/")) return new Response("", { status: 504 }); + if (u === "https://release-assets.githubusercontent.com/a/2?sig=1") return new Response("abc magpie-linux-amd64\n"); if (u === "https://github.com/yetone/magpie-releases/releases/latest") return new Response(null, { status: 302, headers: { Location: "https://github.com/yetone/magpie-releases/releases/tag/v0.1.3" } }); if (u.endsWith("/releases.atom")) return new Response(FEED); - const gh = (tag) => ({ tag_name: tag, body: BODIES[tag], html_url: "https://github.com/r/" + tag, published_at: "2026-10-01T00:00:00Z", draft: false, prerelease: false, assets: [{ name: "magpie-linux-amd64", size: 1, browser_download_url: "https://dl/x" }] }); + const gh = (tag) => ({ tag_name: tag, body: BODIES[tag], html_url: "https://github.com/r/" + tag, published_at: "2026-10-01T00:00:00Z", draft: false, prerelease: false, assets: [ + { name: "magpie-linux-amd64", size: 1, browser_download_url: "https://dl/x", url: "https://api.github.com/repos/yetone/magpie-releases/releases/assets/1" }, + { name: "SHA256SUMS", size: 1, browser_download_url: "https://dl/sums", url: "https://api.github.com/repos/yetone/magpie-releases/releases/assets/2" }, + ] }); + if (u.endsWith("/releases/tags/v0.1.3")) return Response.json(gh("v0.1.3")); if (u.endsWith("/releases/latest")) return Response.json(gh("v0.1.3")); if (u.includes("/releases?per_page=")) return Response.json(Object.keys(BODIES).map(gh)); if (u.endsWith("/SHA256SUMS")) return new Response("abc magpie-linux-amd64\n"); @@ -710,3 +724,63 @@ test("seo: the home page's structured data parses and its title is in every lang assert.match(html, /[^<]{20,70}<\/title>/); for (const [l, { dict }] of Object.entries(LANGS)) assert.ok(dict["meta.title"].startsWith("magpie"), l); }); + +// 2026-11-08: github.com answered 504 for every release file for hours, +// while GitHub's API served the same ones. The feed then reads the +// checksums through the API and sends each file by the site's /dl, which +// an app too old to know the api field follows; it is kept a minute, so +// github.com's own address comes back as soon as it answers. +test("latest: github.com's downloads failing, the files go by /dl, through GitHub's API", async () => { + store.clear(); + downloadsDown = true; + try { + const res = await ask("/api/latest"); + assert.equal(res.status, 200); + assert.equal(res.headers.get("Cache-Control"), "public, max-age=60"); + const a = (await res.json()).assets["magpie-linux-amd64"]; + assert.deepEqual(a, { + url: "https://usemagpie.ai/dl/v0.1.3/magpie-linux-amd64", + api: "https://api.github.com/repos/yetone/magpie-releases/releases/assets/1", + size: 1, + sha256: "abc", + }); + seen.length = 0; + // each ask's writes to the edge's cache are waited for before the next + const pending = []; + const keeping = { waitUntil: (p) => void pending.push(p) }; + for (let i = 0; i < 2; i++) { + const dl = await worker.fetch(new Request("https://usemagpie.ai/dl/v0.1.3/magpie-linux-amd64"), {}, keeping); + await Promise.all(pending); + assert.equal(dl.status, 302); + assert.equal(dl.headers.get("Location"), "https://release-assets.githubusercontent.com/a/1?sig=1"); + assert.equal(dl.headers.get("Cache-Control"), "no-store"); + } + // the release's files once, where one is once: the second is the edge's + assert.equal(seen.length, 2); + assert.equal(seen[1].get("Accept"), "application/octet-stream"); + assert.equal((await ask("/dl/v0.1.3/magpie-nothing")).status, 404); + } finally { + downloadsDown = false; + } + // github.com answering again: its own address, and api beside it + store.clear(); + const res = await ask("/api/latest"); + assert.equal(res.headers.get("Cache-Control"), "public, max-age=300"); + const a = (await res.json()).assets["magpie-linux-amd64"]; + assert.equal(a.url, "https://dl/x"); + assert.equal(a.api, "https://api.github.com/repos/yetone/magpie-releases/releases/assets/1"); +}); + +test("dl: a redirect GitHub's API gives anywhere but its asset host is not passed on", async () => { + store.clear(); + const was = globalThis.fetch; + globalThis.fetch = async (u, init = {}) => + /\/releases\/assets\/\d+$/.test(String(u)) ? new Response(null, { status: 302, headers: { Location: "https://evil.example/x" } }) : was(u, init); + try { + const res = await ask("/dl/v0.1.3/magpie-linux-amd64"); + assert.equal(res.status, 502); + assert.equal(res.headers.get("Cache-Control"), "no-store"); + } finally { + globalThis.fetch = was; + } +});