page-chat 0.1.2: opened from another machine, the page reaches its service through magpie web

aigcfree (Discord DM) runs `magpie web --addr 0.0.0.0:3430` on an Ubuntu
server behind nginx, and opens it from a Windows PC. The chat tab showed
"127.0.0.1 refused to connect": boot.js sent the frame to 127.0.0.1, the
viewer's own PC. 0.1.1 (8a9680b) explains an SSH tunnel instead. With a
magpie that proxies a page's service, no tunnel is needed:

- package.json declares magpie.page.service {port: 3477, option: "port"},
  the same port index.mjs listens on. magpie web then proxies the service
  under the page's token (/_magpie/plugin/<token>/_magpie/service/) and the
  bridge hands that address to the page as magpie.service.
- boot.js goes to magpie.service when it is an http(s) address. Without
  one (the desktop window, or an older magpie) it behaves as 0.1.1: on
  loopback it goes to 127.0.0.1, from another machine it explains the
  tunnel.
- The chat client asks api/... by relative address (app.js, index.html,
  library.mjs's icon URLs), so it works under the proxied path. Served
  from 127.0.0.1:<port>/ these resolve as before.

The service still listens on 127.0.0.1 only, and still checks Host,
Origin and its token. magpie's proxy sets Host to 127.0.0.1:<port>.

Run: bun test packages/chat (16 pass) and bun scripts/check.mjs on mote.
Real: a sandbox magpie web on mote (0.0.0.0, LAN), this package installed
from a folder, a fake gateway. Playwright on the Windows box opened the
chat tab over the LAN in Chromium and WebKit, sent a message, and got the
streamed answer; the fake gateway logged both requests.
Broken by hand: the service branch in boot.js off, 2 tests red.
Not tried: behind a real nginx; the desktop window with this version (the
fallback is the 0.1.1 path, covered by the launcher tests).
This commit is contained in:
yetone
2026-10-29 13:26:58 +08:00
parent 8a9680b4cb
commit 4a46212f89
6 changed files with 98 additions and 23 deletions
+55 -1
View File
@@ -172,7 +172,7 @@ test("the chat UI sends the token on every API call", () => {
expect(calls.length).toBe(2)
expect(calls[0]).toStartWith("init")
expect(app).toMatch(/var init = \{[^\n]*headers: authHeaders\(\)/)
expect(app).toMatch(/fetch\("\/api\/chat", \{\s*method: "POST",\s*headers: authHeaders\(/)
expect(app).toMatch(/fetch\("api\/chat", \{\s*method: "POST",\s*headers: authHeaders\(/)
expect(app).toContain('meta[name="magpie-chat-token"]')
expect(app).not.toMatch(/XMLHttpRequest|new WebSocket|EventSource|sendBeacon/)
})
@@ -187,3 +187,57 @@ test("the plugin starts nothing on import and serves the option's port", async (
expect(pkg.scripts?.install).toBeUndefined()
expect(pkg.scripts?.preinstall).toBeUndefined()
})
// aigcfree on Discord: `magpie web` on a server, opened from another
// computer's browser. There 127.0.0.1 is the viewer's own computer, so
// magpie web serves this service under a path of its own address
// (magpie.page.service), and the chat UI has to work from under that path.
test("the chat UI's addresses are relative, so it works under magpie web's path", async () => {
const app = readFileSync(join(dir, "chat", "app.js"), "utf8").replace(/^\s*\/\/.*$/gm, "")
expect(app).not.toMatch(/["'`]\/api\//)
const html = readFileSync(join(dir, "chat", "index.html"), "utf8")
expect(html).not.toMatch(/(href|src)="\//)
expect(html).toContain('href="api/fonts.css"')
// a provider's icon, as the bootstrap hands it to the UI
writeFileSync(join(cfg, "providers.json"), JSON.stringify([{ id: "remote", icon: "https://example.com/i.png" }]))
const { providerIcons } = await import("./lib/library.mjs")
expect((await providerIcons(cfg)).get("remote")).toBe("api/icon/remote")
})
test("the plugin declares its service on the option's port", () => {
const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"))
expect(pkg.magpie.page.service).toEqual({ port: pkg.magpie.options.port, option: "port" })
})
// boot.js run as the page's frame runs it: where it sends the frame
async function boot(magpie, hostname = "127.0.0.1") {
const src = readFileSync(join(dir, "page", "boot.js"), "utf8")
let went = ""
const location = { hostname, replace: (u) => { went = u } }
const document = { getElementById: () => null }
await new Function("window", "location", "document", "return " + src.replace(/^\s*\/\/.*$/gm, "").trim().replace(/;\s*$/, ""))({ magpie }, location, document)
return went
}
test("the launcher goes to magpie web's path when the bridge offers one, else to 127.0.0.1", async () => {
const ready = Promise.resolve({ dark: true, tokens: { bg: "#000" } })
const options = { get: async () => ({ port: 3999 }) }
const svc = "http://server.lan:3430/_magpie/plugin/" + "a".repeat(32) + "/_magpie/service/"
const remote = await boot({ ready, options, service: svc })
expect(remote).toStartWith(svc + "?")
expect(new URL(remote).searchParams.get("theme")).toBe("dark")
// the desktop window, and a magpie from before magpie.service
expect(await boot({ ready, options, service: "" })).toStartWith("http://127.0.0.1:3999/?theme=dark")
expect(await boot({ ready, options })).toStartWith("http://127.0.0.1:3999/?")
expect(await boot(undefined)).toBe("http://127.0.0.1:3477/?")
// only an http(s) address is followed
expect(await boot({ ready, service: "javascript:alert(1)" })).toStartWith("http://127.0.0.1:3477/?")
})
test("opened from another machine, the launcher takes magpie web's path, and explains the tunnel only without one", async () => {
const ready = Promise.resolve({ dark: false })
const svc = "http://server.lan:3430/_magpie/plugin/" + "b".repeat(32) + "/_magpie/service/"
expect(await boot({ ready, service: svc }, "server.lan")).toStartWith(svc + "?")
// a magpie from before magpie.service: no navigation to a refused 127.0.0.1
expect(await boot({ ready }, "server.lan")).toBe("")
})
+16 -16
View File
@@ -556,7 +556,7 @@ function parseEventBlock(block) {
}
function streamChat(payload, onEvent, signal) {
return fetch("/api/chat", {
return fetch("api/chat", {
method: "POST",
headers: authHeaders({ "content-type": "application/json" }),
body: JSON.stringify(payload),
@@ -629,7 +629,7 @@ function patchSettings(patch) {
function flushSettings() {
if (saveTimer) { clearTimeout(saveTimer); saveTimer = null; }
return api("/api/settings", { method: "POST", body: state.settings }).then(function (saved) {
return api("api/settings", { method: "POST", body: state.settings }).then(function (saved) {
state.settings = Object.assign({}, state.settings, saved || {});
}).catch(function (err) {
toast("设置保存失败:" + err.message, true);
@@ -852,7 +852,7 @@ function addFiles(files) {
return null;
}
return readAsDataURL(file).then(function (data) {
return api("/api/upload", {
return api("api/upload", {
method: "POST",
body: { name: file.name || "file", type: type, data: data, clientType: type }
}).catch(function () {
@@ -1030,7 +1030,7 @@ function bindResizers() {
var w = Math.round(target.getBoundingClientRect().width);
var key = WIDTHS[cfg[1]].key;
state.settings[key] = w;
api("/api/settings", { method: "POST", body: { [key]: w } }).catch(function () {});
api("api/settings", { method: "POST", body: { [key]: w } }).catch(function () {});
}
bar.addEventListener("mousedown", down);
@@ -1046,7 +1046,7 @@ function bindResizers() {
target.style.setProperty(cfg[1] === "left" ? "--side-w" : "--set-w", next + "px");
var key = WIDTHS[cfg[1]].key;
state.settings[key] = next;
api("/api/settings", { method: "POST", body: { [key]: next } }).catch(function () {});
api("api/settings", { method: "POST", body: { [key]: next } }).catch(function () {});
});
});
}
@@ -1071,7 +1071,7 @@ function toggleSettings(open, persist) {
state.settings.settingsOpen = show;
// 恢复上次状态时不要再写回去,否则会把用户刚改的值覆盖成旧的
if (persist !== false) {
api("/api/settings", { method: "POST", body: { settingsOpen: show } }).catch(function () {});
api("api/settings", { method: "POST", body: { settingsOpen: show } }).catch(function () {});
}
if (show) renderSettings();
}
@@ -1138,7 +1138,7 @@ function checkTools() {
status.textContent = "检查中…";
status.className = "set-tools-status";
$("#checkTools").disabled = true;
api("/api/mcp/tools").then(function (data) {
api("api/mcp/tools").then(function (data) {
var servers = (data && data.servers) || [];
if (!servers.length) { status.textContent = "没有启用的服务器"; return; }
var ok = servers.filter(function (s) { return s.ok; });
@@ -1161,7 +1161,7 @@ function checkTools() {
/* ================= 会话列表 ================= */
function loadConversations() {
return api("/api/conversations").then(function (data) {
return api("api/conversations").then(function (data) {
state.conversations = (data && data.items) || [];
renderSessions();
}).catch(function (err) {
@@ -1217,7 +1217,7 @@ function togglePin(id, pin) {
if (pin && at < 0) pinned.push(id);
if (!pin && at >= 0) pinned.splice(at, 1);
state.settings.pinned = pinned;
api("/api/settings", { method: "POST", body: { pinned: pinned } })
api("api/settings", { method: "POST", body: { pinned: pinned } })
.then(function () { return loadConversations(); })
.then(function () { toast(pin ? "已置顶" : "已取消置顶"); })
.catch(function (err) { toast("置顶失败:" + err.message, true); });
@@ -1227,11 +1227,11 @@ function togglePin(id, pin) {
function askDelete(id, title) {
var name = String(title || "这条对话");
{
api("/api/conversations/" + encodeURIComponent(id), { method: "DELETE" }).then(function () {
api("api/conversations/" + encodeURIComponent(id), { method: "DELETE" }).then(function () {
// 置顶列表里也把它去掉,免得留下悬空的 id
var pinned = (state.settings.pinned || []).filter(function (x) { return x !== id; });
state.settings.pinned = pinned;
api("/api/settings", { method: "POST", body: { pinned: pinned } }).catch(function () {});
api("api/settings", { method: "POST", body: { pinned: pinned } }).catch(function () {});
if (state.convId === id) {
state.convId = null;
state.title = "新对话";
@@ -1252,12 +1252,12 @@ function askDelete(id, title) {
function setSidebar(open) {
$("#app").classList.toggle("side-off", !open);
state.settings.sidebar = open;
api("/api/settings", { method: "POST", body: { sidebar: open } }).catch(function () {});
api("api/settings", { method: "POST", body: { sidebar: open } }).catch(function () {});
}
function openConversation(id) {
if (state.busy) { toast("正在生成,先停止再切换对话", true); return; }
api("/api/conversations/" + encodeURIComponent(id)).then(function (conv) {
api("api/conversations/" + encodeURIComponent(id)).then(function (conv) {
if (!conv) return;
state.convId = conv.id;
state.title = conv.title || "新对话";
@@ -1316,7 +1316,7 @@ function persistConversation() {
};
})
};
return api("/api/conversations", { method: "POST", body: payload }).then(function (saved) {
return api("api/conversations", { method: "POST", body: payload }).then(function (saved) {
if (!saved) return;
state.convId = saved.id;
state.title = saved.title || state.title;
@@ -2015,7 +2015,7 @@ function stop() {
if (!state.busy) return;
state.stopped = true;
var clientId = state.clientId;
api("/api/chat/stop", { method: "POST", body: { clientId: clientId, id: clientId } }).catch(function () { /* 断开也会中止 */ });
api("api/chat/stop", { method: "POST", body: { clientId: clientId, id: clientId } }).catch(function () { /* 断开也会中止 */ });
if (state.abort) {
try { state.abort.abort(); } catch (e) { /* 已结束 */ }
}
@@ -2121,7 +2121,7 @@ function boot() {
updateSend();
renderMessages();
api("/api/bootstrap").then(function (data) {
api("api/bootstrap").then(function (data) {
state.boot = data || {};
state.models = (data && data.models) || [];
state.library = (data && data.library) || { instructions: [], skills: [], mcp: [] };
+1 -1
View File
@@ -8,7 +8,7 @@
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="vendor/katex/katex.min.css">
<!-- 用户在 magpie 设置里选的字体,由服务端读 settings.json 生成,放在最后好覆盖上面的兜底 -->
<link rel="stylesheet" href="/api/fonts.css">
<link rel="stylesheet" href="api/fonts.css">
</head>
<body>
<div class="app" id="app">
+2 -2
View File
@@ -123,7 +123,7 @@ export async function composeSystem(settings, dir = configDir()) {
// 供应商图标:magpie 的 providers.json 里每个供应商有 icon,
// 可能是内置图标名(deepseek-color)、file: 本地文件,或 http 地址。
// 这里统一变成服务端能直接给的 URL(/api/icon/<provider>),取不到就不给。
// 这里统一变成服务端能直接给的 URL(api/icon/<provider>,相对对话页,经 magpie web 转发时也对),取不到就不给。
export async function providerIcons(dir = configDir()) {
const out = new Map();
const providers = await readJson(join(dir, "providers.json"), null);
@@ -133,7 +133,7 @@ export async function providerIcons(dir = configDir()) {
const id = p.id || p.name;
const icon = p.icon || p.logo || "";
if (!id || typeof icon !== "string" || !icon) continue;
out.set(String(id), "/api/icon/" + encodeURIComponent(String(id)));
out.set(String(id), "api/icon/" + encodeURIComponent(String(id)));
}
return out;
}
+6 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/page-chat",
"version": "0.1.1",
"version": "0.1.2",
"description": "在 magpie 窗口里加一个「对话」页面:用 magpie 自己的模型、MCP 服务器、指令和技能聊天,支持图片与 LaTeX。A chat page inside magpie's window: talk with magpie's own models, MCP servers, instructions and skills, with images and LaTeX.",
"author": "Magic_zero (https://github.com/Magiczerowxy)",
"files": [
@@ -50,7 +50,11 @@
"ja": "チャット"
},
"file": "page/index.html",
"icon": "assets/icon.svg"
"icon": "assets/icon.svg",
"service": {
"port": 3477,
"option": "port"
}
},
"options": {
"port": 3477
+18 -1
View File
@@ -8,6 +8,12 @@
//
// 端口用插件选项里的 port(默认 3477),服务端(index.mjs)读的是同一个值。
//
// 跳到哪:magpie 把页面给浏览器时(`magpie web`,可能在另一台电脑上打开),
// 127.0.0.1 是看页面那台电脑自己,不是跑服务的机器。这时 bridge 会给出
// magpie.service:magpie web 在它自己的地址上替本服务转发的路径(package.json
// 的 magpie.page.service 声明了它)。有就跳那里;没有(桌面窗口,或旧版
// magpie)就照旧跳 127.0.0.1。
//
// 顺手把窗口的主题和设计令牌一起带上(magpie 的 bridge 已经把它们算好了),
// 这样对话页的配色和字体跟窗口完全一致,连用户的自定义主题也算在内。
(async () => {
@@ -15,6 +21,7 @@
let port = DEFAULT_PORT;
let theme = "";
let tokens = null;
let service = "";
try {
const t = await window.magpie?.ready; // { dark, lang, tokens }
@@ -23,6 +30,10 @@
if (t.tokens && typeof t.tokens === "object") tokens = t.tokens;
}
} catch { /* 没有 bridge 就退回默认主题 */ }
try {
const s = window.magpie?.service;
if (typeof s === "string" && /^https?:\/\//.test(s)) service = s;
} catch { /* 旧版 magpie 没有 service */ }
try {
const o = await window.magpie?.options?.get?.();
@@ -51,12 +62,18 @@
}
}
// magpie 给了 service 就走它:这是 magpie web 在自己地址上的转发,远程也能用。
if (service) {
location.replace(service + "?" + q.toString());
return;
}
const target = "http://127.0.0.1:" + port + "/?" + q.toString();
// 服务只听本机的 127.0.0.1,跳过去的是「打开这个页面的浏览器」所在的机器。
// magpie web 部署在服务器上、从别的电脑打开时,那台电脑的 127.0.0.1 上没有服务,
// 直接跳只会得到「127.0.0.1 拒绝连接」(Discord DM: AIGCFREE,magpie web + nginx)。
// 这种情况先说明原因,给出 SSH 端口转发的做法,转好了再点「继续」。
// 旧版 magpie 不给 service 时,先说明原因,给出 SSH 端口转发的做法,转好了再点「继续」。
if (!isLoopback(location.hostname)) {
showRemote(port, target);
return;