From c89c50219e2f9e4b2ef5d5e81717152c7a9394e3 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Wed, 28 Oct 2026 21:47:39 +0100 Subject: [PATCH 1/3] feat(settings): Mobile app card backed by /api/mobile-access --- app/api/mobile-access/route.ts | 40 +++++++ components/SettingsConfig.tsx | 102 ++++++++++++++++ lib/api-contract.test.mjs | 13 ++ lib/i18n/locales/en.json | 24 ++++ lib/i18n/locales/ja.json | 24 ++++ lib/i18n/locales/zh-CN.json | 24 ++++ lib/mobile-access.test.mjs | 141 ++++++++++++++++++++++ lib/mobile-access.ts | 212 +++++++++++++++++++++++++++++++++ 8 files changed, 580 insertions(+) create mode 100644 app/api/mobile-access/route.ts create mode 100644 lib/mobile-access.test.mjs create mode 100644 lib/mobile-access.ts diff --git a/app/api/mobile-access/route.ts b/app/api/mobile-access/route.ts new file mode 100644 index 000000000..44f22605a --- /dev/null +++ b/app/api/mobile-access/route.ts @@ -0,0 +1,40 @@ +import { NextResponse } from "next/server"; +import { networkInterfaces } from "node:os"; +import { + candidateAddresses, + classifyExposure, + DEFAULT_MOBILE_PORT, + detectBindHostname, + mobileAccessMethods, + parseMobilePort, + probeMagicDnsName, +} from "@/lib/mobile-access"; +import { isWebPasswordEnabled, webPasswordConfigurationProblem } from "@/lib/web-auth"; + +export const dynamic = "force-dynamic"; + +/** + * GET /api/mobile-access — read-only facts for Settings → Mobile app. The + * endpoint cannot change the binding and never returns the password (only + * whether one is configured). + */ +export async function GET(req: Request) { + const hostname = detectBindHostname(); + const port = parseMobilePort(new URL(req.url).port) ?? parseMobilePort(process.env.PORT) ?? DEFAULT_MOBILE_PORT; + // Optional and time-boxed inside the helper: a missing tailscale binary + // resolves without spawning, and a slow one is cut off by its timeout. + const magicDnsName = await probeMagicDnsName(); + return NextResponse.json({ + binding: { + hostname, + exposure: classifyExposure(hostname), + port, + }, + password: { + configured: isWebPasswordEnabled(), + problem: webPasswordConfigurationProblem() !== null, + }, + addresses: candidateAddresses({ interfaces: networkInterfaces(), port, magicDnsName }), + methods: mobileAccessMethods(), + }); +} diff --git a/components/SettingsConfig.tsx b/components/SettingsConfig.tsx index 77f7240db..45fd9a547 100644 --- a/components/SettingsConfig.tsx +++ b/components/SettingsConfig.tsx @@ -349,6 +349,106 @@ function AgentToolsSetting() { ); } +type MobileAccessData = { + binding: { hostname: string | null; exposure: "loopback" | "network" | "unknown"; port: number }; + password: { configured: boolean; problem: boolean }; + addresses: Array<{ url: string; label: "magicdns" | "tailscale" | "lan" }>; + methods: Array<{ id: "cli" | "windowsTray" | "systemd" | "launchd"; commands: string[] }>; +}; + +/** Read-only guide for the Android app: binding, password state, addresses, exact commands. */ +function MobileAppCard() { + const { t } = useI18n(); + const [data, setData] = useState(null); + const [failed, setFailed] = useState(false); + useEffect(() => { + let alive = true; + fetch("/api/mobile-access") + .then((res) => (res.ok ? res.json() as Promise : Promise.reject(new Error(`HTTP ${res.status}`)))) + .then((next) => { if (alive) setData(next); }) + .catch(() => { if (alive) setFailed(true); }); + return () => { alive = false; }; + }, []); + const bindingText = data === null ? "" + : t(`settingsConfig.mobileAppBinding.${data.binding.exposure}`, { + hostname: data.binding.hostname ?? "—", + port: String(data.binding.port), + }); + const methodTitleKey: Record = { + cli: "settingsConfig.mobileAppCli", + windowsTray: "settingsConfig.mobileAppWindowsTray", + systemd: "settingsConfig.mobileAppSystemd", + launchd: "settingsConfig.mobileAppLaunchd", + }; + const methodHintKey: Record = { + cli: "settingsConfig.mobileAppCliHint", + windowsTray: "settingsConfig.mobileAppWindowsTrayHint", + systemd: "settingsConfig.mobileAppSystemdHint", + launchd: "settingsConfig.mobileAppLaunchdHint", + }; + return ( +
+
+
{t("settingsConfig.mobileAppTitle")}
+
{t("settingsConfig.mobileAppDesc")}
+
+ {failed && } + {data !== null && ( + <> +
+
{bindingText}
+
{data.password.problem ? t("settingsConfig.mobileAppPasswordProblem") : data.password.configured ? t("settingsConfig.mobileAppPasswordSet") : t("settingsConfig.mobileAppPasswordMissing")}
+ {data.binding.exposure !== "network" &&
{t("settingsConfig.mobileAppNetworkHint")}
} +
+
+
{t("settingsConfig.mobileAppAddresses")}
+ {data.addresses.length === 0 + ?
{t("settingsConfig.mobileAppNoAddresses")}
+ : data.addresses.map((address) => ( +
+ {address.url} + {t(`settingsConfig.mobileAppLabel.${address.label}`)} + +
+ ))} +
+
+
{t("settingsConfig.mobileAppSteps")}
+ {data.methods.map((method) => ( +
+
{t(methodTitleKey[method.id])}
+
{t(methodHintKey[method.id])}
+ {method.commands.map((command) => ( +
+ {command} + +
+ ))} +
+ ))} +
+ + )} +
+ ); +} + /** Server-side omp-web setting (issue #104): KEY=VALUE text injected into the * `omp` child process. Parsing/validation lives in lib/omp/agent-env.ts; this only * feeds it localized messages and renders the result. */ @@ -1770,6 +1870,8 @@ export function SettingsConfig({ activeTab, toolCallsDefaultCollapsed, onToolCal + + {/* ompweb app update card */}
diff --git a/lib/api-contract.test.mjs b/lib/api-contract.test.mjs index f5b3298e9..91d446e6d 100644 --- a/lib/api-contract.test.mjs +++ b/lib/api-contract.test.mjs @@ -229,3 +229,16 @@ test("new-session route never forwards a session id into the child RPC", async ( const route = await readFile(new URL("../app/api/agent/new/route.ts", import.meta.url), "utf8"); assert.match(route, /delete promptCommand\.sessionId/); }); + +test("the tailscale probe runs a fixed binary with a sanitized environment", async () => { + const source = await readFile(new URL("./mobile-access.ts", import.meta.url), "utf8"); + + // A PATH lookup ran whatever a project, an npm `bin` directory or + // ~/.local/bin provided — with this server's environment, which holds + // OMP_WEB_PASSWORD_HASH. Only fixed install locations may be executed. + assert.doesNotMatch(source, /process\.env\.PATH/); + assert.match(source, /"\/usr\/bin\/tailscale"/); + assert.match(source, /"Tailscale IPN", "tailscale\.exe"/); + // Same rule as ps/PowerShell: child processes never inherit the secrets. + assert.match(source, /env: createChildProcessEnvironment\(\)/); +}); diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index 1ad043f14..4ed89a618 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -115,6 +115,30 @@ "settingsConfig.agentTools": "Agent tools (cross-session)", "settingsConfig.agentToolsDesc": "Allow agents to call list_sessions, new_session and send_to_session to reach other omp-web sessions, even with no browser tab open. Messages delivered this way are prefixed with the sending session's ID. A per-session rate limit and a chain-depth limit stop sessions looping messages to each other. Applies to sessions started or reconnected after saving.", "settingsConfig.agentToolsSaveFailed": "Could not save the agent tools setting", + "settingsConfig.mobileAppTitle": "Mobile app", + "settingsConfig.mobileAppDesc": "The Android app connects to this server directly. Use one of the addresses below, then sign in with your ompweb password.", + "settingsConfig.mobileAppBinding.loopback": "Server binding: {hostname}:{port} (loopback only).", + "settingsConfig.mobileAppBinding.network": "Server binding: {hostname}:{port} (reachable from your network).", + "settingsConfig.mobileAppBinding.unknown": "Server binding: unknown (port {port}).", + "settingsConfig.mobileAppPasswordSet": "Password protection is configured.", + "settingsConfig.mobileAppPasswordMissing": "No password is configured. Set one before exposing this server to the network.", + "settingsConfig.mobileAppPasswordProblem": "The password configuration is broken. Fix it before connecting a phone.", + "settingsConfig.mobileAppNetworkHint": "The server is not listening on the network. Restart it with one of the commands below and use the network address.", + "settingsConfig.mobileAppAddresses": "Addresses", + "settingsConfig.mobileAppNoAddresses": "No network address was found. Connect a network interface or start Tailscale.", + "settingsConfig.mobileAppLabel.magicdns": "Tailscale MagicDNS", + "settingsConfig.mobileAppLabel.tailscale": "Tailscale", + "settingsConfig.mobileAppLabel.lan": "Local network", + "settingsConfig.mobileAppSteps": "Expose this server", + "settingsConfig.mobileAppCli": "Command line", + "settingsConfig.mobileAppCliHint": "Generate a password hash, then start ompweb on all interfaces. The hash is not echoed.", + "settingsConfig.mobileAppWindowsTray": "Windows tray app", + "settingsConfig.mobileAppWindowsTrayHint": "Store the hash for your user, then install the tray app bound to all interfaces.", + "settingsConfig.mobileAppSystemd": "systemd service", + "settingsConfig.mobileAppSystemdHint": "The installer hashes the password and writes the unit. A network binding is refused without a password.", + "settingsConfig.mobileAppLaunchd": "launchd service", + "settingsConfig.mobileAppLaunchdHint": "The installer hashes the password and writes the plist. A network binding is refused without a password.", + "settingsConfig.mobileAppLoadFailed": "Could not load the mobile access details.", "settingsConfig.agentEnv": "Agent environment variables", "settingsConfig.agentEnvDesc": "Extra environment variables handed to the omp process, for example the API key an MCP server needs. One KEY=VALUE per line; # comments and blank lines are ignored.", "settingsConfig.agentEnvNote": "Saved values are injected when a session starts. Sessions that are already running keep the environment they started with, so restart them to pick up the new values. Variables omp-web needs itself (PATH, HOME, PI_CODING_AGENT_DIR, OMP_WEB_*, and similar) cannot be set here.", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index af23a236a..1645d9221 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -112,6 +112,30 @@ "settingsConfig.autoResumeSessionsSaveFailed": "再開設定を保存できませんでした", "settingsConfig.autoResumeSessionsDesc": "エージェントの作業中に omp-web が再起動した場合、それらのセッションを再開し、各エージェントに「Session interrupted and resumed. Continue as you would have done without the interruption.」と伝えます。再起動の時点で進行中だった作業(実行中のコマンドなど)は失われます。", "settingsConfig.autoResumeSessions": "再起動後に実行中のセッションを再開", + "settingsConfig.mobileAppTitle": "モバイルアプリ", + "settingsConfig.mobileAppDesc": "Android アプリはこのサーバーに直接接続します。以下のアドレスを使用し、ompweb のパスワードでサインインしてください。", + "settingsConfig.mobileAppBinding.loopback": "サーバーのバインド: {hostname}:{port}(ループバックのみ)。", + "settingsConfig.mobileAppBinding.network": "サーバーのバインド: {hostname}:{port}(ネットワークから到達可能)。", + "settingsConfig.mobileAppBinding.unknown": "サーバーのバインド: 不明(ポート {port})。", + "settingsConfig.mobileAppPasswordSet": "パスワード保護が設定されています。", + "settingsConfig.mobileAppPasswordMissing": "パスワードが設定されていません。ネットワークに公開する前に設定してください。", + "settingsConfig.mobileAppPasswordProblem": "パスワード設定が壊れています。スマートフォンを接続する前に修正してください。", + "settingsConfig.mobileAppNetworkHint": "サーバーはネットワークで待ち受けていません。以下のコマンドのいずれかで再起動し、ネットワークアドレスを使用してください。", + "settingsConfig.mobileAppAddresses": "アドレス", + "settingsConfig.mobileAppNoAddresses": "ネットワークアドレスが見つかりません。ネットワークインターフェースを接続するか Tailscale を起動してください。", + "settingsConfig.mobileAppLabel.magicdns": "Tailscale MagicDNS", + "settingsConfig.mobileAppLabel.tailscale": "Tailscale", + "settingsConfig.mobileAppLabel.lan": "ローカルネットワーク", + "settingsConfig.mobileAppSteps": "このサーバーを公開する", + "settingsConfig.mobileAppCli": "コマンドライン", + "settingsConfig.mobileAppCliHint": "パスワードハッシュを生成し、すべてのインターフェースで ompweb を起動します。ハッシュは画面に表示されません。", + "settingsConfig.mobileAppWindowsTray": "Windows トレイアプリ", + "settingsConfig.mobileAppWindowsTrayHint": "ユーザーのハッシュを保存し、すべてのインターフェースにバインドしたトレイアプリをインストールします。", + "settingsConfig.mobileAppSystemd": "systemd サービス", + "settingsConfig.mobileAppSystemdHint": "インストーラーがパスワードをハッシュ化してユニットを書き込みます。ネットワークバインドではパスワードなしでは拒否されます。", + "settingsConfig.mobileAppLaunchd": "launchd サービス", + "settingsConfig.mobileAppLaunchdHint": "インストーラーがパスワードをハッシュ化して plist を書き込みます。ネットワークバインドではパスワードなしでは拒否されます。", + "settingsConfig.mobileAppLoadFailed": "モバイルアクセスの詳細を読み込めませんでした。", "settingsConfig.agentEnv": "エージェントの環境変数", "settingsConfig.agentEnvDesc": "omp プロセスに渡される追加の環境変数です(例: MCP サーバーが必要とする API キー)。1 行につき 1 つの KEY=VALUE を記述します。# で始まる行と空行は無視されます。", "settingsConfig.agentEnvNote": "保存した値はセッションの開始時に注入されます。実行中のセッションは開始時の環境のままなので、新しい値を反映するには再起動してください。omp-web 自身が必要とする変数(PATH、HOME、PI_CODING_AGENT_DIR、OMP_WEB_* など)はここでは設定できません。", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index 75878b912..26712fd7f 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -112,6 +112,30 @@ "settingsConfig.autoResumeSessionsSaveFailed": "无法保存恢复设置", "settingsConfig.autoResumeSessionsDesc": "如果 omp-web 在智能体工作时重启,将重新启动这些会话并告知每个智能体:“Session interrupted and resumed. Continue as you would have done without the interruption.”重启时正在进行的工作(例如正在运行的命令)会丢失。", "settingsConfig.autoResumeSessions": "重启后恢复正在运行的会话", + "settingsConfig.mobileAppTitle": "移动应用", + "settingsConfig.mobileAppDesc": "Android 应用直接连接此服务器。使用下面的地址,并用你的 ompweb 密码登录。", + "settingsConfig.mobileAppBinding.loopback": "服务器绑定:{hostname}:{port}(仅回环)。", + "settingsConfig.mobileAppBinding.network": "服务器绑定:{hostname}:{port}(可从网络访问)。", + "settingsConfig.mobileAppBinding.unknown": "服务器绑定:未知(端口 {port})。", + "settingsConfig.mobileAppPasswordSet": "已配置密码保护。", + "settingsConfig.mobileAppPasswordMissing": "未配置密码。在将此服务器暴露到网络之前请设置密码。", + "settingsConfig.mobileAppPasswordProblem": "密码配置已损坏。连接手机前请修复。", + "settingsConfig.mobileAppNetworkHint": "服务器未在网络监听。请用下面的命令之一重启,并使用网络地址。", + "settingsConfig.mobileAppAddresses": "地址", + "settingsConfig.mobileAppNoAddresses": "未找到网络地址。请连接网络接口或启动 Tailscale。", + "settingsConfig.mobileAppLabel.magicdns": "Tailscale MagicDNS", + "settingsConfig.mobileAppLabel.tailscale": "Tailscale", + "settingsConfig.mobileAppLabel.lan": "局域网", + "settingsConfig.mobileAppSteps": "公开此服务器", + "settingsConfig.mobileAppCli": "命令行", + "settingsConfig.mobileAppCliHint": "生成密码哈希,然后在所有接口上启动 ompweb。哈希不会回显。", + "settingsConfig.mobileAppWindowsTray": "Windows 托盘应用", + "settingsConfig.mobileAppWindowsTrayHint": "为你的用户保存哈希,然后安装绑定所有接口的托盘应用。", + "settingsConfig.mobileAppSystemd": "systemd 服务", + "settingsConfig.mobileAppSystemdHint": "安装程序会哈希密码并写入 unit。绑定网络时没有密码会拒绝安装。", + "settingsConfig.mobileAppLaunchd": "launchd 服务", + "settingsConfig.mobileAppLaunchdHint": "安装程序会哈希密码并写入 plist。绑定网络时没有密码会拒绝安装。", + "settingsConfig.mobileAppLoadFailed": "无法加载移动访问详情。", "settingsConfig.agentEnv": "智能体环境变量", "settingsConfig.agentEnvDesc": "传递给 omp 进程的额外环境变量,例如 MCP 服务器所需的 API 密钥。每行一个 KEY=VALUE;以 # 开头的行和空行会被忽略。", "settingsConfig.agentEnvNote": "保存的值会在会话启动时注入。正在运行的会话仍使用启动时的环境,需要重启后才会生效。omp-web 自身依赖的变量(PATH、HOME、PI_CODING_AGENT_DIR、OMP_WEB_* 等)无法在此设置。", diff --git a/lib/mobile-access.test.mjs b/lib/mobile-access.test.mjs new file mode 100644 index 000000000..2cdb498e1 --- /dev/null +++ b/lib/mobile-access.test.mjs @@ -0,0 +1,141 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { delimiter, isAbsolute, join } from "node:path"; +import test from "node:test"; +import { createJiti } from "jiti"; + +const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); +const { + candidateAddresses, + classifyExposure, + DEFAULT_MOBILE_PORT, + detectBindHostname, + isTailscaleIpv4, + mobileAccessMethods, + parseMagicDns, + parseMobilePort, +} = await jiti.import("./mobile-access.ts"); + +// Only the fields the candidate scan reads; a netmask/mac fixture would only +// add address-shaped literals that are not part of the contract. +const iface = (address, { internal = false, family = "IPv4" } = {}) => ({ address, family, internal }); + +test("port parsing accepts only real TCP ports", () => { + assert.equal(parseMobilePort("30177"), 30177); + assert.equal(parseMobilePort(443), 443); + assert.equal(parseMobilePort("0"), null); + assert.equal(parseMobilePort("65536"), null); + assert.equal(parseMobilePort("12x"), null); + assert.equal(parseMobilePort(""), null); + assert.equal(parseMobilePort(undefined), null); +}); + +test("bind hostname comes from the documented env override, then Next's -H flag", () => { + assert.equal(detectBindHostname({ OMP_WEB_HOSTNAME: "0.0.0.0" }, ["node", "server", "-H", "127.0.0.1"]), "0.0.0.0"); + assert.equal(detectBindHostname({}, ["next", "dev", "-H", "0.0.0.0"]), "0.0.0.0"); + // leak-gate:allow ip-private-range — synthetic LAN fixture + assert.equal(detectBindHostname({}, ["next", "start", "--hostname=192.168.1.5"]), "192.168.1.5"); + assert.equal(detectBindHostname({}, ["next", "start"]), null); +}); + +test("exposure distinguishes loopback, wildcard/network and an unknown dev server", () => { + assert.equal(classifyExposure("127.0.0.1"), "loopback"); + assert.equal(classifyExposure("localhost"), "loopback"); + assert.equal(classifyExposure("::1"), "loopback"); + assert.equal(classifyExposure("0.0.0.0"), "network"); + // leak-gate:allow ip-private-range — synthetic LAN fixture + assert.equal(classifyExposure("192.168.1.5"), "network"); + assert.equal(classifyExposure(null), "unknown"); +}); + +test("addresses skip loopback/link-local and put MagicDNS, then Tailscale, then LAN", () => { + // Synthetic fixtures only: RFC 1918, link-local and CGNAT addresses. + const interfaces = { + "Loopback Pseudo-Interface 1": [iface("127.0.0.1", { internal: true })], + Ethernet: [iface("192.168.178.20"), iface("169.254.10.5"), iface("fe80::1", { family: "IPv6" })], // leak-gate:allow ip-private-range + "Tailscale": [iface("100.101.102.103")], // leak-gate:allow ip-private-range + WLAN: [iface("192.168.178.21", { family: 4 })], // leak-gate:allow ip-private-range + }; + assert.deepEqual(candidateAddresses({ interfaces, port: 30177, magicDnsName: "pc.tailnet.ts.net." }), [ + { url: "http://pc.tailnet.ts.net:30177", label: "magicdns" }, + { url: "http://100.101.102.103:30177", label: "tailscale" }, // leak-gate:allow ip-private-range + { url: "http://192.168.178.20:30177", label: "lan" }, // leak-gate:allow ip-private-range + { url: "http://192.168.178.21:30177", label: "lan" }, // leak-gate:allow ip-private-range + ]); +}); + +test("no interfaces still returns the MagicDNS address; duplicate addresses appear once", () => { + assert.deepEqual(candidateAddresses({ interfaces: {}, port: 30177, magicDnsName: "pc.tailnet.ts.net" }), [ + { url: "http://pc.tailnet.ts.net:30177", label: "magicdns" }, + ]); + const interfaces = { Tailscale: [iface("100.64.0.1")], WLAN: [iface("100.64.0.1")] }; // leak-gate:allow ip-private-range + assert.deepEqual(candidateAddresses({ interfaces, port: 1 }).map((entry) => entry.url), ["http://100.64.0.1:1"]); // leak-gate:allow ip-private-range +}); + +test("Tailscale CGNAT detection is 100.64.0.0/10 only", () => { + assert.equal(isTailscaleIpv4("100.64.0.1"), true); // leak-gate:allow ip-private-range + assert.equal(isTailscaleIpv4("100.127.255.254"), true); // leak-gate:allow ip-private-range + // The first address past 100.64.0.0/10 is a public one. + assert.equal(isTailscaleIpv4("100.128.0.1"), false); // leak-gate:allow ip-public ip-private-range + assert.equal(isTailscaleIpv4("192.168.1.2"), false); // leak-gate:allow ip-private-range +}); + +test("MagicDNS parsing accepts only a plausible Self.DNSName", () => { + assert.equal(parseMagicDns(JSON.stringify({ Self: { DNSName: "pc.tailnet.ts.net." } })), "pc.tailnet.ts.net"); + assert.equal(parseMagicDns(JSON.stringify({ Self: { DNSName: " " } })), null); + assert.equal(parseMagicDns(JSON.stringify({ Self: { DNSName: "bad name" } })), null); + assert.equal(parseMagicDns(JSON.stringify({ Self: {} })), null); + assert.equal(parseMagicDns(JSON.stringify({})), null); + assert.equal(parseMagicDns("not json"), null); +}); + +test("tailscale is resolved from its install location, never from PATH", async (t) => { + const { tailscaleBinary } = await jiti.import("./mobile-access.ts"); + const fakeDir = mkdtempSync(join(tmpdir(), "omp-web-tailscale-")); + const fake = join(fakeDir, process.platform === "win32" ? "tailscale.exe" : "tailscale"); + writeFileSync(fake, ""); + const previousPath = process.env.PATH; + process.env.PATH = `${fakeDir}${delimiter}${previousPath ?? ""}`; + t.after(() => { + if (previousPath === undefined) delete process.env.PATH; + else process.env.PATH = previousPath; + rmSync(fakeDir, { recursive: true, force: true }); + }); + + // A PATH entry (a project, an npm bin, ~/.local/bin) must never be executed: + // it would run with the server's environment and could read the login hash. + const binary = tailscaleBinary(); + assert.notEqual(binary, fake); + if (binary !== null) assert.ok(isAbsolute(binary), `${binary} must be an absolute install path`); +}); + +test("every start mode carries exact commands and no real secret", () => { + const methods = mobileAccessMethods(); + assert.deepEqual(methods.map((method) => method.id), ["cli", "windowsTray", "systemd", "launchd"]); + assert.ok(methods.every((method) => method.commands.length >= 1 && method.commands.every((command) => typeof command === "string" && command.length > 0))); + assert.equal(DEFAULT_MOBILE_PORT, 30177); + const joined = methods.flatMap((method) => method.commands).join("\n"); + assert.match(joined, /ompweb hash-password/); + assert.match(joined, /ompweb-systemd install/); + assert.match(joined, /ompweb-launchd install/); + assert.match(joined, /ompweb --install-tray/); + assert.doesNotMatch(joined, /scrypt\$1\$/); +}); + +test("the route reports binding, password state, addresses and methods without secrets", async () => { + const route = await jiti.import("../app/api/mobile-access/route.ts"); + const response = await route.GET(new Request("http://localhost:30999/api/mobile-access")); + assert.equal(response.status, 200); + const body = await response.json(); + assert.equal(body.binding.port, 30999); + assert.ok(["loopback", "network", "unknown"].includes(body.binding.exposure)); + assert.equal(typeof body.password.configured, "boolean"); + assert.equal(typeof body.password.problem, "boolean"); + assert.ok(Array.isArray(body.addresses)); + assert.ok(body.addresses.every((address) => address.url.startsWith("http://") && address.url.endsWith(":30999") && ["magicdns", "tailscale", "lan"].includes(address.label))); + assert.deepEqual(body.methods.map((method) => method.id), ["cli", "windowsTray", "systemd", "launchd"]); + const configured = (process.env.OMP_WEB_PASSWORD_HASH ?? "").trim(); + if (configured) assert.equal(JSON.stringify(body).includes(configured), false, "the configured hash never leaves the server"); + assert.match(body.methods[0].commands.join("\n"), /scrypt\$…/); +}); diff --git a/lib/mobile-access.ts b/lib/mobile-access.ts new file mode 100644 index 000000000..b0f7eb159 --- /dev/null +++ b/lib/mobile-access.ts @@ -0,0 +1,212 @@ +import { execFile } from "node:child_process"; +import { networkInterfaces } from "node:os"; +import { join } from "node:path"; +import { existsSync } from "node:fs"; +import { createChildProcessEnvironment } from "./project-command-env"; + +/** + * Read-only data for Settings → Mobile app: how the server is bound, whether a + * password is configured, which addresses a phone can type in, and the exact + * commands that expose an installed server to the network. + * + * The endpoint never changes the binding and never returns a credential — only + * whether a password hash is configured. + */ + +export type MobileExposure = "loopback" | "network" | "unknown"; +export type MobileAddressLabel = "magicdns" | "tailscale" | "lan"; + +export interface MobileAddress { + url: string; + label: MobileAddressLabel; +} + +export interface MobileAccessMethod { + id: "cli" | "windowsTray" | "systemd" | "launchd"; + commands: string[]; +} + +export const DEFAULT_MOBILE_PORT = 30177; +const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1", "[::1]", "0:0:0:0:0:0:0:1", "[0:0:0:0:0:0:0:1]"]); +const WILDCARD_HOSTS = new Set(["0.0.0.0", "::", "[::]", "0:0:0:0:0:0:0:0", "[0:0:0:0:0:0:0:0]", ""]); + +export function parseMobilePort(value: unknown): number | null { + const port = typeof value === "number" ? value : typeof value === "string" && /^\d{1,5}$/.test(value.trim()) ? Number(value.trim()) : NaN; + return Number.isInteger(port) && port >= 1 && port <= 65535 ? port : null; +} + +/** Next.js `-H/--hostname` is the only launch-time bind information a route can see. */ +export function detectBindHostname(env: NodeJS.ProcessEnv = process.env, argv: string[] = process.argv): string | null { + const fromEnv = env.OMP_WEB_HOSTNAME?.trim(); + if (fromEnv) return fromEnv; + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + if (arg === "-H" || arg === "--hostname") { + const value = argv[i + 1]?.trim(); + if (value) return value; + } + if (arg.startsWith("--hostname=")) { + const value = arg.slice("--hostname=".length).trim(); + if (value) return value; + } + } + return null; +} + +export function classifyExposure(hostname: string | null): MobileExposure { + if (hostname === null) return "unknown"; + const host = hostname.trim().toLowerCase(); + if (WILDCARD_HOSTS.has(host)) return "network"; + if (host.startsWith("127.") || LOOPBACK_HOSTS.has(host)) return "loopback"; + return "network"; +} + +export function isTailscaleIpv4(address: string): boolean { + const parts = address.split(".").map(Number); + return parts.length === 4 && parts.every((part) => Number.isInteger(part)) && parts[0] === 100 && parts[1] >= 64 && parts[1] <= 127; +} + +function isCandidateAddress(address: string): boolean { + if (address.startsWith("127.") || address.startsWith("169.254.") || /^198\.(18|19)\./.test(address)) return false; + return address.split(".").length === 4; +} + +/** + * Addresses to type into the app: Tailscale first (MagicDNS, then 100.64/10 + * addresses), then other non-internal IPv4s. No loopback: a phone cannot use it. + */ +export function candidateAddresses({ + interfaces, + port, + magicDnsName, +}: { + interfaces: ReturnType; + port: number; + magicDnsName?: string | null; +}): MobileAddress[] { + const magic = magicDnsName?.trim().replace(/\.$/, ""); + const magicdn: MobileAddress[] = magic ? [{ url: `http://${magic}:${port}`, label: "magicdns" }] : []; + const tailscale: MobileAddress[] = []; + const lan: MobileAddress[] = []; + const seen = new Set(); + for (const [name, infos] of Object.entries(interfaces)) { + for (const info of infos ?? []) { + // `family` is "IPv4" on modern Node and 4 on older versions. + if (info.family !== "IPv4" && String(info.family) !== "4") continue; + if (info.internal || seen.has(info.address) || !isCandidateAddress(info.address)) continue; + seen.add(info.address); + const entry = { url: `http://${info.address}:${port}`, label: "tailscale" as const }; + if (isTailscaleIpv4(info.address) || name.toLowerCase().includes("tailscale")) tailscale.push(entry); + else lan.push({ url: `http://${info.address}:${port}`, label: "lan" }); + } + } + return [...magicdn, ...tailscale, ...lan]; +} + +/** Never throw: `tailscale status --json` is optional and time-boxed. */ +export function parseMagicDns(stdout: string): string | null { + try { + const parsed: unknown = JSON.parse(stdout); + if (!parsed || typeof parsed !== "object" || !("Self" in parsed)) return null; + const self = parsed.Self; + if (!self || typeof self !== "object" || !("DNSName" in self)) return null; + const dnsName = self.DNSName; + if (typeof dnsName !== "string") return null; + const name = dnsName.trim().replace(/\.$/, ""); + return /^[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?$/.test(name) ? name : null; + } catch { + return null; + } +} + +let magicDnsCache: { at: number; name: string | null } | undefined; + +/** + * Fixed install locations only. A PATH lookup would run whatever a project, an + * npm `bin` directory or `~/.local/bin` provides — with this server's + * environment — so a `tailscale` there could read the web password hash from + * `process.env` and forward it. Without one of these paths, Settings → Mobile + * app simply shows no MagicDNS name (the address list still works). + */ +export function tailscaleBinary(): string | null { + const candidates = process.platform === "win32" + ? [ + join(process.env.ProgramFiles || "C:\\Program Files", "Tailscale", "tailscale.exe"), + join(process.env.ProgramFiles || "C:\\Program Files", "Tailscale IPN", "tailscale.exe"), + ] + : [ + "/usr/bin/tailscale", + "/usr/local/bin/tailscale", + "/opt/homebrew/bin/tailscale", + // The macOS app ships the CLI inside the bundle and installs no symlink. + "/Applications/Tailscale.app/Contents/MacOS/Tailscale", + ]; + for (const candidate of candidates) { + try { + if (existsSync(candidate)) return candidate; + } catch { + // An unreadable candidate is simply not one. + } + } + return null; +} + +/** MagicDNS name of this machine, cached for a minute. Absent binary → null without spawning. */ +export async function probeMagicDnsName(timeoutMs = 1500): Promise { + if (magicDnsCache && Date.now() - magicDnsCache.at < 60_000) return magicDnsCache.name; + const binary = tailscaleBinary(); + if (!binary) { + magicDnsCache = { at: Date.now(), name: null }; + return null; + } + const { promise, resolve } = Promise.withResolvers(); + execFile(binary, ["status", "--json"], { + timeout: timeoutMs, + windowsHide: true, + maxBuffer: 2 * 1024 * 1024, + // The child never sees omp-web's own secrets (issue #239). + env: createChildProcessEnvironment(), + }, (error, stdout) => { + resolve(error ? null : parseMagicDns(stdout)); + }); + const name = await promise; + magicDnsCache = { at: Date.now(), name }; + return name; +} + +/** + * Exact commands from the installers and `ompweb --help`; nothing invented. + * `scrypt$…` stands for the output of `ompweb hash-password` (stdin, so it + * never reaches the shell history or `ps`). + */ +export function mobileAccessMethods(): MobileAccessMethod[] { + return [ + { + id: "cli", + commands: [ + "ompweb hash-password", + "OMP_WEB_PASSWORD_HASH='scrypt$…' ompweb -H 0.0.0.0", + ], + }, + { + id: "windowsTray", + commands: [ + "ompweb hash-password", + "setx OMP_WEB_PASSWORD_HASH \"scrypt$…\"", + "ompweb --install-tray -H 0.0.0.0", + ], + }, + { + id: "systemd", + commands: [ + "OMP_WEB_HOSTNAME=0.0.0.0 OMP_WEB_PASSWORD='…' ompweb-systemd install", + ], + }, + { + id: "launchd", + commands: [ + "OMP_WEB_HOSTNAME=0.0.0.0 OMP_WEB_PASSWORD='…' ompweb-launchd install", + ], + }, + ]; +} From a0c2a8bc40adbac8140be3f95b05627d52c3c5ed Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Wed, 28 Oct 2026 21:47:39 +0100 Subject: [PATCH 2/3] =?UTF-8?q?docs(changelog):=20Settings=20=E2=86=92=20M?= =?UTF-8?q?obile=20app?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f25ddce22..d85b50b2a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ## [Unreleased] +### Added + +- **Settings → Mobile app tells you how to reach this server from a phone.** The new `GET /api/mobile-access` reports the binding (`-H`/`OMP_WEB_HOSTNAME`), whether a password is configured, the addresses a phone can type in (Tailscale MagicDNS when `tailscale` is installed, then Tailscale and LAN IPv4s, never loopback) and the exact install commands for the CLI, the Windows tray, systemd and launchd. It never changes the binding and never returns a credential — only whether the hash is present. The Tailscale probe runs a fixed install path with a sanitized environment, so a `tailscale` binary on `PATH` cannot read the server's secrets. + ### Fixes & Improvements - **In-app updates work when ompweb runs as a systemd service.** The update worker ran inside the service's cgroup, so stopping the server killed the worker too: nothing was installed, the service could stay down (`Restart=on-failure` does not restart a clean SIGTERM exit), and every page load reopened the update dialog at "Stop ompweb-managed sessions". The worker now runs in its own transient scope (`systemd-run --scope`) and stops, updates and starts the unit through `systemctl`, starting it again if the install fails. From 942acecf497b930c7f75196115d730ced6049f0c Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Thu, 29 Oct 2026 00:51:24 +0100 Subject: [PATCH 3/3] test: drop tooling comments --- lib/mobile-access.test.mjs | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/lib/mobile-access.test.mjs b/lib/mobile-access.test.mjs index 2cdb498e1..f73f71699 100644 --- a/lib/mobile-access.test.mjs +++ b/lib/mobile-access.test.mjs @@ -34,7 +34,6 @@ test("port parsing accepts only real TCP ports", () => { test("bind hostname comes from the documented env override, then Next's -H flag", () => { assert.equal(detectBindHostname({ OMP_WEB_HOSTNAME: "0.0.0.0" }, ["node", "server", "-H", "127.0.0.1"]), "0.0.0.0"); assert.equal(detectBindHostname({}, ["next", "dev", "-H", "0.0.0.0"]), "0.0.0.0"); - // leak-gate:allow ip-private-range — synthetic LAN fixture assert.equal(detectBindHostname({}, ["next", "start", "--hostname=192.168.1.5"]), "192.168.1.5"); assert.equal(detectBindHostname({}, ["next", "start"]), null); }); @@ -44,7 +43,6 @@ test("exposure distinguishes loopback, wildcard/network and an unknown dev serve assert.equal(classifyExposure("localhost"), "loopback"); assert.equal(classifyExposure("::1"), "loopback"); assert.equal(classifyExposure("0.0.0.0"), "network"); - // leak-gate:allow ip-private-range — synthetic LAN fixture assert.equal(classifyExposure("192.168.1.5"), "network"); assert.equal(classifyExposure(null), "unknown"); }); @@ -53,15 +51,15 @@ test("addresses skip loopback/link-local and put MagicDNS, then Tailscale, then // Synthetic fixtures only: RFC 1918, link-local and CGNAT addresses. const interfaces = { "Loopback Pseudo-Interface 1": [iface("127.0.0.1", { internal: true })], - Ethernet: [iface("192.168.178.20"), iface("169.254.10.5"), iface("fe80::1", { family: "IPv6" })], // leak-gate:allow ip-private-range - "Tailscale": [iface("100.101.102.103")], // leak-gate:allow ip-private-range - WLAN: [iface("192.168.178.21", { family: 4 })], // leak-gate:allow ip-private-range + Ethernet: [iface("192.168.178.20"), iface("169.254.10.5"), iface("fe80::1", { family: "IPv6" })], + "Tailscale": [iface("100.101.102.103")], + WLAN: [iface("192.168.178.21", { family: 4 })], }; assert.deepEqual(candidateAddresses({ interfaces, port: 30177, magicDnsName: "pc.tailnet.ts.net." }), [ { url: "http://pc.tailnet.ts.net:30177", label: "magicdns" }, - { url: "http://100.101.102.103:30177", label: "tailscale" }, // leak-gate:allow ip-private-range - { url: "http://192.168.178.20:30177", label: "lan" }, // leak-gate:allow ip-private-range - { url: "http://192.168.178.21:30177", label: "lan" }, // leak-gate:allow ip-private-range + { url: "http://100.101.102.103:30177", label: "tailscale" }, + { url: "http://192.168.178.20:30177", label: "lan" }, + { url: "http://192.168.178.21:30177", label: "lan" }, ]); }); @@ -69,16 +67,16 @@ test("no interfaces still returns the MagicDNS address; duplicate addresses appe assert.deepEqual(candidateAddresses({ interfaces: {}, port: 30177, magicDnsName: "pc.tailnet.ts.net" }), [ { url: "http://pc.tailnet.ts.net:30177", label: "magicdns" }, ]); - const interfaces = { Tailscale: [iface("100.64.0.1")], WLAN: [iface("100.64.0.1")] }; // leak-gate:allow ip-private-range - assert.deepEqual(candidateAddresses({ interfaces, port: 1 }).map((entry) => entry.url), ["http://100.64.0.1:1"]); // leak-gate:allow ip-private-range + const interfaces = { Tailscale: [iface("100.64.0.1")], WLAN: [iface("100.64.0.1")] }; + assert.deepEqual(candidateAddresses({ interfaces, port: 1 }).map((entry) => entry.url), ["http://100.64.0.1:1"]); }); test("Tailscale CGNAT detection is 100.64.0.0/10 only", () => { - assert.equal(isTailscaleIpv4("100.64.0.1"), true); // leak-gate:allow ip-private-range - assert.equal(isTailscaleIpv4("100.127.255.254"), true); // leak-gate:allow ip-private-range + assert.equal(isTailscaleIpv4("100.64.0.1"), true); + assert.equal(isTailscaleIpv4("100.127.255.254"), true); // The first address past 100.64.0.0/10 is a public one. - assert.equal(isTailscaleIpv4("100.128.0.1"), false); // leak-gate:allow ip-public ip-private-range - assert.equal(isTailscaleIpv4("192.168.1.2"), false); // leak-gate:allow ip-private-range + assert.equal(isTailscaleIpv4("100.128.0.1"), false); + assert.equal(isTailscaleIpv4("192.168.1.2"), false); }); test("MagicDNS parsing accepts only a plausible Self.DNSName", () => {