From becbabce9eb53b44fc1212ce26332312e7ca08d3 Mon Sep 17 00:00:00 2001 From: awork Date: Mon, 19 Oct 2026 20:22:35 +0800 Subject: [PATCH 1/3] feat: dsh settings panel guides remote users to security.adminRelay when the loopback origin is unreachable (#3816) --- src/agent/dsh-native-client.ts | 67 +++++++++++++++- tests/dsh-settings-ui.test.ts | 139 +++++++++++++++++++++++++++++++++ 2 files changed, 204 insertions(+), 2 deletions(-) diff --git a/src/agent/dsh-native-client.ts b/src/agent/dsh-native-client.ts index c5e8c3cc28..9b6a14ffcc 100644 --- a/src/agent/dsh-native-client.ts +++ b/src/agent/dsh-native-client.ts @@ -88,6 +88,11 @@ const PAGE_KEYS: Record = { config: "tab_config", logs: "tab_logs", }; + +// #3816: the exact field a remote user adds to enable the #3373 relay. A +// fragment on purpose — pasting a whole object would clobber an existing +// config's other keys. +const REMOTE_RELAY_SNIPPET = '"security": { "adminRelay": true }'; const EMBED_HEIGHT = "min(640px, 78vh)"; // #3100: pre-flight for the framed face. Auto-update refreshes the profile @@ -213,6 +218,7 @@ const zh: Dict = { "degraded": "当前 dsh 进程未绑定 bili 代理(未经 bili dsh 启动,或代理尚未就绪)——先运行 /acp,或改用 bili dsh 启动。", "connecting": "正在连接 bili 代理…", "stale": "运行中的 bili 代理比已安装的配置文件旧:本页面已加载新版界面,但代理进程仍在提供旧版服务,暂时无法打开内嵌页面。若本应用已运行新版本,启动一个新会话即会自动换上新代理(也可手动结束旧代理进程立即生效);若应用本身还是旧版本,请完全退出并重新启动 dsh。恢复前可点下方按钮直接打开 Web UI。", + "remote_blocked": "本页面通过远程地址访问,而 bili 面板运行在服务器本机的回环地址(127.0.0.1)上——你的浏览器无法直连它(直连会指向你自己的电脑)。要远程打开面板:在服务器上编辑 ~/.config/billion-context/billion-context.json,向顶层对象加入下方字段并保存——本页会在数秒内自动生效(无需重启 dsh,刷新页面同样可以)。", "tab_overview": "总览", "tab_sessions": "会话", "tab_config": "配置", @@ -227,6 +233,7 @@ const en: Dict = { "degraded": "This dsh process is not bound to a bili proxy (not launched via bili dsh, or the proxy is not up yet) — run /acp first, or launch through bili dsh.", "connecting": "Connecting to the bili proxy…", "stale": "The running bili proxy is older than the installed profile: this page already runs the new face, but the proxy process still serves the old build, so the embedded page cannot be opened yet. If this app itself runs the new version, starting a new session swaps in the new proxy automatically (or kill the old proxy process manually for an immediate switch); if the app itself is still on the old version, fully quit and relaunch dsh. Until then, use the button below to open the Web UI directly.", + "remote_blocked": "This page is reached through a remote address, but the bili panel runs on the server's own loopback address (127.0.0.1) — your browser cannot reach it directly (it would point at your own machine). To open the panel remotely: edit ~/.config/billion-context/billion-context.json on the server and add the field below to the top-level object — this page picks it up within seconds (no dsh restart needed; reloading works too).", "tab_overview": "Overview", "tab_sessions": "Sessions", "tab_config": "Config", @@ -262,6 +269,35 @@ function relayBaseOf(res: { url?: unknown }): string { return ""; } +/** #3816: hosts that mean "this machine" from the browser's point of view. */ +function isLoopbackHost(host: string): boolean { + const h = host.replace(/^\[|\]$/g, "").toLowerCase(); + return h === "localhost" || h === "127.0.0.1" || h === "::1"; +} + +// #3816: remote-access mismatch — the bound origin is the server's loopback +// while THIS page was reached through a non-loopback address, so the +// browser's 127.0.0.1 is its own machine and the origin is unreachable by +// construction. Left alone the entry spins on "connecting…" forever and the +// backup button opens a dead link; instead the face explains the fix +// (security.adminRelay, #3373). Client-side detection on purpose: server +// socket inspection breaks under reverse proxies. Undecidable (no location, +// no URL constructor, unparsable origin) ⇒ false ⇒ old behavior stands. +function remoteMismatch(origin: string | undefined): boolean { + if (origin === undefined || origin.length === 0) return false; // relay mode: same-origin paths are reachable by construction + let parsed: { hostname?: unknown }; + try { + parsed = new URL(origin); + } catch { + return false; + } + const originHost = typeof parsed.hostname === "string" ? parsed.hostname : ""; + if (!isLoopbackHost(originHost)) return false; + const g = globalThis as { location?: { hostname?: unknown } }; + const pageHost = typeof g.location?.hostname === "string" ? g.location.hostname : ""; + return pageHost.length > 0 && !isLoopbackHost(pageHost); +} + // #3373: gateways that mount dsh web under a path prefix re-map every URL // the index references, so the absolute probe path misses. Probe relative to // the page's own base as a second form; the last form that answered wins the @@ -387,6 +423,11 @@ export function apply(ctx: ClientContext): void { if (origin !== undefined) probeEmbedRoute(origin, setEmbed); }, [origin]); const liveEmbed: EmbedVerdict | undefined = embed !== undefined && embed.origin === origin ? embed.verdict : undefined; + // #3816: remote page + loopback origin ⇒ unreachable by construction — + // explain the fix instead of spinning on "connecting…". A resolved + // "ok" verdict outranks the mismatch (same-machine access through a + // LAN IP still reaches the loopback) — never shadow a working frame. + const remoteBlocked = remoteMismatch(origin) && liveEmbed !== "ok"; const lang = t("nav") === zhDict.nav ? "zh" : "en"; // The open-in-browser action button. One shared builder so the two // placements (embedded-tab row, degraded/stale footer) cannot drift: @@ -420,6 +461,27 @@ export function apply(ctx: ClientContext): void { let middle: unknown; if (origin === undefined) { middle = createElement("p", { style: { margin: 0, opacity: 0.7, lineHeight: 1.6 } }, t("degraded")); + } else if (remoteBlocked) { + middle = createElement( + "div", + { style: { display: "flex", flexDirection: "column", gap: 8 } }, + createElement("p", { style: { margin: 0, opacity: 0.7, lineHeight: 1.6 } }, t("remote_blocked")), + createElement( + "code", + { + style: { + display: "block", + padding: "6px 10px", + borderRadius: 8, + border: "1px solid rgba(127,127,127,0.4)", + background: "rgba(127,127,127,0.08)", + fontSize: 13, + lineHeight: 1.6, + }, + }, + REMOTE_RELAY_SNIPPET, + ), + ); } else if (liveEmbed === "stale") { middle = createElement("p", { style: { margin: 0, opacity: 0.7, lineHeight: 1.6 } }, t("stale")); } else if (liveEmbed === "ok") { @@ -483,8 +545,9 @@ export function apply(ctx: ClientContext): void { { style: { display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" } }, createElement("p", { style: { margin: 0, opacity: 0.7, fontSize: 13, lineHeight: 1.6, flex: 1, minWidth: 200 } }, t("hint")), // ok 状态:按钮在上方页签行(日志页签后面);degraded/stale - // 仍留在页脚作后备入口(#2448 同一按钮)。 - liveEmbed === "ok" ? null : openWebButton(), + // 仍留在页脚作后备入口(#2448 同一按钮)。#3816: remoteBlocked + // 时按钮指向的正是那个够不到的回环地址——死链,一并隐藏。 + liveEmbed === "ok" || remoteBlocked ? null : openWebButton(), ), ); }; diff --git a/tests/dsh-settings-ui.test.ts b/tests/dsh-settings-ui.test.ts index 2fbf6c5b9e..cd501bfd89 100644 --- a/tests/dsh-settings-ui.test.ts +++ b/tests/dsh-settings-ui.test.ts @@ -1254,3 +1254,142 @@ test("#3100: embed pre-flight — a stale proxy build gets the restart notice in m.runCleanups(); } }); + +test("#3816: remote page + loopback origin (relay off) shows the adminRelay guidance instead of spinning; gate negatives stay unchanged", async () => { + // Positive: the page is reached through a non-loopback host while the + // bound origin is the server's loopback — unreachable by construction. + // The face must explain the fix instead of spinning on "connecting…". + { + const m = await mountClient({ + location: { hostname: "vps.example.com" }, + URL, + open: (_url: string) => {}, + fetch: async (url: string) => { + if (String(url).endsWith("/__bili/?embed=1")) throw new Error("connection refused"); + return { ok: true, json: async () => ({ origin: "http://127.0.0.1:18787" }) }; + }, + setTimeout, + clearTimeout, + }); + m.resetHooks(); + m.component(); + await tick(); + m.component(); + await tick(); + const tree = m.component() as ElementNode; + const texts: string[] = []; + collectText(tree, texts); + const joined = texts.join(" "); + assert.ok(joined.includes("adminRelay"), "the guidance names the adminRelay knob"); + assert.ok(joined.includes("~/.config/billion-context/billion-context.json"), "the guidance names the config file"); + assert.ok(!joined.includes("正在连接"), "the endless connecting state is replaced by actionable guidance"); + assert.equal(findTag(tree, "iframe"), undefined, "no frame while the origin is unreachable by construction"); + assert.equal(findButton(tree), undefined, "the backup button would open a dead loopback link remotely — hidden with the hint"); + m.runCleanups(); + } + // Negative 1: a resolved "ok" verdict outranks the mismatch — same-machine + // access through a LAN IP still reaches the loopback; never shadow a working frame. + { + const m = await mountClient({ + location: { hostname: "192.168.1.50" }, + URL, + open: (_url: string) => {}, + fetch: async (url: string) => { + if (String(url).endsWith("/__bili/?embed=1")) return htmlOk(); + return { ok: true, json: async () => ({ origin: "http://127.0.0.1:18787" }) }; + }, + setTimeout, + clearTimeout, + }); + m.resetHooks(); + m.component(); + await tick(); + m.component(); + await tick(); + const tree = m.component() as ElementNode; + const texts: string[] = []; + collectText(tree, texts); + assert.ok(!texts.join(" ").includes("adminRelay"), "no guidance when the panel actually resolves"); + assert.ok(findTag(tree, "iframe") !== undefined, "the working frame stays"); + m.runCleanups(); + } + // Negative 2: local page (loopback host) + loopback origin — the classic + // desktop posture keeps the plain connecting state. + { + const m = await mountClient({ + location: { hostname: "127.0.0.1" }, + URL, + open: (_url: string) => {}, + fetch: async (url: string) => { + if (String(url).endsWith("/__bili/?embed=1")) throw new Error("connection refused"); + return { ok: true, json: async () => ({ origin: "http://127.0.0.1:18787" }) }; + }, + setTimeout, + clearTimeout, + }); + m.resetHooks(); + m.component(); + await tick(); + m.component(); + await tick(); + const tree = m.component() as ElementNode; + const texts: string[] = []; + collectText(tree, texts); + assert.ok(!texts.join(" ").includes("adminRelay"), "local access gets no remote guidance"); + assert.ok(texts.join(" ").includes("正在连接"), "local posture keeps the connecting state"); + m.runCleanups(); + } + // Negative 3: remote page + NON-loopback origin — a directly exposed proxy + // is plausibly reachable; the adminRelay guidance would mislead. + { + const m = await mountClient({ + location: { hostname: "vps.example.com" }, + URL, + open: (_url: string) => {}, + fetch: async (url: string) => { + if (String(url).endsWith("/__bili/?embed=1")) throw new Error("connection refused"); + return { ok: true, json: async () => ({ origin: "http://203.0.113.5:18787" }) }; + }, + setTimeout, + clearTimeout, + }); + m.resetHooks(); + m.component(); + await tick(); + m.component(); + await tick(); + const tree = m.component() as ElementNode; + const texts: string[] = []; + collectText(tree, texts); + assert.ok(!texts.join(" ").includes("adminRelay"), "non-loopback origins get no adminRelay guidance"); + assert.ok(texts.join(" ").includes("正在连接"), "falls back to the plain connecting state"); + m.runCleanups(); + } + // Negative 4: relay mode under a remote page — same-origin paths are + // reachable by construction; the #3373 flow must not gain a hint. + { + const m = await mountClient({ + __BILI__: { origin: null, relay: true }, + location: { hostname: "vps.example.com" }, + URL, + open: (_url: string) => {}, + fetch: async (url: string) => { + if (String(url).endsWith("/__bili/?embed=1")) return htmlOk(); + return { ok: true, json: async () => ({ origin: null, relay: true }) }; + }, + setTimeout, + clearTimeout, + }); + m.resetHooks(); + m.component(); + await tick(); + m.component(); + await tick(); + const tree = m.component() as ElementNode; + const texts: string[] = []; + collectText(tree, texts); + assert.ok(!texts.join(" ").includes("adminRelay"), "relay mode never shows the opt-in guidance"); + assert.ok(findTag(tree, "iframe") !== undefined, "the relayed frame renders"); + m.runCleanups(); + } +}); From 0e357b806a48cfcf0f65b4aea7209e1ed6d690ab Mon Sep 17 00:00:00 2001 From: awork Date: Mon, 19 Oct 2026 20:35:23 +0800 Subject: [PATCH 2/3] fix: let any resolved embed verdict outrank the #3816 remote-mismatch hint (#3834 review) A resolved stale verdict proves THIS browser reached the loopback origin (same-machine access through a LAN IP): the adminRelay guidance must not shadow the #3100 restart notice nor hide the still-working backup button. remoteBlocked now keys on liveEmbed === undefined (no verdict yet) instead of liveEmbed !== 'ok'. Pinned by the new negative-5 gate row in tests/dsh-settings-ui.test.ts. --- src/agent/dsh-native-client.ts | 10 +++++---- tests/dsh-settings-ui.test.ts | 38 ++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/src/agent/dsh-native-client.ts b/src/agent/dsh-native-client.ts index 9b6a14ffcc..f39db7d800 100644 --- a/src/agent/dsh-native-client.ts +++ b/src/agent/dsh-native-client.ts @@ -424,10 +424,12 @@ export function apply(ctx: ClientContext): void { }, [origin]); const liveEmbed: EmbedVerdict | undefined = embed !== undefined && embed.origin === origin ? embed.verdict : undefined; // #3816: remote page + loopback origin ⇒ unreachable by construction — - // explain the fix instead of spinning on "connecting…". A resolved - // "ok" verdict outranks the mismatch (same-machine access through a - // LAN IP still reaches the loopback) — never shadow a working frame. - const remoteBlocked = remoteMismatch(origin) && liveEmbed !== "ok"; + // explain the fix instead of spinning on "connecting…". ANY resolved + // verdict outranks the mismatch: a verdict means THIS browser actually + // reached the origin (same-machine access through a LAN IP still + // reaches the loopback) — never shadow a working frame or the stale + // notice of a reachable-but-frozen proxy. + const remoteBlocked = remoteMismatch(origin) && liveEmbed === undefined; const lang = t("nav") === zhDict.nav ? "zh" : "en"; // The open-in-browser action button. One shared builder so the two // placements (embedded-tab row, degraded/stale footer) cannot drift: diff --git a/tests/dsh-settings-ui.test.ts b/tests/dsh-settings-ui.test.ts index cd501bfd89..0da3d8504c 100644 --- a/tests/dsh-settings-ui.test.ts +++ b/tests/dsh-settings-ui.test.ts @@ -1392,4 +1392,42 @@ test("#3816: remote page + loopback origin (relay off) shows the adminRelay guid assert.ok(findTag(tree, "iframe") !== undefined, "the relayed frame renders"); m.runCleanups(); } + // Negative 5: remote page + loopback origin + RESOLVED stale verdict — + // the probe answered, so THIS browser reached the loopback (same machine + // through a LAN IP): the #3100 restart notice keeps its place and the + // backup button stays (its loopback link is alive here). + { + const m = await mountClient({ + location: { hostname: "192.168.1.50" }, + URL, + open: (_url: string) => {}, + fetch: async (url: string) => { + if (String(url).endsWith("/__bili/?embed=1")) { + return { + ok: false, + status: 404, + headers: { get: (_k: string) => "application/json; charset=utf-8" }, + json: async () => ({ error: { type: "not_found", message: "no such management endpoint" } }), + }; + } + return { ok: true, json: async () => ({ origin: "http://127.0.0.1:18787" }) }; + }, + setTimeout, + clearTimeout, + }); + m.resetHooks(); + m.component(); + await tick(); + m.component(); + await tick(); + const tree = m.component() as ElementNode; + const texts: string[] = []; + collectText(tree, texts); + assert.ok(!texts.join(" ").includes("adminRelay"), "a reachable-but-stale proxy keeps its own notice, not the relay guidance"); + assert.ok(texts.join(" ").includes("重新启动 dsh"), "the #3100 stale notice survives the remote-page state"); + const btns = collectButtons(tree); + assert.equal(btns.length, 1, "the backup button stays — on this machine the loopback link is alive"); + assert.equal(btns[0].props?.title, "http://127.0.0.1:18787", "the backup button names the live origin"); + m.runCleanups(); + } }); From 3ee4425f8653b2d946c1fb159ea858f7963481ce Mon Sep 17 00:00:00 2001 From: awork Date: Mon, 19 Oct 2026 20:50:36 +0800 Subject: [PATCH 3/3] =?UTF-8?q?feat(web,dsh):=20#3816=20owner=20follow-up?= =?UTF-8?q?=20=E2=80=94=20config-page=20jump=20button=20+=20adminRelay=20e?= =?UTF-8?q?nable=20warning?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Owner ruling on #3816: keep adminRelay opt-in (no default remote access); prompt with the reason, let the user self-serve from the web UI, and warn while they set it. - dsh settings hint (remote page + loopback origin): add an 'Open config page' button jumping to /__bili/#/config in a fresh tab; the hint text mentions it; shares ACTION_BTN_STYLE with the open-in-browser entry so the two buttons cannot drift. - bili panel Config page: a warning banner shows while the editor draft enables security.adminRelay (strict === true, JSONC-tolerant via parseConfigDraft) — driven by refreshDirtyFlag so it follows every editor change and the initial load, before the save lands. Tests: extended the #3816 UI rows (button label/target/click, exactly one button in the state); new tests/web-relay-warn.test.ts (gate truth table incl. truthy-typo negatives + JSONC draft, wiring, shell slot, i18n pins). --- src/agent/dsh-native-client.ts | 50 +++++++++++++++++++++----------- src/web/client.ts | 35 +++++++++++++++++++++++ src/web/i18n.ts | 2 ++ src/web/page.ts | 1 + tests/dsh-settings-ui.test.ts | 16 +++++++++-- tests/web-relay-warn.test.ts | 52 ++++++++++++++++++++++++++++++++++ 6 files changed, 137 insertions(+), 19 deletions(-) create mode 100644 tests/web-relay-warn.test.ts diff --git a/src/agent/dsh-native-client.ts b/src/agent/dsh-native-client.ts index f39db7d800..340a1be443 100644 --- a/src/agent/dsh-native-client.ts +++ b/src/agent/dsh-native-client.ts @@ -95,6 +95,21 @@ const PAGE_KEYS: Record = { const REMOTE_RELAY_SNIPPET = '"security": { "adminRelay": true }'; const EMBED_HEIGHT = "min(640px, 78vh)"; +// One look for the panel's action buttons (footer backup entry, #3816 +// config-page jump) so the placements cannot drift apart visually. +const ACTION_BTN_STYLE = { + cursor: "pointer", + borderRadius: 8, + border: "1px solid rgba(127,127,127,0.4)", + background: "transparent", + color: "inherit", + fontFamily: "inherit", + fontSize: 14, + lineHeight: "22px", + padding: "7px 16px", + whiteSpace: "nowrap", +}; + // #3100: pre-flight for the framed face. Auto-update refreshes the profile // bundle on DISK while the long-running proxy child keeps serving the code it // booted with — and this browser half always runs the freshest disk code — so @@ -218,7 +233,8 @@ const zh: Dict = { "degraded": "当前 dsh 进程未绑定 bili 代理(未经 bili dsh 启动,或代理尚未就绪)——先运行 /acp,或改用 bili dsh 启动。", "connecting": "正在连接 bili 代理…", "stale": "运行中的 bili 代理比已安装的配置文件旧:本页面已加载新版界面,但代理进程仍在提供旧版服务,暂时无法打开内嵌页面。若本应用已运行新版本,启动一个新会话即会自动换上新代理(也可手动结束旧代理进程立即生效);若应用本身还是旧版本,请完全退出并重新启动 dsh。恢复前可点下方按钮直接打开 Web UI。", - "remote_blocked": "本页面通过远程地址访问,而 bili 面板运行在服务器本机的回环地址(127.0.0.1)上——你的浏览器无法直连它(直连会指向你自己的电脑)。要远程打开面板:在服务器上编辑 ~/.config/billion-context/billion-context.json,向顶层对象加入下方字段并保存——本页会在数秒内自动生效(无需重启 dsh,刷新页面同样可以)。", + "remote_blocked": "本页面通过远程地址访问,而 bili 面板运行在服务器本机的回环地址(127.0.0.1)上——你的浏览器无法直连它(直连会指向你自己的电脑)。要远程打开面板:在服务器上编辑 ~/.config/billion-context/billion-context.json,向顶层对象加入下方字段并保存——本页会在数秒内自动生效(无需重启 dsh,刷新页面同样可以);若你能直接访问该面板地址,也可点下方按钮在配置页开启。", + "remote_open_config": "打开配置页", "tab_overview": "总览", "tab_sessions": "会话", "tab_config": "配置", @@ -233,7 +249,8 @@ const en: Dict = { "degraded": "This dsh process is not bound to a bili proxy (not launched via bili dsh, or the proxy is not up yet) — run /acp first, or launch through bili dsh.", "connecting": "Connecting to the bili proxy…", "stale": "The running bili proxy is older than the installed profile: this page already runs the new face, but the proxy process still serves the old build, so the embedded page cannot be opened yet. If this app itself runs the new version, starting a new session swaps in the new proxy automatically (or kill the old proxy process manually for an immediate switch); if the app itself is still on the old version, fully quit and relaunch dsh. Until then, use the button below to open the Web UI directly.", - "remote_blocked": "This page is reached through a remote address, but the bili panel runs on the server's own loopback address (127.0.0.1) — your browser cannot reach it directly (it would point at your own machine). To open the panel remotely: edit ~/.config/billion-context/billion-context.json on the server and add the field below to the top-level object — this page picks it up within seconds (no dsh restart needed; reloading works too).", + "remote_blocked": "This page is reached through a remote address, but the bili panel runs on the server's own loopback address (127.0.0.1) — your browser cannot reach it directly (it would point at your own machine). To open the panel remotely: edit ~/.config/billion-context/billion-context.json on the server and add the field below to the top-level object — this page picks it up within seconds (no dsh restart needed; reloading works too); if you CAN reach that panel address directly, use the button below to enable it from the config page.", + "remote_open_config": "Open config page", "tab_overview": "Overview", "tab_sessions": "Sessions", "tab_config": "Config", @@ -444,29 +461,23 @@ export function apply(ctx: ClientContext): void { type: "button", title: origin, onClick: () => openExternal(`${origin}/__bili/`), - style: { - cursor: "pointer", - borderRadius: 8, - border: "1px solid rgba(127,127,127,0.4)", - background: "transparent", - color: "inherit", - fontFamily: "inherit", - fontSize: 14, - lineHeight: "22px", - padding: "7px 16px", - whiteSpace: "nowrap", - ...style, - }, + style: { ...ACTION_BTN_STYLE, ...style }, }, t("open"), ); let middle: unknown; if (origin === undefined) { middle = createElement("p", { style: { margin: 0, opacity: 0.7, lineHeight: 1.6 } }, t("degraded")); - } else if (remoteBlocked) { + } else if (remoteBlocked && origin !== undefined) { + // The jump button targets the panel's config page (#/config) in a + // fresh tab. For a purely remote browser that address is still + // unreachable — the file-edit text above is the primary route; + // the button serves same-LAN/tunneled access where it lands on + // the exact field to set. + const cfgUrl = `${origin}/__bili/#/config`; middle = createElement( "div", - { style: { display: "flex", flexDirection: "column", gap: 8 } }, + { style: { display: "flex", flexDirection: "column", gap: 8, alignItems: "flex-start" } }, createElement("p", { style: { margin: 0, opacity: 0.7, lineHeight: 1.6 } }, t("remote_blocked")), createElement( "code", @@ -483,6 +494,11 @@ export function apply(ctx: ClientContext): void { }, REMOTE_RELAY_SNIPPET, ), + createElement( + "button", + { type: "button", title: cfgUrl, onClick: () => openExternal(cfgUrl), style: ACTION_BTN_STYLE }, + t("remote_open_config"), + ), ); } else if (liveEmbed === "stale") { middle = createElement("p", { style: { margin: 0, opacity: 0.7, lineHeight: 1.6 } }, t("stale")); diff --git a/src/web/client.ts b/src/web/client.ts index 007795399d..812697de32 100644 --- a/src/web/client.ts +++ b/src/web/client.ts @@ -109,11 +109,28 @@ export function parseConfigDraft(text: string): unknown { return JSON.parse(stripJsoncTrailingCommas(stripJsoncComments(text))); } +// #3816: does this config draft carry an ENABLED admin relay? Strict on the +// value (=== true): "true", 1 and other truthy typos do not count. Malformed +// drafts report false — the parse-error banner owns that state, not this one. +export function adminRelayActiveInDraft(text: string): boolean { + let draft: unknown; + try { + draft = parseConfigDraft(text); + } catch { + return false; + } + if (draft === null || typeof draft !== "object" || Array.isArray(draft)) return false; + const sec = (draft as Record).security; + if (sec === null || sec === undefined || typeof sec !== "object" || Array.isArray(sec)) return false; + return (sec as Record).adminRelay === true; +} + export const WEB_CLIENT = `(function () { "use strict"; const stripJsoncComments = ${stripJsoncComments.toString()}; const stripJsoncTrailingCommas = ${stripJsoncTrailingCommas.toString()}; const parseConfigDraft = ${parseConfigDraft.toString()}; + const adminRelayActiveInDraft = ${adminRelayActiveInDraft.toString()}; const MESSAGES=${JSON.stringify(MESSAGES)}; let locale = "zh-CN"; try { @@ -515,6 +532,24 @@ export const WEB_CLIENT = `(function () { const dirty = Boolean(el && cfgSavedSnap !== null && canonCfgText(el.value) !== canonCfgText(cfgSavedSnap)); ["card-quick", "card-file", "summary-settings"].forEach((id) => { const c = $(id); if (c) c.style.borderColor = dirty ? "#bf8700" : ""; }); document.querySelectorAll(".cfg-dirty-note").forEach((n) => { n.hidden = !dirty; }); + refreshRelayWarn(); + } + // #3816: the admin-relay warning rides every editor change and the initial + // load, so it shows WHILE the user is setting security.adminRelay — before + // the save lands — not only afterwards. + function refreshRelayWarn() { + const el = $("cfg-relay-warn"); + const fe = $("cfg-file-edit"); + if (!el || !fe) return; + if (adminRelayActiveInDraft(fe.value)) { + el.hidden = false; + el.classList.add("show"); + el.textContent = t("cfg.relay_warn"); + } else { + el.hidden = true; + el.classList.remove("show"); + el.textContent = ""; + } } function sessionTitleCell(s) { diff --git a/src/web/i18n.ts b/src/web/i18n.ts index 81e40d1001..a4975646ee 100644 --- a/src/web/i18n.ts +++ b/src/web/i18n.ts @@ -364,6 +364,7 @@ export const MESSAGES: Record> = { "cfg.sub": "修改即时写入配置文件并热生效 · 保存前请确认 JSON 语法", "cfg.file": "配置文件", "cfg.parse_error": "配置文件不是有效 JSON —— 显示为空视图", + "cfg.relay_warn": "草稿中已启用 security.adminRelay(管理中继):任何能访问 dsh Web 入口的人,都能经由它使用完整的 bili 管理面板——包括修改配置与写入凭据。请确认该入口已受登录鉴权或反向代理保护;不再需要时删除该字段即可关闭。", "cfg.upstream_net": "上游网络", "cfg.up_auto": "auto(跟随系统代理)", "cfg.up_manual": "manual(显式代理)", @@ -854,6 +855,7 @@ export const MESSAGES: Record> = { "cfg.sub": "Edits write straight to the config file and hot-apply · check JSON syntax before saving", "cfg.file": "Config file", "cfg.parse_error": "Config file is not valid JSON — showing an empty view", + "cfg.relay_warn": "The draft enables security.adminRelay (admin relay): anyone who can reach the dsh web entry gets the FULL bili admin panel through it — including config edits and credential writes. Make sure that entry is behind login auth or a reverse proxy; remove the field to turn it back off.", "cfg.upstream_net": "Upstream network", "cfg.up_auto": "auto (follow system proxy)", "cfg.up_manual": "manual (explicit proxy)", diff --git a/src/web/page.ts b/src/web/page.ts index ca0eb8fef0..d6ece0eda6 100644 --- a/src/web/page.ts +++ b/src/web/page.ts @@ -87,6 +87,7 @@ export function renderPage(origin: string, version: string, embed = false, theme

${zh("cfg.file_desc")}

${zh("dt.config_file")}
+
diff --git a/tests/dsh-settings-ui.test.ts b/tests/dsh-settings-ui.test.ts index 0da3d8504c..4751919a3d 100644 --- a/tests/dsh-settings-ui.test.ts +++ b/tests/dsh-settings-ui.test.ts @@ -1260,10 +1260,11 @@ test("#3816: remote page + loopback origin (relay off) shows the adminRelay guid // bound origin is the server's loopback — unreachable by construction. // The face must explain the fix instead of spinning on "connecting…". { + const opened: string[] = []; const m = await mountClient({ location: { hostname: "vps.example.com" }, URL, - open: (_url: string) => {}, + open: (url: string) => { opened.push(String(url)); }, fetch: async (url: string) => { if (String(url).endsWith("/__bili/?embed=1")) throw new Error("connection refused"); return { ok: true, json: async () => ({ origin: "http://127.0.0.1:18787" }) }; @@ -1284,7 +1285,18 @@ test("#3816: remote page + loopback origin (relay off) shows the adminRelay guid assert.ok(joined.includes("~/.config/billion-context/billion-context.json"), "the guidance names the config file"); assert.ok(!joined.includes("正在连接"), "the endless connecting state is replaced by actionable guidance"); assert.equal(findTag(tree, "iframe"), undefined, "no frame while the origin is unreachable by construction"); - assert.equal(findButton(tree), undefined, "the backup button would open a dead loopback link remotely — hidden with the hint"); + // #3816 owner follow-up: the hint offers a jump straight to the panel's + // config page — the ONLY button in this state (the footer backup entry + // stays hidden: it would open the same dead loopback address). + const btns = collectButtons(tree); + assert.equal(btns.length, 1, "exactly one action: the config-page jump"); + const btn = btns[0]; + assert.equal(btn.props?.title, "http://127.0.0.1:18787/__bili/#/config", "the jump targets the panel's config page"); + const label: string[] = []; + collectText(btn.children, label); + assert.equal(label.join(""), "打开配置页", "the jump button carries its localized label"); + (btn.props!.onClick as () => void)(); + assert.deepEqual(opened, ["http://127.0.0.1:18787/__bili/#/config"], "clicking opens the config page in a fresh tab"); m.runCleanups(); } // Negative 1: a resolved "ok" verdict outranks the mismatch — same-machine diff --git a/tests/web-relay-warn.test.ts b/tests/web-relay-warn.test.ts new file mode 100644 index 0000000000..74a34f2c54 --- /dev/null +++ b/tests/web-relay-warn.test.ts @@ -0,0 +1,52 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { WEB_CLIENT, adminRelayActiveInDraft } from "../src/web/client.ts"; +import { MESSAGES, LOCALES } from "../src/web/i18n.ts"; +import { renderPage } from "../src/web/page.ts"; + +// #3816 owner follow-up: while the user SETS security.adminRelay in the panel's +// config editor, a warning must be visible. The gate is strict on purpose — +// enabling the relay exposes the FULL admin surface (config edits, credential +// writes) through whoever reaches the dsh web entry, so truthy typos must not +// trip it. +test("#3816: adminRelayActiveInDraft — strict === true only", () => { + assert.equal(adminRelayActiveInDraft('{"security":{"adminRelay":true}}'), true); + assert.equal(adminRelayActiveInDraft('{ "security" : { "adminRelay" : true , "other": 1 } }'), true); + assert.equal(adminRelayActiveInDraft('{"security":{"adminRelay":false}}'), false); + assert.equal(adminRelayActiveInDraft('{"security":{"adminRelay":"true"}}'), false); + assert.equal(adminRelayActiveInDraft('{"security":{"adminRelay":1}}'), false); + assert.equal(adminRelayActiveInDraft('{"security":{}}'), false); + assert.equal(adminRelayActiveInDraft('{"security":true}'), false); + assert.equal(adminRelayActiveInDraft("{}"), false); + assert.equal(adminRelayActiveInDraft("[]"), false); + assert.equal(adminRelayActiveInDraft('"str"'), false); + assert.equal(adminRelayActiveInDraft("null"), false); + assert.equal(adminRelayActiveInDraft(""), false); + assert.equal(adminRelayActiveInDraft("{"), false); + assert.equal(adminRelayActiveInDraft('{"a": '), false); +}); + +test("#3816: JSONC-tolerant drafts still detect the enabled relay", () => { + const draft = "// enable relay\n{\n \"security\": {\n \"adminRelay\": true,\n }\n}\n"; + assert.equal(adminRelayActiveInDraft(draft), true); +}); + +test("#3816: the config page warns while the draft enables the relay", () => { + assert.ok(WEB_CLIENT.includes("const adminRelayActiveInDraft = "), "the IIFE embeds the relay gate"); + assert.ok(WEB_CLIENT.includes('$("cfg-relay-warn")'), "the client targets the warning slot"); + assert.ok(WEB_CLIENT.includes('t("cfg.relay_warn")'), "the warning text is localized"); + const dirty = WEB_CLIENT.indexOf("function refreshDirtyFlag()"); + assert.ok(dirty >= 0, "refreshDirtyFlag present"); + const body = WEB_CLIENT.slice(dirty, dirty + 900); + assert.ok(body.includes("refreshRelayWarn();"), "every editor change re-evaluates the relay warning"); + const ui = renderPage("http://127.0.0.1:1", "0.0.0-test"); + assert.match(ui, /id="cfg-relay-warn" class="banner warn"/); + for (const locale of LOCALES) { + assert.ok( + typeof MESSAGES[locale]["cfg.relay_warn"] === "string" && MESSAGES[locale]["cfg.relay_warn"].length > 0, + `cfg.relay_warn missing in ${locale}`, + ); + } + assert.ok(!/\p{Script=Han}/u.test(MESSAGES.en["cfg.relay_warn"]), "en value has no Chinese residue"); + assert.ok(/adminRelay/.test(MESSAGES["zh-CN"]["cfg.relay_warn"]), "zh names the knob"); +});