site: PostHog goes through usemagpie.ai/r/, and downloads are counted

A blocker that knows posthog.com dropped every count of the pages, so the
snippet's api_host is now this site's /r/: relay passes the library and
its config on to PostHog's assets host and the rest to its ingestion
host, with the visitor's address as X-Forwarded-For (PostHog's country)
and without the site's cookies. ui_host stays PostHog's.

Downloads weren't in PostHog at all: /download/* and install.sh are now
counted server-side, as "magpie site download" (link, file, country,
browser or command) and "magpie site install script", each under an id
of its own like the partner counts. A HEAD, or a file the release
doesn't have, isn't counted. The privacy pages (en, zh, ja) say both.

Run: node --test site/worker.test.mjs site/install.test.mjs
site/stable.test.mjs on mote, 48 pass. Broken by hand (no
X-Forwarded-For, the Cookie passed on, the download count off): the
relay and download tests went red. A Playwright page with the snippet
and every posthog.com request aborted (a blocker): Chromium on mote and
WebKit on xiaomi-gpu (mote's WebKit wouldn't launch at load 28) sent
$pageview, $autocapture, $snapshot, $$heatmap and $web_vitals through
/r/ alone, nothing blocked; under GPC nothing was fetched.
This commit is contained in:
yetone
2026-10-31 01:46:34 +08:00
parent e2d7d1f54a
commit cfb06e11c3
5 changed files with 102 additions and 5 deletions
+1 -1
View File
@@ -177,7 +177,7 @@
<li><code>/go/&lt;パートナー&gt;/site</code> と <code>/go/&lt;パートナー&gt;/keys</code>:パートナーの公式サイトとキーのページへのリンクをブラウザーで開くと、移動の前に <code>magpie partner go</code>(どのパートナーか、どのリンクか、地域、国)として数えます。</li>
<li><code>/api/icon?url=…</code>:プラグイン、インポートリンク、ライブラリが示すアイコンはここを経由して取得するので、アイコンのあるホストに見えるのはあなたではなく Cloudflare のアドレスです。画像を中継するだけで、数えることも記録することもしません。</li>
</ul>
<p>サイト自身のページ(このドキュメント、ホーム)には Cloudflare Web Analytics と PostHog Web Analytics(<code>us.i.posthog.com</code>)が入っており、どちらも Cookie は使いません。PostHog はこのサイト用のランダムな訪問者 ID をブラウザのローカルストレージに保存し、再訪問を同じ訪問者として数えます。受け取るのは各ページのアドレス、参照元のページ、ページ上でクリックしたもの(入力内容は含みません)、ページとそのリクエストの読み込み速度、ページで起きたエラー、ブラウザ・OS・画面サイズ、IP アドレスの国と都市、そして訪問の録画(ページの表示、マウスの動き、クリック、スクロール、コンソールのメッセージ)で、入力欄はすべて伏せられます。ブラウザが Do Not Track か Global Privacy Control を送っていれば何も送りません。アプリはどちらも読み込みません。コードは <a href="https://github.com/yetone/magpie/blob/main/site/worker.js">site/worker.js</a> です。</p>
<p>サイト自身のページ(このドキュメント、ホーム)には Cloudflare Web Analytics と PostHog Web Analytics(<code>us.i.posthog.com</code>)が入っており、どちらも Cookie は使いません。PostHog はこのサイト用のランダムな訪問者 ID をブラウザのローカルストレージに保存し、再訪問を同じ訪問者として数えます。受け取るのは各ページのアドレス、参照元のページ、ページ上でクリックしたもの(入力内容は含みません)、ページとそのリクエストの読み込み速度、ページで起きたエラー、ブラウザ・OS・画面サイズ、IP アドレスの国と都市、そして訪問の録画(ページの表示、マウスの動き、クリック、スクロール、コンソールのメッセージ)で、入力欄はすべて伏せられます。ブラウザが Do Not Track か Global Privacy Control を送っていれば何も送りません。PostHog へのリクエストはこのサイトの <code>usemagpie.ai/r/</code> を経由し、IP アドレスとともに PostHog へ渡されます。サイトの Cookie は渡しません。<code>/download</code> のリンクを開くか <code>install.sh</code> を取得すると、PostHog に別のカウントが 1 件送られます。どのファイルか、国、ブラウザかコマンドか、だけで、ID も IP アドレスも含みません。アプリはどちらも読み込みません。コードは <a href="https://github.com/yetone/magpie/blob/main/site/worker.js">site/worker.js</a> です。</p>
<h2 id="lists"><a class="anchor" href="#lists">magpie が取得する公開リスト</a></h2>
<p>モデルの価格と名前のために <a href="https://models.dev">models.dev</a> のカタログ(<code>models.dev/api.json</code>)を、あなたの通貨で価格を表示するために <code>open.er-api.com</code> から米ドルの為替レート(12 時間保持)を取得します。プラグインとその更新は npm レジストリから、ライブラリの項目は GitHub から取得します。どれも公開データの単なるダウンロードで、あなた、あなたのプロバイダー、使用量については何も送りません。ただし、どのリクエストとも同じく、これらのホストにはあなた(またはプロキシ)の IP アドレスが見えます。magpie は各プロバイダーにも、あなた自身のキーやサインインで残量とモデル一覧を尋ねます。<span class="ui">設定</span> → <span class="ui">利用枠</span> → <span class="ui">利用枠の読み込み</span> → <span class="ui">手動のみ</span> で、頼んだときに限れます。</p>
+1 -1
View File
@@ -177,7 +177,7 @@
<li><code>/go/&lt;partner&gt;/site</code> and <code>/go/&lt;partner&gt;/keys</code>: a partner’s website and key-page links, opened in your browser, are counted (the partner, which link, a region, a country) as <code>magpie partner go</code> before you are sent on.</li>
<li><code>/api/icon?url=…</code>: 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.</li>
</ul>
<p>The site’s own pages (these docs, the home page) carry Cloudflare Web Analytics and PostHog Web Analytics (<code>us.i.posthog.com</code>), without cookies. PostHog keeps a random visitor id in your browser’s local storage for this site, so a return visit counts as the same visitor. It gets each page’s address, the page that sent you, what you click on the page (not what you type), how fast the page and its requests loaded, errors the page hit, your browser, system and screen size, the country and city your address is in, and a recording of the visit (what the page showed, mouse moves, clicks and scrolls, its console messages) with every input box masked; nothing at all when your browser sends Do Not Track or Global Privacy Control. The app doesn’t load either. The code is <a href="https://github.com/yetone/magpie/blob/main/site/worker.js">site/worker.js</a>.</p>
<p>The site’s own pages (these docs, the home page) carry Cloudflare Web Analytics and PostHog Web Analytics (<code>us.i.posthog.com</code>), without cookies. PostHog keeps a random visitor id in your browser’s local storage for this site, so a return visit counts as the same visitor. It gets each page’s address, the page that sent you, what you click on the page (not what you type), how fast the page and its requests loaded, errors the page hit, your browser, system and screen size, the country and city your address is in, and a recording of the visit (what the page showed, mouse moves, clicks and scrolls, its console messages) with every input box masked; nothing at all when your browser sends Do Not Track or Global Privacy Control. PostHog’s requests go through this site, under <code>usemagpie.ai/r/</code>, which passes them and your address on to PostHog and keeps the site’s cookies. Following a <code>/download</code> link, or fetching <code>install.sh</code>, sends PostHog a count of its own: which file, your country, and whether a browser or a command asked; no id and no address. The app doesn’t load either. The code is <a href="https://github.com/yetone/magpie/blob/main/site/worker.js">site/worker.js</a>.</p>
<h2 id="lists"><a class="anchor" href="#lists">Public lists magpie fetches</a></h2>
<p>To price and name models magpie fetches the <a href="https://models.dev">models.dev</a> catalog (<code>models.dev/api.json</code>), and for prices in your currency the USD exchange rate from <code>open.er-api.com</code> (kept 12 hours). Plugins and their updates come from the npm registry, and the library’s items from GitHub. These are plain downloads of public data: nothing about you, your providers or your usage is sent, though, as with any request, those hosts see your IP address (or your proxy’s). magpie also asks each of your providers for your allowance and model list, with your own key or sign-in; <span class="ui">Settings</span> → <span class="ui">Allowances</span> → <span class="ui">Allowance reads</span> → <span class="ui">When I ask</span> limits those to when you ask.</p>
+1 -1
View File
@@ -177,7 +177,7 @@
<li><code>/go/&lt;合作伙伴&gt;/site</code> 和 <code>/go/&lt;合作伙伴&gt;/keys</code>:在浏览器里打开合作伙伴的官网和 Key 页面链接时,先记一次 <code>magpie partner go</code>(哪个合作伙伴、哪个链接、地区、国家),再跳转。</li>
<li><code>/api/icon?url=…</code>:插件、导入链接和库里的图标经它获取,图标所在的服务器只看到 Cloudflare 的地址,看不到你的。它只转发图片,不计数也不记录。</li>
</ul>
<p>网站自己的页面(这些文档、首页)带 Cloudflare Web Analytics 和 PostHog Web Analytics(<code>us.i.posthog.com</code>),都不用 Cookie。PostHog 在浏览器的本地存储里为本站记一个随机访客 id,再次访问算同一位访客。它收到每个页面的地址、来源页面、你在页面上点了什么(不含输入的内容)、页面及其请求的加载速度、页面遇到的报错、浏览器、系统和屏幕尺寸、IP 所在的国家和城市,以及这次访问的录屏(页面显示的内容、鼠标移动、点击、滚动和控制台消息),所有输入框都被遮住;浏览器开了 Do Not Track 或 Global Privacy Control 就什么都不发。应用两者都不加载。代码见 <a href="https://github.com/yetone/magpie/blob/main/site/worker.js">site/worker.js</a>。</p>
<p>网站自己的页面(这些文档、首页)带 Cloudflare Web Analytics 和 PostHog Web Analytics(<code>us.i.posthog.com</code>),都不用 Cookie。PostHog 在浏览器的本地存储里为本站记一个随机访客 id,再次访问算同一位访客。它收到每个页面的地址、来源页面、你在页面上点了什么(不含输入的内容)、页面及其请求的加载速度、页面遇到的报错、浏览器、系统和屏幕尺寸、IP 所在的国家和城市,以及这次访问的录屏(页面显示的内容、鼠标移动、点击、滚动和控制台消息),所有输入框都被遮住;浏览器开了 Do Not Track 或 Global Privacy Control 就什么都不发。PostHog 的请求经由本站的 <code>usemagpie.ai/r/</code> 转给 PostHog,连同你的 IP 一起转发,本站的 Cookie 不转发。打开 <code>/download</code> 下载链接或获取 <code>install.sh</code> 时,会另外向 PostHog 发一次计数:哪个文件、你所在的国家、是浏览器还是命令发起的;不带 id,也不带 IP。应用两者都不加载。代码见 <a href="https://github.com/yetone/magpie/blob/main/site/worker.js">site/worker.js</a>。</p>
<h2 id="lists"><a class="anchor" href="#lists">magpie 拉取的公开列表</a></h2>
<p>为了给模型定价和命名,magpie 会拉取 <a href="https://models.dev">models.dev</a> 的模型目录(<code>models.dev/api.json</code>);为了用你的货币显示价格,会从 <code>open.er-api.com</code> 拉取美元汇率(缓存 12 小时)。插件及其更新来自 npm 仓库,库里的内容来自 GitHub。这些都是公开数据的普通下载,不发送任何关于你、你的供应商或用量的信息;和任何请求一样,这些主机能看到你的 IP(或代理的 IP)。magpie 还会用你自己的密钥或登录向各个供应商读取额度和模型列表;<span class="ui">设置</span> → <span class="ui">额度</span> → <span class="ui">额度刷新</span> → <span class="ui">仅手动</span> 可以只在你要求时才读。</p>
+35 -2
View File
@@ -28,6 +28,9 @@
// /download/windows the Windows app (x64); /download/windows-arm64
// /download/linux the Linux app (x86-64); /download/linux-arm64
// /download/<file> any file of the newest release, by name
// /r/... the pages' PostHog snippet, passed on to PostHog
// (relay, below) so a blocker that knows its host
// doesn't drop the count
// /docs, /docs/zh, /docs/ja the getting-started guide: /docs/start, /docs/<lang>/start
// /zh/, /ja/, /de/ the home page in Chinese, Japanese, German (i18n.js);
// / sends a browser that prefers one of them there,
@@ -117,11 +120,13 @@ export default {
return json({ releases: pick }, 200, cacheFor(got));
}
if (url.pathname === "/api/icon") return icon(url.searchParams.get("url"));
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];
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);
}
const guide = DOCS[url.pathname.replace(/\/+$/, "")];
@@ -159,6 +164,8 @@ export default {
out.headers.append("Vary", "Accept-Language, Cookie");
return out;
}
if (url.pathname === "/install.sh" && req.method === "GET")
ctx.waitUntil(capture("magpie site install script", { client: client(req), country: country(req) }));
return beacon(await env.ASSETS.fetch(req));
},
// the cron (wrangler.jsonc's triggers) keeps the ledger the Stable
@@ -236,6 +243,11 @@ function fromMagpie(to) {
}
}
// client says whether a browser asked, or a command (curl, wget, a script).
function client(req) {
return /^Mozilla\//.test(req.headers.get("User-Agent") || "") ? "browser" : "command";
}
function country(req) {
return (req.cf && req.cf.country) || "";
}
@@ -309,9 +321,30 @@ function translate(res, lang) {
return rw.transform(out);
}
// relay passes a request of the pages' PostHog snippet (under RELAY) on to
// PostHog: the library and its config from the assets host, the rest from
// the ingestion host. The visitor's address goes as X-Forwarded-For, which
// PostHog reads for the country, and the site's cookies stay here.
const RELAY = "/r/";
export async function relay(req, url) {
const path = url.pathname.slice(RELAY.length - 1);
const host = /^\/(static|array)\//.test(path) ? "us-assets.i.posthog.com" : "us.i.posthog.com";
const headers = new Headers(req.headers);
for (const h of ["Cookie", "Host"]) headers.delete(h);
const ip = req.headers.get("CF-Connecting-IP");
if (ip) headers.set("X-Forwarded-For", ip);
const body = req.method === "GET" || req.method === "HEAD" ? null : req.body;
try {
return await fetch(`https://${host}${path}${url.search}`, { method: req.method, headers, body, redirect: "manual" });
} catch {
return new Response("", { status: 502 });
}
}
// beacon adds Cloudflare Web Analytics and PostHog's Web Analytics to a page.
// The dashboard's automatic injection skips whatever a worker returns, and
// every page passes through this one. PostHog keeps its visitor id in
// every page passes through this one. PostHog's requests go through RELAY
// on this site. PostHog keeps its visitor id in
// localStorage, never a cookie: these pages vary on Cookie (the lang
// cookie), and a per-visitor cookie would ride on every request. It isn't
// cookieless, since cookieless drops the address before GeoIP and the
@@ -321,7 +354,7 @@ function translate(res, lang) {
// and the rest of the project's settings come from its remote config, so
// flags aren't turned off. Nothing is loaded under Do Not Track or Global
// Privacy Control. Its project is the daily count's.
const WEB_ANALYTICS = `<script>if(!(navigator.doNotTrack=="1"||window.doNotTrack=="1"||navigator.globalPrivacyControl)){!function(t,e){var o,n,p,r;e.__SV||(window.posthog&&window.posthog.__loaded)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+" (stub)"},o="capture register unregister opt_out_capturing opt_in_capturing has_opted_out_capturing set_config".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);posthog.init("${POSTHOG_KEY}",{api_host:"https://us.i.posthog.com",persistence:"localStorage",person_profiles:"identified_only",capture_pageview:true,capture_pageleave:true,autocapture:true,enable_heatmaps:true,capture_dead_clicks:true,capture_exceptions:true,capture_performance:{web_vitals:true,network_timing:true},session_recording:{maskAllInputs:true},disable_surveys:true,respect_dnt:true})}</script>`;
const WEB_ANALYTICS = `<script>if(!(navigator.doNotTrack=="1"||window.doNotTrack=="1"||navigator.globalPrivacyControl)){!function(t,e){var o,n,p,r;e.__SV||(window.posthog&&window.posthog.__loaded)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+" (stub)"},o="capture register unregister opt_out_capturing opt_in_capturing has_opted_out_capturing set_config".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);posthog.init("${POSTHOG_KEY}",{api_host:location.origin+"/r",ui_host:"https://us.posthog.com",persistence:"localStorage",person_profiles:"identified_only",capture_pageview:true,capture_pageleave:true,autocapture:true,enable_heatmaps:true,capture_dead_clicks:true,capture_exceptions:true,capture_performance:{web_vitals:true,network_timing:true},session_recording:{maskAllInputs:true},disable_surveys:true,respect_dnt:true})}</script>`;
const BEACON = `<script defer src="https://static.cloudflareinsights.com/beacon.min.js" data-cf-beacon='{"token": "c09e76abf16b40b2aa5571c196efb847"}'></script>` + WEB_ANALYTICS;
function beacon(res) {
+64
View File
@@ -54,12 +54,18 @@ const FEED = `<?xml version="1.0" encoding="UTF-8"?>
</feed>`;
// what the worker sent PostHog
const captured = [];
// what the worker passed on to PostHog for the pages' snippet (relay)
const relayed = [];
globalThis.fetch = async (u, init = {}) => {
u = String(u);
if (u === "https://us.i.posthog.com/i/v0/e/") {
captured.push(JSON.parse(init.body));
return new Response("{}");
}
if (/^https:\/\/us(-assets)?\.i\.posthog\.com\//.test(u)) {
relayed.push({ u, method: init.method, headers: new Headers(init.headers), body: init.body && (await new Response(init.body).text()) });
return new Response("relayed");
}
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 });
@@ -264,6 +270,64 @@ test("download: a platform's link goes to that asset of the latest release", asy
assert.equal((await ask("/download/nothing-like-it")).status, 404);
});
test("download: each link followed is counted, with the platform, the country and a browser or a command", async () => {
captured.length = 0;
const req = new Request("https://usemagpie.ai/download/linux", { headers: { "User-Agent": "curl/8.7.1" } });
req.cf = { country: "BR" };
assert.equal((await worker.fetch(req, {}, ctx)).status, 302);
await new Promise((ok) => setTimeout(ok, 0));
assert.equal(captured.length, 1);
assert.equal(captured[0].event, "magpie site download");
assert.deepEqual(captured[0].properties, { link: "linux", file: "magpie-linux-amd64", client: "command", country: "BR", $process_person_profile: false });
captured.length = 0;
await worker.fetch(new Request("https://usemagpie.ai/download/linux", { headers: { "User-Agent": "Mozilla/5.0 (Macintosh)" } }), {}, ctx);
await new Promise((ok) => setTimeout(ok, 0));
assert.equal(captured[0].properties.client, "browser");
// a HEAD, or a file the release doesn't have, isn't counted
captured.length = 0;
await worker.fetch(new Request("https://usemagpie.ai/download/linux", { method: "HEAD" }), {}, ctx);
await ask("/download/nothing-like-it");
await new Promise((ok) => setTimeout(ok, 0));
assert.deepEqual(captured, []);
});
test("install.sh: each fetch is counted", async () => {
const env = { ASSETS: { fetch: async () => new Response("#!/bin/sh\n", { headers: { "Content-Type": "text/x-sh" } }) } };
captured.length = 0;
const res = await worker.fetch(new Request("https://usemagpie.ai/install.sh", { headers: { "User-Agent": "curl/8.7.1" } }), env, ctx);
assert.equal(await res.text(), "#!/bin/sh\n");
await new Promise((ok) => setTimeout(ok, 0));
assert.equal(captured.length, 1);
assert.equal(captured[0].event, "magpie site install script");
assert.equal(captured[0].properties.client, "command");
});
test("relay: the snippet's requests reach PostHog with the visitor's address and without the site's cookies", async () => {
relayed.length = 0;
const post = new Request("https://usemagpie.ai/r/e/?ip=0&ver=1.442.1", {
method: "POST",
body: "gzipped",
headers: { Cookie: "lang=zh", "CF-Connecting-IP": "203.0.113.7", "Content-Type": "text/plain", "User-Agent": "Mozilla/5.0" },
});
assert.equal(await (await worker.fetch(post, {}, ctx)).text(), "relayed");
await worker.fetch(new Request("https://usemagpie.ai/r/static/array.js"), {}, ctx);
await worker.fetch(new Request("https://usemagpie.ai/r/array/phc_x/config.js"), {}, ctx);
await worker.fetch(new Request("https://usemagpie.ai/r/flags/?v=2"), {}, ctx);
assert.deepEqual(relayed.map((r) => r.u), [
"https://us.i.posthog.com/e/?ip=0&ver=1.442.1",
"https://us-assets.i.posthog.com/static/array.js",
"https://us-assets.i.posthog.com/array/phc_x/config.js",
"https://us.i.posthog.com/flags/?v=2",
]);
const [e] = relayed;
assert.equal(e.method, "POST");
assert.equal(e.body, "gzipped");
assert.equal(e.headers.get("X-Forwarded-For"), "203.0.113.7");
assert.equal(e.headers.get("Cookie"), null);
assert.equal(e.headers.get("User-Agent"), "Mozilla/5.0");
});
test("docs: an English docs page sends a browser that prefers Chinese or Japanese to its own, until a language is picked", async () => {
const have = new Set(["/docs/start", "/docs/zh/start", "/docs/ja/start", "/docs/only-en"]);
const env = { ASSETS: { fetch: async (r) => new Response(have.has(new URL(r.url).pathname) ? "<html></html>" : "nf", { status: have.has(new URL(r.url).pathname) ? 200 : 404, headers: { "Content-Type": "text/plain" } }) } };