Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 96 additions & 15 deletions src/agent/dsh-native-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,28 @@ const PAGE_KEYS: Record<PageId, string> = {
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)";

// 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
Expand Down Expand Up @@ -213,6 +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_open_config": "打开配置页",
"tab_overview": "总览",
"tab_sessions": "会话",
"tab_config": "配置",
Expand All @@ -227,6 +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); 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",
Expand Down Expand Up @@ -262,6 +286,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
Expand Down Expand Up @@ -387,6 +440,13 @@ 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…". 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:
Expand All @@ -401,25 +461,45 @@ 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 && 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, alignItems: "flex-start" } },
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,
),
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"));
} else if (liveEmbed === "ok") {
Expand Down Expand Up @@ -483,8 +563,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(),
),
);
};
Expand Down
35 changes: 35 additions & 0 deletions src/web/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>).security;
if (sec === null || sec === undefined || typeof sec !== "object" || Array.isArray(sec)) return false;
return (sec as Record<string, unknown>).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 {
Expand Down Expand Up @@ -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) {
Expand Down
2 changes: 2 additions & 0 deletions src/web/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,7 @@ export const MESSAGES: Record<Locale, Record<string, string>> = {
"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(显式代理)",
Expand Down Expand Up @@ -854,6 +855,7 @@ export const MESSAGES: Record<Locale, Record<string, string>> = {
"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)",
Expand Down
1 change: 1 addition & 0 deletions src/web/page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ export function renderPage(origin: string, version: string, embed = false, theme
<p class="dim small" style="margin:0 0 8px" data-i18n="cfg.file_desc">${zh("cfg.file_desc")}</p>
<dl class="kv"><div class="k" data-i18n="dt.config_file">${zh("dt.config_file")}</div><div class="v" style="display:flex;gap:8px;align-items:center;flex-wrap:wrap"><span id="cfg-path" class="mono dim small"></span><button id="copy-cfg-file" class="btn sm copy-btn" data-copy=""><span data-i18n="common.copy">${zh("common.copy")}</span></button></div></dl>
<textarea id="cfg-file-edit" class="editor mono codebox" spellcheck="false"></textarea>
<div id="cfg-relay-warn" class="banner warn" style="margin-top:10px" hidden></div>
<div class="cfg-dirty-note small" style="margin-top:10px;color:#9a6700" hidden><span data-i18n="cfg.unsaved">${zh("cfg.unsaved")}</span></div>
<div style="margin-top:10px"><button id="save-file" class="btn"><span data-i18n="cfg.save">${zh("cfg.save")}</span></button></div>
</div></div>
Expand Down
Loading
Loading