diff --git a/docs/reference.md b/docs/reference.md index d37cdf446..3ed2741e0 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -3106,6 +3106,16 @@ 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. +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 +only with the SHA-256 the release's `SHA256SUMS` gives; the feed names R2 +only for a file it holds, and gives each file's github.com address beside it +(`github`). When the site's copy fails, the app, `magpie update` and the +installer go on to github.com's address, through your mirror when one is +set (a mirror is only ever put before a github.com address). A file R2 +doesn't hold (an older release) is redirected to github.com. + 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 diff --git a/site/files.js b/site/files.js new file mode 100644 index 000000000..9f3191115 --- /dev/null +++ b/site/files.js @@ -0,0 +1,193 @@ +// A release's files on R2 (the RELEASES bucket), GitHub behind them. +// +// github.com's download address can fail for hours (504 on every file, +// 2026-11-08), so the files the update feed and /download hand out are +// served from R2 here, at /files//. GitHub stays the source: +// the cron (mirror) copies the newest release and the Stable one from it +// into R2, and R2 takes a file only when its SHA-256 is the one the +// release's SHA256SUMS gives (put's sha256). A file R2 doesn't have, or +// can't give, is sent on to GitHub's own address (302), and the feed names +// R2 only for files it has with that hash, so nothing is ever only on R2. +// The app checks every file against the feed's hash wherever it came from. +// +// Each release is about 1 GB; the tags the feeds name and the KEEP newest +// besides are kept, the rest deleted (prune), and an older tag's files go +// to GitHub. + +const KEEP = 4; +// a cron run starts no new copy after this long, so the next run (five +// minutes on) doesn't copy the same file beside it +const BUDGET = 4 * 60e3; + +export function githubFile(repo, tag, name) { + return `https://github.com/${repo}/releases/download/${tag}/${name}`; +} + +// serve answers GET and HEAD for /files// from R2, a Range +// included, and sends anything R2 can't give to GitHub. +export async function serve(req, env, repo, tag, name) { + const toGitHub = () => new Response(null, { status: 302, headers: { Location: githubFile(repo, tag, name), "Cache-Control": "no-store" } }); + if (req.method !== "GET" && req.method !== "HEAD") return new Response("method not allowed\n", { status: 405, headers: { Allow: "GET, HEAD" } }); + if (!env.RELEASES) return toGitHub(); + const key = `${tag}/${name}`; + let obj = null; + try { + obj = req.method === "HEAD" ? await env.RELEASES.head(key) : await env.RELEASES.get(key, { range: req.headers, onlyIf: req.headers }); + } catch (e) { + // a Range R2 refuses, or R2 failing: GitHub answers it its own way + console.log("r2 get", key, String(e)); + return toGitHub(); + } + if (!obj) return toGitHub(); + const headers = new Headers(); + obj.writeHttpMetadata(headers); + headers.set("ETag", obj.httpEtag); + headers.set("Accept-Ranges", "bytes"); + // a tag's file never changes + headers.set("Cache-Control", "public, max-age=31536000, immutable"); + if (req.method === "HEAD") { + headers.set("Content-Length", String(obj.size)); + return new Response(null, { status: 200, headers }); + } + // onlyIf not met: the object comes without its body + if (!("body" in obj) || !obj.body) return new Response(null, { status: req.headers.has("If-None-Match") ? 304 : 412, headers }); + const r = obj.range; + if (req.headers.has("Range") && r) { + const start = "suffix" in r ? Math.max(0, obj.size - r.suffix) : r.offset || 0; + const length = "suffix" in r ? obj.size - start : r.length ?? obj.size - start; + headers.set("Content-Range", `bytes ${start}-${start + length - 1}/${obj.size}`); + headers.set("Content-Length", String(length)); + return new Response(obj.body, { status: 206, headers }); + } + headers.set("Content-Length", String(obj.size)); + return new Response(obj.body, { status: 200, headers }); +} + +// held is what R2 has of tag: {name: sha256}, the hash each was put with. +// null when R2 can't say. +export async function held(env, tag) { + if (!env.RELEASES) return null; + const out = {}; + let cursor; + try { + do { + const page = await env.RELEASES.list({ prefix: tag + "/", cursor, include: ["customMetadata"] }); + for (const o of page.objects) out[o.key.slice(tag.length + 1)] = (o.customMetadata && o.customMetadata.sha256) || ""; + cursor = page.truncated ? page.cursor : undefined; + } while (cursor); + } catch (e) { + console.log("r2 list", tag, String(e)); + return null; + } + return out; +} + +// onR2 is rel with each file R2 holds, with the hash rel gives, at +// site/files//; every file also says its github.com address +// (github), which the app takes when the site's fails. have is held's. +export function onR2(rel, have, repo, site) { + if (!rel || !rel.assets) return rel; + const tag = "v" + rel.version; + const assets = {}; + for (const [name, a] of Object.entries(rel.assets)) { + const github = githubFile(repo, tag, name); + const there = have && a.sha256 && have[name] === a.sha256; + assets[name] = there ? { ...a, url: `${site}/files/${tag}/${encodeURIComponent(name)}`, github } : { ...a, github }; + } + return { ...rel, assets }; +} + +// mirror copies into R2 each file of rels (the feeds' releases, with +// their hashes) it doesn't hold yet, then prunes. open(name, asset, tag) +// is the file's bytes from GitHub (a Response), null when GitHub won't +// give them. Returns {copied, failed}. +export async function mirror(env, rels, open, now = Date.now) { + const done = { copied: [], failed: [] }; + if (!env.RELEASES) return done; + const until = now() + BUDGET; + const tags = []; + for (const rel of rels) { + if (!rel || !rel.version || !rel.assets) continue; + const tag = "v" + rel.version; + if (tags.includes(tag)) continue; + tags.push(tag); + const have = await held(env, tag); + if (!have) continue; + for (const [name, a] of Object.entries(rel.assets)) { + if (!a.sha256 || have[name] === a.sha256) continue; + if (now() > until) return done; + if (await copy(env, tag, name, a, open)) done.copied.push(`${tag}/${name}`); + else done.failed.push(`${tag}/${name}`); + } + } + await prune(env, tags); + return done; +} + +async function copy(env, tag, name, a, open) { + let res = null; + try { + res = await open(name, a, tag); + } catch (e) { + console.log("r2 copy: github", tag, name, String(e)); + } + if (!res || !res.ok || !res.body) { + console.log("r2 copy: github", tag, name, res && res.status); + return false; + } + // R2 takes a stream of a known length: GitHub's own, or the feed's size + const length = Number(res.headers.get("Content-Length")) || a.size || 0; + let body = res.body; + if (length > 0 && typeof FixedLengthStream === "function") { + const fixed = new FixedLengthStream(length); + res.body.pipeTo(fixed.writable).catch(() => {}); + body = fixed.readable; + } + try { + await env.RELEASES.put(`${tag}/${name}`, body, { + sha256: a.sha256, + httpMetadata: { contentType: "application/octet-stream", contentDisposition: `attachment; filename="${name}"` }, + customMetadata: { sha256: a.sha256 }, + }); + return true; + } catch (e) { + // a hash that isn't the release's is refused here, and nothing kept + console.log("r2 copy: put", tag, name, String(e)); + return false; + } +} + +// prune deletes every tag but keep and the KEEP newest besides. +async function prune(env, keep) { + let tags = [], cursor; + try { + do { + const page = await env.RELEASES.list({ delimiter: "/", cursor }); + tags.push(...page.delimitedPrefixes.map((p) => p.replace(/\/$/, ""))); + cursor = page.truncated ? page.cursor : undefined; + } while (cursor); + } catch (e) { + console.log("r2 prune: list", String(e)); + return; + } + const rest = tags.filter((t) => !keep.includes(t)).sort((a, b) => byVersion(b, a)); + for (const tag of rest.slice(KEEP)) { + const have = await held(env, tag); + if (!have) continue; + const keys = Object.keys(have).map((n) => `${tag}/${n}`); + try { + if (keys.length) await env.RELEASES.delete(keys); + } catch (e) { + console.log("r2 prune: delete", tag, String(e)); + } + } +} + +function byVersion(a, b) { + const pa = a.replace(/^v/, "").split(".").map(Number), pb = b.replace(/^v/, "").split(".").map(Number); + for (let i = 0; i < Math.max(pa.length, pb.length); i++) { + const d = (pa[i] || 0) - (pb[i] || 0); + if (d) return d; + } + return 0; +} diff --git a/site/files.test.mjs b/site/files.test.mjs new file mode 100644 index 000000000..431b61261 --- /dev/null +++ b/site/files.test.mjs @@ -0,0 +1,144 @@ +// node --test site/: a release's files from R2, GitHub behind them +// (files.js). R2 is stood in for by r2stub.mjs. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { serve, onR2, mirror, held } from "./files.js"; +import { bucket, sha, hold } from "./r2stub.mjs"; + +const REPO = "yetone/magpie-releases"; +const GH = (tag, name) => `https://github.com/${REPO}/releases/download/${tag}/${name}`; +const ask = (env, path, headers = {}, method = "GET") => { + const [, , tag, name] = path.split("/"); + return serve(new Request("https://usemagpie.ai" + path, { method, headers }), env, REPO, tag, name); +}; + +test("files: R2's file whole, a Range of it, its HEAD, and a 304 for its own ETag", async () => { + const env = { RELEASES: bucket() }; + await hold(env.RELEASES, "v0.1.3", "magpie-linux-amd64", "0123456789"); + let res = await ask(env, "/files/v0.1.3/magpie-linux-amd64"); + assert.equal(res.status, 200); + assert.equal(await res.text(), "0123456789"); + assert.equal(res.headers.get("Content-Length"), "10"); + assert.equal(res.headers.get("Accept-Ranges"), "bytes"); + assert.equal(res.headers.get("Content-Type"), "application/octet-stream"); + assert.match(res.headers.get("Cache-Control"), /immutable/); + const etag = res.headers.get("ETag"); + + // the app asks on from what an earlier try kept + res = await ask(env, "/files/v0.1.3/magpie-linux-amd64", { Range: "bytes=4-" }); + assert.equal(res.status, 206); + assert.equal(await res.text(), "456789"); + assert.equal(res.headers.get("Content-Range"), "bytes 4-9/10"); + assert.equal(res.headers.get("Content-Length"), "6"); + res = await ask(env, "/files/v0.1.3/magpie-linux-amd64", { Range: "bytes=2-3" }); + assert.equal(res.headers.get("Content-Range"), "bytes 2-3/10"); + assert.equal(await res.text(), "23"); + res = await ask(env, "/files/v0.1.3/magpie-linux-amd64", { Range: "bytes=-3" }); + assert.equal(res.headers.get("Content-Range"), "bytes 7-9/10"); + assert.equal(await res.text(), "789"); + + res = await ask(env, "/files/v0.1.3/magpie-linux-amd64", {}, "HEAD"); + assert.equal(res.status, 200); + assert.equal(res.headers.get("Content-Length"), "10"); + res = await ask(env, "/files/v0.1.3/magpie-linux-amd64", { "If-None-Match": etag }); + assert.equal(res.status, 304); + assert.equal((await ask(env, "/files/v0.1.3/magpie-linux-amd64", {}, "POST")).status, 405); +}); + +test("files: what R2 hasn't got, can't give, or isn't bound goes to GitHub's own address", async () => { + const env = { RELEASES: bucket() }; + await hold(env.RELEASES, "v0.1.3", "magpie-linux-amd64", "0123456789"); + const toGitHub = async (env, path, headers) => { + const res = await ask(env, path, headers); + assert.equal(res.status, 302, path); + assert.equal(res.headers.get("Location"), GH(...path.split("/").slice(2))); + assert.equal(res.headers.get("Cache-Control"), "no-store"); + }; + await toGitHub(env, "/files/v0.1.2/magpie-linux-amd64"); + await toGitHub(env, "/files/v0.1.3/magpie-linux-arm64"); + // a Range past the end: GitHub answers it its own way + await toGitHub(env, "/files/v0.1.3/magpie-linux-amd64", { Range: "bytes=99-" }); + await toGitHub({}, "/files/v0.1.3/magpie-linux-amd64"); + env.RELEASES.fail = true; + await toGitHub(env, "/files/v0.1.3/magpie-linux-amd64"); +}); + +test("feed: a file R2 holds with the release's hash is at /files, every file says its github.com address", () => { + const rel = { version: "0.1.3", assets: { + a: { url: GH("v0.1.3", "a"), api: "https://api/1", size: 1, sha256: sha("A") }, + b: { url: GH("v0.1.3", "b"), size: 1, sha256: sha("B") }, + c: { url: GH("v0.1.3", "c"), size: 1, sha256: sha("C") }, + } }; + // b holds other bytes than the release says, c isn't there + const got = onR2(rel, { a: sha("A"), b: sha("other") }, REPO, "https://usemagpie.ai"); + assert.deepEqual(got.assets.a, { url: "https://usemagpie.ai/files/v0.1.3/a", api: "https://api/1", size: 1, sha256: sha("A"), github: GH("v0.1.3", "a") }); + assert.equal(got.assets.b.url, GH("v0.1.3", "b")); + assert.equal(got.assets.b.github, GH("v0.1.3", "b")); + assert.equal(got.assets.c.url, GH("v0.1.3", "c")); + // R2 unknown: GitHub for all + assert.equal(onR2(rel, null, REPO, "https://usemagpie.ai").assets.a.url, GH("v0.1.3", "a")); + // rel itself untouched (it is the cached feed) + assert.equal(rel.assets.a.url, GH("v0.1.3", "a")); +}); + +test("mirror: a release's files are copied once, and bytes that aren't the release's are not kept", async () => { + const env = { RELEASES: bucket() }; + const bodies = { a: "AAAA", b: "BBBB", c: "tampered" }; + const opened = []; + const open = async (name) => { + opened.push(name); + return name === "gone" ? new Response("", { status: 504 }) : new Response(bodies[name], { headers: { "Content-Length": String(bodies[name].length) } }); + }; + const rel = { version: "0.1.3", assets: { + a: { size: 4, sha256: sha("AAAA") }, + b: { size: 4, sha256: sha("BBBB") }, + c: { size: 8, sha256: sha("CCCC") }, + gone: { size: 1, sha256: sha("G") }, + nohash: { size: 1, sha256: "" }, + } }; + let done = await mirror(env, [rel, rel], open); + assert.deepEqual(done.copied.sort(), ["v0.1.3/a", "v0.1.3/b"]); + assert.deepEqual(done.failed.sort(), ["v0.1.3/c", "v0.1.3/gone"]); + assert.deepEqual(Object.keys(await held(env, "v0.1.3")).sort(), ["a", "b"]); + // the same release again: only what isn't held yet is asked for + opened.length = 0; + done = await mirror(env, [rel], open); + assert.deepEqual(opened.sort(), ["c", "gone"]); + assert.deepEqual(done.copied, []); +}); + +test("mirror: stops starting copies after its budget, so the next run doesn't copy beside it", async () => { + const env = { RELEASES: bucket() }; + let t = 0; + const open = async (name) => { + t += 3 * 60e3; + return new Response(name); + }; + const rel = { version: "0.1.3", assets: { a: { sha256: sha("a") }, b: { sha256: sha("b") }, c: { sha256: sha("c") } } }; + const done = await mirror(env, [rel], open, () => t); + assert.deepEqual(done.copied, ["v0.1.3/a", "v0.1.3/b"]); +}); + +test("mirror: the tags the feeds name and the four newest besides are kept, older ones deleted", async () => { + const env = { RELEASES: bucket() }; + for (const v of ["0.1.2", "0.1.9", "0.1.10", "0.1.11", "0.1.12", "0.1.13", "0.1.14"]) { + await hold(env.RELEASES, "v" + v, "x", v); + await hold(env.RELEASES, "v" + v, "y", v + "y"); + } + // the newest (0.1.15) and Stable (0.1.2) + const rels = [ + { version: "0.1.15", assets: { x: { sha256: sha("new") } } }, + { version: "0.1.2", assets: { x: { sha256: sha("0.1.2") } } }, + ]; + await mirror(env, rels, async () => new Response("new")); + const tags = [...new Set([...env.RELEASES.objs.keys()].map((k) => k.split("/")[0]))].sort(); + assert.deepEqual(tags, ["v0.1.11", "v0.1.12", "v0.1.13", "v0.1.14", "v0.1.15", "v0.1.2"]); + assert.ok(env.RELEASES.objs.has("v0.1.11/y")); +}); + +test("mirror: without the bucket, or with R2 failing, nothing is copied and nothing throws", async () => { + assert.deepEqual(await mirror({}, [{ version: "1", assets: { a: { sha256: "x" } } }], async () => new Response("a")), { copied: [], failed: [] }); + const env = { RELEASES: bucket() }; + env.RELEASES.fail = true; + assert.deepEqual(await mirror(env, [{ version: "1", assets: { a: { sha256: "x" } } }], async () => new Response("a")), { copied: [], failed: [] }); +}); diff --git a/site/public/docs/ja/privacy.html b/site/public/docs/ja/privacy.html index 71872fa77..8424b78c2 100644 --- a/site/public/docs/ja/privacy.html +++ b/site/public/docs/ja/privacy.html @@ -178,6 +178,7 @@

magpie はプライバシー設定にかかわらず、どのアプリも自分の更新サーバーに尋ねるのと同じように、自分のサイトにいくつか尋ねます。どのリクエストにもインストール ID やアカウントは付きません。

  • /api/latest:更新情報。noAutoUpdate がオンでなければ 6 時間ごと。?lang= であなたの言語のノートを取ります。設定 → 情報 → アップデートチャネルが安定版なら ?channel=stable も付けます。どちらもあなたが誰かは含みません。/api/notes は更新後の「新機能」です。
  • +
  • /files/<バージョン>/<ファイル>:更新とインストーラがダウンロードするリリースファイルで、Cloudflare R2 から配信されます。サイトにないファイルは github.com へ転送されます。何も計測しません。
  • /api/partners:プロバイダー追加シートのパートナー一覧。6 時間ごと。パートナーが載っている間、10 回に 1 回の取得を Cloudflare が示す国とともに magpie partners fetch として数えます。
  • /go/<パートナー>/site と /go/<パートナー>/keys:パートナーの公式サイトとキーのページへのリンクをブラウザーで開くと、移動の前に magpie partner go(どのパートナーか、どのリンクか、地域、国)として数えます。
  • /api/icon?url=…:プラグイン、インポートリンク、ライブラリが示すアイコンはここを経由して取得するので、アイコンのあるホストに見えるのはあなたではなく Cloudflare のアドレスです。画像を中継するだけで、数えることも記録することもしません。
  • diff --git a/site/public/docs/ja/start.html b/site/public/docs/ja/start.html index 9eee16663..13265b4f2 100644 --- a/site/public/docs/ja/start.html +++ b/site/public/docs/ja/start.html @@ -293,7 +293,7 @@ magpie claude group/opus-anywhere # これを使う

    エージェントの設定を手で編集すると、何か壊れますか?

    いいえ。magpie は毎回ファイルを読み直し、自分が設定するキーだけに触れるので、他の設定やコメントはそのまま残ります。Import… で取り込んだプロバイダはコピーなので、その後エージェント側の設定を変えても再度コピーはされません。

    GitHub に届かない環境で、インストールや更新をするには?

    -

    インストーラと magpie update にプロキシを渡します:curl -fsSL https://usemagpie.ai/install.sh | sh -s -- --proxy http://127.0.0.1:7890、または magpie update --proxy socks5://127.0.0.1:1080(http・https・socks5・socks5h に対応。HTTPS_PROXY と ALL_PROXY も使われます)。--mirror <prefix> を付けると、指定した GitHub ダウンロードミラーから <prefix>https://github.com/… としてリリースファイルを取得します。magpie update mirror <prefix> でアプリ自身の更新を含め毎回使い、magpie update mirror off で解除します。指定しない限りミラーは使われず、ファイルの SHA-256 はミラーではなく常に usemagpie.ai から取得するので、ミラーが書き換えたファイルはインストールされません。アプリ自身の更新は Settings → Proxy を通ります。

    +

    インストーラと magpie update にプロキシを渡します:curl -fsSL https://usemagpie.ai/install.sh | sh -s -- --proxy http://127.0.0.1:7890、または magpie update --proxy socks5://127.0.0.1:1080(http・https・socks5・socks5h に対応。HTTPS_PROXY と ALL_PROXY も使われます)。リリースファイルは usemagpie.ai(Cloudflare R2)から取得し、失敗したときは github.com から取得します。--mirror <prefix> を付けると、サイトからの取得に失敗したとき、指定した GitHub ダウンロードミラーから <prefix>https://github.com/… としてリリースファイルを取得します。magpie update mirror <prefix> でアプリ自身の更新を含め毎回使い、magpie update mirror off で解除します。指定しない限りミラーは使われず、ファイルの SHA-256 はミラーではなく常に usemagpie.ai から取得するので、ミラーが書き換えたファイルはインストールされません。アプリ自身の更新は Settings → Proxy を通ります。

    Linux ではインストーラはどのビルドを入れますか?

    GTK 3 と WebKitGTK 4.1 が入っていればデスクトップアプリ(ウィンドウ、トレイアイコン、アプリメニューの項目)です。デスクトップがあってもそれらが無いときは、パッケージマネージャー(apt、dnf、pacman、zypper)で sudo を通して WebKitGTK 4.1 を入れ(sudo がパスワードを尋ねます)、それからアプリを入れます。パスワードを尋ねる前に何を入れるかを表示します。端末が無いとき(CI、Dockerfile)、sudo が無いとき、知らないディストリビューションやインストールに失敗したときはターミナル版(magpie tui、magpie web と CLI)を入れ、最後に入れるコマンドを表示します。Debian・Ubuntu なら sudo apt install libwebkit2gtk-4.1-0、Fedora なら sudo dnf install webkit2gtk4.1 です。入れたあとインストーラをもう一度実行するとアプリになります。デスクトップ上で実行しても ssh 越しでも、グラフィカルなセッション、あなたのグラフィカルなログイン、ログインできるデスクトップ環境のどれかがあればデスクトップありと判断します。デスクトップの無いサーバーにはターミナル版です。自分で選ぶには --gui(ライブラリを今入れられなくてもアプリ)か --tui(ターミナル版、パッケージは入れない)を付けます:curl -fsSL https://usemagpie.ai/install.sh | sh -s -- --tui。

    diff --git a/site/public/docs/privacy.html b/site/public/docs/privacy.html index 495dc6618..20406ead9 100644 --- a/site/public/docs/privacy.html +++ b/site/public/docs/privacy.html @@ -178,6 +178,7 @@

    magpie asks its own site for a few things, whatever the privacy settings say, as any app asks its update server. None of these requests carries the install id or an account.

    • /api/latest: the update feed, every 6 hours unless noAutoUpdate is on, with ?lang= for the notes in your language, and ?channel=stable when Settings → About → Update channel is Stable. Neither says who you are. /api/notes gives What’s new after an update.
    • +
    • /files/<version>/<file>: the release files an update and the installer download, served from Cloudflare R2. A file the site doesn’t hold is sent on to github.com. Nothing is counted.
    • /api/partners: the add sheet’s partner list, every 6 hours. One fetch in ten is counted as a magpie partners fetch event, with the country Cloudflare gives, while a partner is listed.
    • /go/<partner>/site and /go/<partner>/keys: a partner’s website and key-page links, opened in your browser, are counted (the partner, which link, a region, a country) as magpie partner go before you are sent on.
    • /api/icon?url=…: icons named by a plugin, an import link or the library are fetched through it, so their hosts see Cloudflare’s address, not yours. The worker passes the picture on and counts and keeps nothing.
    • diff --git a/site/public/docs/start.html b/site/public/docs/start.html index b22303dc1..52f0eef2b 100644 --- a/site/public/docs/start.html +++ b/site/public/docs/start.html @@ -293,7 +293,7 @@ magpie claude group/opus-anywhere # use it

      Does editing the agent’s config by hand break anything?

      No. magpie reads the files each time and touches only the keys it sets, so your other settings and comments stay. Providers brought over with Import… are copies: later changes in the agent’s settings aren’t copied again.

      Installing or updating behind a firewall, or without access to GitHub?

      -

      Give the installer and magpie update a proxy: curl -fsSL https://usemagpie.ai/install.sh | sh -s -- --proxy http://127.0.0.1:7890, or magpie update --proxy socks5://127.0.0.1:1080 (http, https, socks5 and socks5h; HTTPS_PROXY and ALL_PROXY are honoured too). --mirror <prefix> fetches the release file from a GitHub download mirror you choose, as <prefix>https://github.com/…; magpie update mirror <prefix> keeps it for every update, the app’s too, and magpie update mirror off removes it. No mirror is used unless you give one, and the file’s SHA-256 still comes from usemagpie.ai, never from the mirror: a file the mirror changed is refused. The app’s own updates go through Settings → Proxy.

      +

      Give the installer and magpie update a proxy: curl -fsSL https://usemagpie.ai/install.sh | sh -s -- --proxy http://127.0.0.1:7890, or magpie update --proxy socks5://127.0.0.1:1080 (http, https, socks5 and socks5h; HTTPS_PROXY and ALL_PROXY are honoured too). Release files come from usemagpie.ai (Cloudflare R2), and from github.com when that fails. --mirror <prefix> fetches the release file from a GitHub download mirror you choose, as <prefix>https://github.com/…, when the site’s copy fails; magpie update mirror <prefix> keeps it for every update, the app’s too, and magpie update mirror off removes it. No mirror is used unless you give one, and the file’s SHA-256 still comes from usemagpie.ai, never from the mirror: a file the mirror changed is refused. The app’s own updates go through Settings → Proxy.

      Which build does the installer put on Linux?

      The desktop app (window, tray icon and a menu entry) when GTK 3 and WebKitGTK 4.1 are installed. On a computer with a desktop but without them, the installer installs WebKitGTK 4.1 with your package manager (apt, dnf, pacman or zypper), through sudo, which asks for your password, and then the app; it says what it installs before it asks. Run without a terminal (CI, a Dockerfile), without sudo, on another distribution or when that install fails, it installs the terminal build (magpie tui, magpie web and the CLI) and ends with the command that installs them, such as sudo apt install libwebkit2gtk-4.1-0 on Debian and Ubuntu or sudo dnf install webkit2gtk4.1 on Fedora; run the installer again afterwards for the app. A desktop counts whether you run it there or over ssh: a graphical session, your graphical login, or a desktop installed to log in to. A server without one gets the terminal build. To choose yourself, add --gui (the app even when its libraries can't be installed now) or --tui (the terminal build, and no package installed): curl -fsSL https://usemagpie.ai/install.sh | sh -s -- --tui.

      diff --git a/site/public/docs/zh/privacy.html b/site/public/docs/zh/privacy.html index bcd59edd8..f7d6a17c4 100644 --- a/site/public/docs/zh/privacy.html +++ b/site/public/docs/zh/privacy.html @@ -178,6 +178,7 @@

      magpie 会向自己的网站请求几样东西,不受隐私设置影响,就像任何应用访问自己的更新服务器。这些请求都不带安装 ID 或账号。

      • /api/latest:更新信息,每 6 小时一次(开了 noAutoUpdate 则不请求),带 ?lang= 取对应语言的说明;设置 → 关于 → 更新渠道选了稳定版时还带 ?channel=stable。两者都不含你是谁。/api/notes 在更新后给出“新功能”。
      • +
      • /files/<版本>/<文件>:更新和安装脚本下载的发布文件,由 Cloudflare R2 提供;站点上没有的文件会转到 github.com。不做任何统计。
      • /api/partners:添加供应商页的合作伙伴列表,每 6 小时一次。在有合作伙伴上架时,每十次拉取记一次 magpie partners fetch 事件,附 Cloudflare 给出的国家。
      • /go/<合作伙伴>/site 和 /go/<合作伙伴>/keys:在浏览器里打开合作伙伴的官网和 Key 页面链接时,先记一次 magpie partner go(哪个合作伙伴、哪个链接、地区、国家),再跳转。
      • /api/icon?url=…:插件、导入链接和库里的图标经它获取,图标所在的服务器只看到 Cloudflare 的地址,看不到你的。它只转发图片,不计数也不记录。
      • diff --git a/site/public/docs/zh/start.html b/site/public/docs/zh/start.html index ead285ed3..6be61380f 100644 --- a/site/public/docs/zh/start.html +++ b/site/public/docs/zh/start.html @@ -293,7 +293,7 @@ magpie claude group/opus-anywhere # 使用它

        手动改 Agent 的配置会冲突吗?

        不会。magpie 每次都重新读取文件,只动它设置的那几个键,你的其他设置和注释都会保留。用 导入… 带进来的供应商是一份拷贝:之后在 Agent 里的改动不会再同步过来。

        没有梯子,安装或更新连不上 GitHub 怎么办?

        -

        给安装脚本和 magpie update 加代理:curl -fsSL https://usemagpie.ai/install.sh | sh -s -- --proxy http://127.0.0.1:7890,或 magpie update --proxy socks5://127.0.0.1:1080(支持 http、https、socks5、socks5h;环境变量 HTTPS_PROXY、ALL_PROXY 同样生效)。--mirror <前缀> 从你指定的 GitHub 下载镜像取发布文件,即 <前缀>https://github.com/…;magpie update mirror <前缀> 让之后每次更新(包括应用自己的更新)都用它,magpie update mirror off 取消。不指定就不用任何镜像;文件的 SHA-256 始终来自 usemagpie.ai,而不是镜像,镜像改过的文件会被拒绝安装。应用自己的更新走 设置 → 代理。

        +

        给安装脚本和 magpie update 加代理:curl -fsSL https://usemagpie.ai/install.sh | sh -s -- --proxy http://127.0.0.1:7890,或 magpie update --proxy socks5://127.0.0.1:1080(支持 http、https、socks5、socks5h;环境变量 HTTPS_PROXY、ALL_PROXY 同样生效)。发布文件从 usemagpie.ai(Cloudflare R2)下载,失败时改从 github.com 下载。--mirror <前缀> 在站点下载失败时从你指定的 GitHub 下载镜像取发布文件,即 <前缀>https://github.com/…;magpie update mirror <前缀> 让之后每次更新(包括应用自己的更新)都用它,magpie update mirror off 取消。不指定就不用任何镜像;文件的 SHA-256 始终来自 usemagpie.ai,而不是镜像,镜像改过的文件会被拒绝安装。应用自己的更新走 设置 → 代理。

        Linux 上安装脚本装的是哪个版本?

        装了 GTK 3 和 WebKitGTK 4.1 时装桌面版(窗口、托盘图标和应用菜单项)。有桌面但缺这两个库时,脚本会用系统的包管理器(apt、dnf、pacman 或 zypper)通过 sudo 装上 WebKitGTK 4.1(sudo 会要你的密码),再装桌面版;要密码之前会先说要装什么。没有终端(CI、Dockerfile)、没有 sudo、发行版不认识或者装库失败时,先装终端版(magpie tui、magpie web 和命令行),最后给出装库的命令,比如 Debian、Ubuntu 上是 sudo apt install libwebkit2gtk-4.1-0,Fedora 上是 sudo dnf install webkit2gtk4.1;装好后再运行一次安装脚本就换成桌面版。在桌面上运行还是 ssh 进去运行都算有桌面:有图形会话、你登录着图形界面,或者装了可登录的桌面环境。没有桌面的服务器装终端版。想自己选,加 --gui(库现在装不上也装桌面版)或 --tui(装终端版,不装任何系统包):curl -fsSL https://usemagpie.ai/install.sh | sh -s -- --tui。

        diff --git a/site/r2stub.mjs b/site/r2stub.mjs new file mode 100644 index 000000000..a89a091e3 --- /dev/null +++ b/site/r2stub.mjs @@ -0,0 +1,91 @@ +// An R2 bucket binding for the tests: what files.js asks of R2 (get with +// range and onlyIf, head, put with sha256, list with prefix, delimiter +// and include, delete), kept in memory. put refuses a body whose SHA-256 +// isn't the one given, as R2 does. fail makes every call throw. +import { createHash } from "node:crypto"; + +export function bucket() { + const objs = new Map(); + const b = { + objs, + fail: false, + puts: 0, + check() { + if (b.fail) throw new Error("R2 is down"); + }, + view(key, o, body, range) { + return { + key, + size: o.bytes.length, + httpEtag: `"${o.sha256.slice(0, 8)}"`, + customMetadata: o.customMetadata, + writeHttpMetadata(h) { + if (o.httpMetadata.contentType) h.set("Content-Type", o.httpMetadata.contentType); + if (o.httpMetadata.contentDisposition) h.set("Content-Disposition", o.httpMetadata.contentDisposition); + }, + ...(body === undefined ? {} : { body, range }), + }; + }, + async head(key) { + b.check(); + const o = objs.get(key); + return o ? b.view(key, o) : null; + }, + async get(key, opts = {}) { + b.check(); + const o = objs.get(key); + if (!o) return null; + const h = opts.onlyIf instanceof Headers ? opts.onlyIf : new Headers(); + if (h.get("If-None-Match") === `"${o.sha256.slice(0, 8)}"`) return b.view(key, o); + const rh = opts.range instanceof Headers ? opts.range.get("Range") : null; + if (!rh) return b.view(key, o, new Blob([o.bytes]).stream(), undefined); + const m = rh.match(/^bytes=(\d*)-(\d*)$/); + if (!m || (m[1] === "" && m[2] === "")) throw new Error("bad range"); + let range, start, end; + if (m[1] === "") { + range = { suffix: +m[2] }; + start = Math.max(0, o.bytes.length - +m[2]); + end = o.bytes.length; + } else { + start = +m[1]; + if (start >= o.bytes.length) throw new Error("range not satisfiable"); + end = m[2] === "" ? o.bytes.length : Math.min(o.bytes.length, +m[2] + 1); + range = { offset: start, length: end - start }; + } + return b.view(key, o, new Blob([o.bytes.slice(start, end)]).stream(), range); + }, + async put(key, body, opts = {}) { + b.check(); + b.puts++; + const bytes = new Uint8Array(await new Response(body).arrayBuffer()); + const sha256 = createHash("sha256").update(bytes).digest("hex"); + if (opts.sha256 && opts.sha256 !== sha256) throw new Error(`put: The SHA-256 checksum you specified did not match what we received`); + objs.set(key, { bytes, sha256, httpMetadata: opts.httpMetadata || {}, customMetadata: opts.customMetadata || {} }); + return b.view(key, objs.get(key)); + }, + async list(opts = {}) { + b.check(); + const prefix = opts.prefix || ""; + const keys = [...objs.keys()].filter((k) => k.startsWith(prefix)).sort(); + if (opts.delimiter) { + const pre = new Set(keys.map((k) => k.slice(prefix.length)).filter((k) => k.includes(opts.delimiter)).map((k) => prefix + k.split(opts.delimiter)[0] + opts.delimiter)); + return { objects: [], delimitedPrefixes: [...pre], truncated: false }; + } + return { objects: keys.map((k) => b.view(k, objs.get(k))), delimitedPrefixes: [], truncated: false }; + }, + async delete(keys) { + b.check(); + for (const k of [].concat(keys)) objs.delete(k); + }, + }; + return b; +} + +export function sha(s) { + return createHash("sha256").update(s).digest("hex"); +} + +// hold puts body at tag/name, as the cron would have +export async function hold(b, tag, name, body) { + await b.put(`${tag}/${name}`, body, { sha256: sha(body), httpMetadata: { contentType: "application/octet-stream" }, customMetadata: { sha256: sha(body) } }); +} diff --git a/site/worker.js b/site/worker.js index aca3601b8..4a69c01a1 100644 --- a/site/worker.js +++ b/site/worker.js @@ -1,6 +1,7 @@ // usemagpie.ai. Releases live on GitHub (yetone/magpie-releases); this // worker turns the newest one into the update feed the app reads and into -// download links that never go stale. +// download links that never go stale, and serves their files from R2, +// copied there from GitHub (files.js). // // /api/latest {version, notes, url, published, assets: {name: {url, api, size, sha256}}} // /api/latest?channel=stable @@ -32,6 +33,9 @@ // /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 +// /files// a release's file from R2 (files.js), the feed's +// url and /download's for the files R2 holds; +// GitHub's own address for any it doesn't // /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 @@ -48,6 +52,7 @@ import { LANGS } from "./i18n.js"; import { PARTNERS } from "./partners.js"; import { SPONSORS } from "./sponsors.js"; +import { serve as serveFile, held, onR2, mirror, githubFile } from "./files.js"; const REPO = "yetone/magpie-releases"; const SITE = "https://usemagpie.ai"; @@ -87,11 +92,11 @@ export default { if (url.searchParams.get("channel") === "stable") { const got = await stable(ctx, env, Date.now()); if (!got) return json({ error: "the stable version isn't known yet" }, 503, NO_STORE); - return json({ ...got.rel, notes: inLang(got.rel.notes, lang) }, 200, cacheFor(got)); + return json({ ...(await fromR2(ctx, env, got.rel)), notes: inLang(got.rel.notes, lang) }, 200, cacheFor(got)); } const got = await latest(ctx, env); if (!got) return json({ error: "no release yet" }, 503, NO_STORE); - return json({ ...got.rel, notes: inLang(got.rel.notes, lang) }, 200, cacheFor(got)); + return json({ ...(await fromR2(ctx, env, got.rel)), notes: inLang(got.rel.notes, lang) }, 200, cacheFor(got)); } if (url.pathname === "/api/partners") { const now = Date.now(); @@ -130,13 +135,16 @@ export default { return json({ releases: pick }, 200, cacheFor(got)); } if (url.pathname === "/api/icon") return icon(url.searchParams.get("url")); + const file = url.pathname.match(/^\/files\/(v[0-9][0-9A-Za-z.+-]*)\/([0-9A-Za-z._+-]+)$/); + if (file) return serveFile(req, env, REPO, file[1], file[2]); 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"; const got = await latest(ctx, env); - const asset = got && got.rel.assets && got.rel.assets[SHORT[want] || want]; + const rel = got && (await fromR2(ctx, env, got.rel)); + const asset = rel && rel.assets && rel.assets[SHORT[want] || want]; if (!asset) return new Response("not found\n", { status: 404 }); if (req.method === "GET") ctx.waitUntil(capture("magpie site download", { link: want, file: SHORT[want] || want, client: client(req), country: country(req) })); return Response.redirect(asset.url, 302); @@ -182,10 +190,12 @@ export default { ctx.waitUntil(capture("magpie site install script", { client: client(req), country: country(req) })); return beacon(await withWall(await env.ASSETS.fetch(req), env, url)); }, - // the cron (wrangler.jsonc's triggers) keeps the ledger the Stable - // channel is chosen from + // the crons (wrangler.jsonc's triggers): every quarter hour the ledger + // the Stable channel is chosen from, every five minutes the newest and + // the Stable release's files into R2 async scheduled(event, env, ctx) { - ctx.waitUntil(keepLedger(env, Date.now())); + if (event.cron === MIRROR_CRON) ctx.waitUntil(keepFiles(ctx, env)); + else ctx.waitUntil(keepLedger(env, Date.now())); }, }; @@ -458,6 +468,46 @@ async function latest(ctx, env) { const UA = { "User-Agent": "usemagpie.ai" }; +const MIRROR_CRON = "*/5 * * * *"; + +// fromR2 is rel with the files R2 holds at /files (onR2); what R2 holds +// of a tag is asked once a minute. +async function fromR2(ctx, env, rel) { + if (!rel || !env.RELEASES) return rel; + const tag = "v" + rel.version; + let have = await cached("r2/" + tag); + if (!have || typeof have !== "object") { + have = await held(env, tag); + if (have) remember(ctx, "r2/" + tag, have, BRIEF); + } + return onR2(rel, have, REPO, SITE); +} + +// keepFiles is the five-minute cron's run: the newest release's files and +// the Stable one's into R2, each from github.com's address or, when that +// fails, by way of GitHub's API (located). +async function keepFiles(ctx, env) { + if (!env.RELEASES) return; + const rels = []; + const got = await latest(ctx, env); + if (got) rels.push(got.rel); + const st = await stable(ctx, env, Date.now()).catch((e) => console.log("r2: stable", String(e))); + if (st) rels.push(st.rel); + const open = async (name, a, tag) => { + let res = null; + try { + res = await fetch(githubFile(REPO, tag, name), { headers: UA }); + } catch (e) { + console.log("r2: github.com", name, String(e)); + } + if (res && res.ok) return res; + const to = a.api && (await located(a.api, env)); + return to ? fetch(to, { headers: UA }) : res; + }; + const done = await mirror(env, rels, open); + if (done.copied.length || done.failed.length) console.log("r2", JSON.stringify(done)); +} + // api asks GitHub's API, with the GITHUB_TOKEN secret where one is set. function api(path, env) { const headers = { ...UA, Accept: "application/vnd.github+json" }; diff --git a/site/worker.test.mjs b/site/worker.test.mjs index c39d81d34..b3d131e58 100644 --- a/site/worker.test.mjs +++ b/site/worker.test.mjs @@ -3,6 +3,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import worker, { served, goTarget, sponsorTarget } from "./worker.js"; +import { bucket, sha } from "./r2stub.mjs"; const EN = "### Features\n\n- One thing (#1)\n\n### Install\n\nDownload it."; const ZH = "### 新功能\n\n- 一件事 (#1)"; @@ -784,3 +785,93 @@ test("dl: a redirect GitHub's API gives anywhere but its asset host is not passe globalThis.fetch = was; } }); + +// R2 holding a file under the hash the release gives, as the cron leaves it +const holding = async (b, tag, name, body, hash = sha(body)) => + b.put(`${tag}/${name}`, body, { httpMetadata: { contentType: "application/octet-stream" }, customMetadata: { sha256: hash } }); + +test("r2: the feed and /download name the site's /files for a file R2 holds, with github.com's address beside it", async () => { + store.clear(); + const env = { RELEASES: bucket() }; + // the fixture's SHA256SUMS says "abc" + await holding(env.RELEASES, "v0.1.3", "magpie-linux-amd64", "bytes", "abc"); + const res = await ask("/api/latest", env); + assert.equal(res.status, 200); + assert.deepEqual((await res.json()).assets["magpie-linux-amd64"], { + url: "https://usemagpie.ai/files/v0.1.3/magpie-linux-amd64", + api: "https://api.github.com/repos/yetone/magpie-releases/releases/assets/1", + size: 1, + sha256: "abc", + github: "https://github.com/yetone/magpie-releases/releases/download/v0.1.3/magpie-linux-amd64", + }); + const dl = await ask("/download/linux", env); + assert.equal(dl.status, 302); + assert.equal(dl.headers.get("Location"), "https://usemagpie.ai/files/v0.1.3/magpie-linux-amd64"); + const file = await ask("/files/v0.1.3/magpie-linux-amd64", env); + assert.equal(file.status, 200); + assert.equal(await file.text(), "bytes"); + // a tag R2 no longer keeps goes to GitHub + const old = await ask("/files/v0.1.1/magpie-linux-amd64", env); + assert.equal(old.status, 302); + assert.equal(old.headers.get("Location"), "https://github.com/yetone/magpie-releases/releases/download/v0.1.1/magpie-linux-amd64"); +}); + +test("r2: bytes R2 holds under another hash than the release's are not named; github.com's address is", async () => { + store.clear(); + const env = { RELEASES: bucket() }; + await holding(env.RELEASES, "v0.1.3", "magpie-linux-amd64", "older"); + const a = (await (await ask("/api/latest", env)).json()).assets["magpie-linux-amd64"]; + assert.equal(a.url, "https://dl/x"); + assert.equal(a.github, "https://github.com/yetone/magpie-releases/releases/download/v0.1.3/magpie-linux-amd64"); + // R2 failing: the feed as GitHub has it + store.clear(); + env.RELEASES.fail = true; + const res = await ask("/api/latest", env); + assert.equal(res.status, 200); + assert.equal((await res.json()).assets["magpie-linux-amd64"].url, "https://dl/x"); +}); + +test("r2: the five-minute cron copies the newest release's files from github.com, by GitHub's API when that fails", async () => { + const body = "the linux build"; + const was = globalThis.fetch; + const asked = []; + globalThis.fetch = async (u, init = {}) => { + u = String(u); + if (u.endsWith("/SHA256SUMS") || u === "https://release-assets.githubusercontent.com/a/2?sig=1") return new Response(`${sha(body)} magpie-linux-amd64\n`); + if (u === "https://github.com/yetone/magpie-releases/releases/download/v0.1.3/magpie-linux-amd64") { + asked.push("github.com"); + return downloadsDown ? new Response("", { status: 504 }) : new Response(body); + } + if (u === "https://release-assets.githubusercontent.com/a/1?sig=1") { + asked.push("api"); + return new Response(body); + } + return was(u, init); + }; + try { + for (const down of [false, true]) { + store.clear(); + downloadsDown = down; + asked.length = 0; + const env = { RELEASES: bucket() }; + const pending = []; + await worker.scheduled({ cron: "*/5 * * * *" }, env, { waitUntil: (p) => void pending.push(p) }); + await Promise.all(pending); + assert.deepEqual(asked, down ? ["github.com", "api"] : ["github.com"]); + const o = env.RELEASES.objs.get("v0.1.3/magpie-linux-amd64"); + assert.ok(o, "copied"); + assert.equal(new TextDecoder().decode(o.bytes), body); + assert.equal(o.customMetadata.sha256, sha(body)); + // the quarter-hour cron is the ledger's, and copies nothing + const other = { RELEASES: bucket(), LEDGER: { get: async () => null, put: async () => {} } }; + const p2 = []; + await worker.scheduled({ cron: "*/15 * * * *" }, other, { waitUntil: (p) => void p2.push(p.catch(() => {})) }); + await Promise.all(p2); + assert.equal(other.RELEASES.objs.size, 0); + } + } finally { + globalThis.fetch = was; + downloadsDown = false; + store.clear(); + } +}); diff --git a/site/wrangler.jsonc b/site/wrangler.jsonc index cd340a1c9..276977804 100644 --- a/site/wrangler.jsonc +++ b/site/wrangler.jsonc @@ -20,6 +20,9 @@ // the ledger of releases the Stable channel is chosen from (worker.js, // "The Stable channel"), kept by the cron every quarter hour "kv_namespaces": [{ "binding": "LEDGER", "id": "716b22ec7d4c496abb7b3dc085258fde" }], - "triggers": { "crons": ["*/15 * * * *"] }, + // RELEASES: each release's files, copied from GitHub by the five-minute + // cron and served at /files (files.js) + "r2_buckets": [{ "binding": "RELEASES", "bucket_name": "magpie-releases" }], + "triggers": { "crons": ["*/15 * * * *", "*/5 * * * *"] }, "observability": { "enabled": true } }