From ad137e182bb258dac206a0b16c27cf817ecd1b3d Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Fri, 6 Nov 2026 05:25:48 +0100 Subject: [PATCH 1/6] feat(settings): Mobile app card backed by /api/mobile-access MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `GET /api/mobile-access` reports how this server is bound, whether a password is configured (never the password itself), the addresses a phone can use — Tailscale MagicDNS, Tailscale and LAN — and the exact commands that expose the server on each install method. It is read-only: the endpoint cannot change the binding. Settings gains a "Mobile app" card that renders that answer, so a user can point the Android app at this server without guessing the URL or the binding state. The probe for a MagicDNS name is time-boxed and resolves without spawning when tailscale is absent. --- app/api/mobile-access/route.ts | 37 ++++++ components/SettingsConfig.tsx | 106 +++++++++++++++++ lib/i18n/locales/en.json | 26 +++- lib/i18n/locales/ja.json | 26 +++- lib/i18n/locales/zh-CN.json | 26 +++- lib/mobile-access.test.mjs | 139 +++++++++++++++++++++ lib/mobile-access.ts | 212 +++++++++++++++++++++++++++++++++ server/routes.ts | 2 + 8 files changed, 571 insertions(+), 3 deletions(-) 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..61efbda6b --- /dev/null +++ b/app/api/mobile-access/route.ts @@ -0,0 +1,37 @@ +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"; + +/** + * 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 Response.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 04af234fa..3b5b3d015 100644 --- a/components/SettingsConfig.tsx +++ b/components/SettingsConfig.tsx @@ -48,6 +48,110 @@ const AgentsConfig = dynamic(() => import("./AgentsConfig").then((module) => mod const HostsConfig = dynamic(() => import("./HostsConfig").then((module) => module.HostsConfig), { loading: SettingsTabLoading }); const UsageConfig = dynamic(() => import("./UsageConfig").then((module) => module.UsageConfig), { loading: SettingsTabLoading }); +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. */ + type WindowsServiceStatus = { isWindows: boolean; isInstalled: boolean; @@ -2030,6 +2134,8 @@ export function SettingsConfig({ activeTab, toolCallsDefaultCollapsed, onToolCal {appUpdateMessage && setAppUpdateMessage(null)} />} + + {/* Windows Background Service & System Tray card (Windows only) */} {windowsService?.isWindows && (
diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index d7f84bdfc..0f82a5ae7 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -2045,5 +2045,29 @@ "modelsConfig.accountApiKey": "API key", "modelsConfig.disconnectAccount": "Disconnect {label}", "modelsConfig.disconnectAccountTitle": "Disconnect account?", - "modelsConfig.disconnectAccountBody": "omp will delete the stored credential for {label}. Other accounts for this provider stay connected." + "modelsConfig.disconnectAccountBody": "omp will delete the stored credential for {label}. Other accounts for this provider stay connected.", + "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." } diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index d3016efef..13a457464 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -2005,5 +2005,29 @@ "modelsConfig.accountApiKey": "APIキー", "modelsConfig.disconnectAccount": "{label} を切断", "modelsConfig.disconnectAccountTitle": "アカウントを切断しますか?", - "modelsConfig.disconnectAccountBody": "omp は {label} の保存済み資格情報を削除します。このプロバイダーの他のアカウントは接続されたままです。" + "modelsConfig.disconnectAccountBody": "omp は {label} の保存済み資格情報を削除します。このプロバイダーの他のアカウントは接続されたままです。", + "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": "モバイルアクセスの詳細を読み込めませんでした。" } diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index 0307bfb1a..f2b621c17 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -2005,5 +2005,29 @@ "modelsConfig.accountApiKey": "API 密钥", "modelsConfig.disconnectAccount": "断开 {label}", "modelsConfig.disconnectAccountTitle": "断开账户?", - "modelsConfig.disconnectAccountBody": "omp 将删除 {label} 的已存储凭据。此提供商的其他账户保持连接。" + "modelsConfig.disconnectAccountBody": "omp 将删除 {label} 的已存储凭据。此提供商的其他账户保持连接。", + "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": "无法加载移动访问详情。" } diff --git a/lib/mobile-access.test.mjs b/lib/mobile-access.test.mjs new file mode 100644 index 000000000..f73f71699 --- /dev/null +++ b/lib/mobile-access.test.mjs @@ -0,0 +1,139 @@ +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"); + 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"); + 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" })], + "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" }, + { url: "http://192.168.178.20:30177", label: "lan" }, + { url: "http://192.168.178.21:30177", label: "lan" }, + ]); +}); + +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")] }; + 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); + 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); + assert.equal(isTailscaleIpv4("192.168.1.2"), false); +}); + +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", + ], + }, + ]; +} diff --git a/server/routes.ts b/server/routes.ts index c87c165e4..f41aa7dff 100644 --- a/server/routes.ts +++ b/server/routes.ts @@ -35,6 +35,7 @@ import * as hostsIdMaintenance from "@/app/api/hosts/[id]/maintenance/route"; import * as manifest from "@/app/api/manifest/route"; import * as mcp from "@/app/api/mcp/route"; import * as mediaHash from "@/app/api/media/[hash]/route"; +import * as mobileAccess from "@/app/api/mobile-access/route"; import * as modelRoles from "@/app/api/model-roles/route"; import * as modelsConfigCatalog from "@/app/api/models-config/catalog/route"; import * as modelsConfig from "@/app/api/models-config/route"; @@ -139,6 +140,7 @@ export const ROUTE_MODULES: Record = { "manifest": manifest, "mcp": mcp, "media/[hash]": mediaHash, + "mobile-access": mobileAccess, "model-roles": modelRoles, "models-config/catalog": modelsConfigCatalog, "models-config": modelsConfig, From d20f9d28105d6ebef3698fe18b2a531c79359dfe Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:27:00 +0100 Subject: [PATCH 2/6] fix(settings): bound port, binding-aware addresses, and secret-free setup MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Maintainer triage of #412 raised four points; each is fixed where the probe exercised it: - The route resolves the port from `OMP_WEB_PORT` first. `startProduction` writes it from the bound listener, so it is the actual port; the request URL only carries what a proxy forwarded in `Host`, and `PORT` is the launcher's intent. Behind a proxy or a nondefault `--port` launch the card now suggests the address the server really listens on. - `candidateAddresses` reuses `bin/network-addresses.js` (`getAccessibleAddresses`) instead of a second interface enumeration. That enumeration ignored the binding: a specific-IP bind offered every interface address, and a loopback bind offered addresses a phone cannot reach. The helper's `Local` entry is dropped (loopback is useless to a phone), and a loopback/unknown bind now yields no address at all — MagicDNS included, since that name resolves to an address this server is not listening on. - The setup commands no longer put a secret on a command line. `ompweb hash-password` reads the password at a hidden prompt; the hash is pasted into a second hidden prompt (`read -rsp` / `Read-Host -AsSecureString`) and reaches the installer through the environment. All four installers accept `OMP_WEB_PASSWORD_HASH`, so the plaintext is never exported. The i18n hints in en/ja/zh-CN say so instead of implying that secrets never enter history. - The credential-leak test sets a known hash itself and restores the environment afterwards, so the assertion runs on every machine instead of only where a hash happened to be configured. A deliberate `leakedHash` response mutation now fails the test. Adds regression tests for the port precedence, the binding-aware address list (specific-IP, loopback, wildcard), the hidden-prompt commands, and the leak assertion. --- app/api/mobile-access/route.ts | 20 +++++- lib/i18n/locales/en.json | 10 +-- lib/i18n/locales/ja.json | 10 +-- lib/i18n/locales/zh-CN.json | 10 +-- lib/mobile-access.test.mjs | 117 ++++++++++++++++++++++++++------- lib/mobile-access.ts | 96 ++++++++++++++++++--------- 6 files changed, 191 insertions(+), 72 deletions(-) diff --git a/app/api/mobile-access/route.ts b/app/api/mobile-access/route.ts index 61efbda6b..36cf1109c 100644 --- a/app/api/mobile-access/route.ts +++ b/app/api/mobile-access/route.ts @@ -10,6 +10,22 @@ import { } from "@/lib/mobile-access"; import { isWebPasswordEnabled, webPasswordConfigurationProblem } from "@/lib/web-auth"; +/** + * The port this server is actually listening on. + * + * `OMP_WEB_PORT` is written by `startProduction` from the bound listener, so it + * is the authoritative value for a production launch (`npm start`, the binary + * and the launcher all go through it). The request URL's port is only as good + * as the `Host` header a proxy forwards, and `PORT` is the launcher's *intent*, + * not what the socket ended up on. Order: bound port, then the URL, then PORT. + */ +function resolveServerPort(req: Request): number { + return parseMobilePort(process.env.OMP_WEB_PORT) + ?? parseMobilePort(new URL(req.url).port) + ?? parseMobilePort(process.env.PORT) + ?? DEFAULT_MOBILE_PORT; +} + /** * GET /api/mobile-access — read-only facts for Settings → Mobile app. The * endpoint cannot change the binding and never returns the password (only @@ -17,7 +33,7 @@ import { isWebPasswordEnabled, webPasswordConfigurationProblem } from "@/lib/web */ export async function GET(req: Request) { const hostname = detectBindHostname(); - const port = parseMobilePort(new URL(req.url).port) ?? parseMobilePort(process.env.PORT) ?? DEFAULT_MOBILE_PORT; + const port = resolveServerPort(req); // 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(); @@ -31,7 +47,7 @@ export async function GET(req: Request) { configured: isWebPasswordEnabled(), problem: webPasswordConfigurationProblem() !== null, }, - addresses: candidateAddresses({ interfaces: networkInterfaces(), port, magicDnsName }), + addresses: candidateAddresses({ hostname, port, magicDnsName, interfaces: networkInterfaces() }), methods: mobileAccessMethods(), }); } diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index 0f82a5ae7..b75e8dd05 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -2056,18 +2056,18 @@ "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.mobileAppNoAddresses": "No address a phone can reach was found. Expose the server to the network with one of the commands below, 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.mobileAppCliHint": "Generate a hash at a hidden prompt, paste it into a second hidden prompt, then start ompweb on all interfaces. Neither the password nor the hash is echoed or kept in the shell history.", "settingsConfig.mobileAppWindowsTray": "Windows tray app", - "settingsConfig.mobileAppWindowsTrayHint": "Store the hash for your user, then install the tray app bound to all interfaces.", + "settingsConfig.mobileAppWindowsTrayHint": "Generate a hash, paste it into a hidden prompt that stores it for your user, then install the tray app bound to all interfaces. The hash never appears on a command line.", "settingsConfig.mobileAppSystemd": "systemd service", - "settingsConfig.mobileAppSystemdHint": "The installer hashes the password and writes the unit. A network binding is refused without a password.", + "settingsConfig.mobileAppSystemdHint": "Paste the hash into a hidden prompt, then run the installer; it 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.mobileAppLaunchdHint": "Paste the hash into a hidden prompt, then run the installer; it writes the plist. A network binding is refused without a password.", "settingsConfig.mobileAppLoadFailed": "Could not load the mobile access details." } diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index 13a457464..38cecd4bd 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -2016,18 +2016,18 @@ "settingsConfig.mobileAppPasswordProblem": "パスワード設定が壊れています。スマートフォンを接続する前に修正してください。", "settingsConfig.mobileAppNetworkHint": "サーバーはネットワークで待ち受けていません。以下のコマンドのいずれかで再起動し、ネットワークアドレスを使用してください。", "settingsConfig.mobileAppAddresses": "アドレス", - "settingsConfig.mobileAppNoAddresses": "ネットワークアドレスが見つかりません。ネットワークインターフェースを接続するか Tailscale を起動してください。", + "settingsConfig.mobileAppNoAddresses": "スマートフォンから到達できるアドレスが見つかりません。以下のコマンドでサーバーをネットワークに公開するか、Tailscale を起動してください。", "settingsConfig.mobileAppLabel.magicdns": "Tailscale MagicDNS", "settingsConfig.mobileAppLabel.tailscale": "Tailscale", "settingsConfig.mobileAppLabel.lan": "ローカルネットワーク", "settingsConfig.mobileAppSteps": "このサーバーを公開する", "settingsConfig.mobileAppCli": "コマンドライン", - "settingsConfig.mobileAppCliHint": "パスワードハッシュを生成し、すべてのインターフェースで ompweb を起動します。ハッシュは画面に表示されません。", + "settingsConfig.mobileAppCliHint": "非表示のプロンプトでハッシュを生成し、2 つ目の非表示プロンプトに貼り付けてから、すべてのインターフェースで ompweb を起動します。パスワードもハッシュも表示されず、シェル履歴にも残りません。", "settingsConfig.mobileAppWindowsTray": "Windows トレイアプリ", - "settingsConfig.mobileAppWindowsTrayHint": "ユーザーのハッシュを保存し、すべてのインターフェースにバインドしたトレイアプリをインストールします。", + "settingsConfig.mobileAppWindowsTrayHint": "ハッシュを生成し、ユーザー用に保存する非表示のプロンプトに貼り付けてから、すべてのインターフェースにバインドしたトレイアプリをインストールします。ハッシュがコマンドラインに現れることはありません。", "settingsConfig.mobileAppSystemd": "systemd サービス", - "settingsConfig.mobileAppSystemdHint": "インストーラーがパスワードをハッシュ化してユニットを書き込みます。ネットワークバインドではパスワードなしでは拒否されます。", + "settingsConfig.mobileAppSystemdHint": "ハッシュを非表示のプロンプトに貼り付けてからインストーラーを実行すると、ユニットが書き込まれます。ネットワークバインドではパスワードなしでは拒否されます。", "settingsConfig.mobileAppLaunchd": "launchd サービス", - "settingsConfig.mobileAppLaunchdHint": "インストーラーがパスワードをハッシュ化して plist を書き込みます。ネットワークバインドではパスワードなしでは拒否されます。", + "settingsConfig.mobileAppLaunchdHint": "ハッシュを非表示のプロンプトに貼り付けてからインストーラーを実行すると、plist が書き込まれます。ネットワークバインドではパスワードなしでは拒否されます。", "settingsConfig.mobileAppLoadFailed": "モバイルアクセスの詳細を読み込めませんでした。" } diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index f2b621c17..cb00367f6 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -2016,18 +2016,18 @@ "settingsConfig.mobileAppPasswordProblem": "密码配置已损坏。连接手机前请修复。", "settingsConfig.mobileAppNetworkHint": "服务器未在网络监听。请用下面的命令之一重启,并使用网络地址。", "settingsConfig.mobileAppAddresses": "地址", - "settingsConfig.mobileAppNoAddresses": "未找到网络地址。请连接网络接口或启动 Tailscale。", + "settingsConfig.mobileAppNoAddresses": "未找到手机可访问的地址。请用下面的命令将服务器暴露到网络,或启动 Tailscale。", "settingsConfig.mobileAppLabel.magicdns": "Tailscale MagicDNS", "settingsConfig.mobileAppLabel.tailscale": "Tailscale", "settingsConfig.mobileAppLabel.lan": "局域网", "settingsConfig.mobileAppSteps": "公开此服务器", "settingsConfig.mobileAppCli": "命令行", - "settingsConfig.mobileAppCliHint": "生成密码哈希,然后在所有接口上启动 ompweb。哈希不会回显。", + "settingsConfig.mobileAppCliHint": "在隐藏提示中生成哈希,将其粘贴到第二个隐藏提示中,然后在所有接口上启动 ompweb。密码和哈希都不会回显,也不会留在 shell 历史中。", "settingsConfig.mobileAppWindowsTray": "Windows 托盘应用", - "settingsConfig.mobileAppWindowsTrayHint": "为你的用户保存哈希,然后安装绑定所有接口的托盘应用。", + "settingsConfig.mobileAppWindowsTrayHint": "生成哈希,将其粘贴到为用户保存的隐藏提示中,然后安装绑定所有接口的托盘应用。哈希绝不会出现在命令行上。", "settingsConfig.mobileAppSystemd": "systemd 服务", - "settingsConfig.mobileAppSystemdHint": "安装程序会哈希密码并写入 unit。绑定网络时没有密码会拒绝安装。", + "settingsConfig.mobileAppSystemdHint": "将哈希粘贴到隐藏提示中,然后运行安装程序,它会写入 unit。绑定网络时没有密码会拒绝安装。", "settingsConfig.mobileAppLaunchd": "launchd 服务", - "settingsConfig.mobileAppLaunchdHint": "安装程序会哈希密码并写入 plist。绑定网络时没有密码会拒绝安装。", + "settingsConfig.mobileAppLaunchdHint": "将哈希粘贴到隐藏提示中,然后运行安装程序,它会写入 plist。绑定网络时没有密码会拒绝安装。", "settingsConfig.mobileAppLoadFailed": "无法加载移动访问详情。" } diff --git a/lib/mobile-access.test.mjs b/lib/mobile-access.test.mjs index f73f71699..dd53b5c5c 100644 --- a/lib/mobile-access.test.mjs +++ b/lib/mobile-access.test.mjs @@ -11,7 +11,6 @@ const { classifyExposure, DEFAULT_MOBILE_PORT, detectBindHostname, - isTailscaleIpv4, mobileAccessMethods, parseMagicDns, parseMobilePort, @@ -55,7 +54,10 @@ test("addresses skip loopback/link-local and put MagicDNS, then Tailscale, then "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." }), [ + // A wildcard bind is the only case that lists interfaces; the helper's + // "Local" (loopback) entry is dropped because a phone cannot reach it, and + // Tailscale is listed before LAN (a phone away from home needs it first). + assert.deepEqual(candidateAddresses({ hostname: "0.0.0.0", 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" }, { url: "http://192.168.178.20:30177", label: "lan" }, @@ -63,20 +65,35 @@ test("addresses skip loopback/link-local and put MagicDNS, then Tailscale, then ]); }); +test("a specific-IP bind offers that address only, a loopback bind none", () => { + // The regression the maintainer probed: a duplicate enumeration ignored the + // binding and offered every interface address for a single-IP bind. + const interfaces = { + Ethernet: [iface("192.168.178.20")], + "Tailscale": [iface("100.101.102.103")], + WLAN: [iface("192.168.178.21")], + }; + assert.deepEqual(candidateAddresses({ hostname: "192.168.178.21", interfaces, port: 30177 }), [ + { url: "http://192.168.178.21:30177", label: "lan" }, + ]); + + // Loopback: the helper reports the local URL and a hint; a phone gets nothing + // usable, so the card shows no address rather than a 127.0.0.1 one. MagicDNS + // is suppressed too: that name resolves to an address this server is not + // listening on, so offering it would promise a reachability that is absent. + assert.deepEqual(candidateAddresses({ hostname: "127.0.0.1", interfaces, port: 30177, magicDnsName: "pc.tailnet.ts.net" }), []); + assert.deepEqual(candidateAddresses({ hostname: null, interfaces, port: 30177 }), []); +}); + test("no interfaces still returns the MagicDNS address; duplicate addresses appear once", () => { - assert.deepEqual(candidateAddresses({ interfaces: {}, port: 30177, magicDnsName: "pc.tailnet.ts.net" }), [ + assert.deepEqual(candidateAddresses({ hostname: "0.0.0.0", 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")] }; - 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); - 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); - assert.equal(isTailscaleIpv4("192.168.1.2"), false); + assert.deepEqual( + candidateAddresses({ hostname: "0.0.0.0", interfaces, port: 1 }).map((entry) => entry.url), + ["http://100.64.0.1:1"], + ); }); test("MagicDNS parsing accepts only a plausible Self.DNSName", () => { @@ -119,21 +136,71 @@ test("every start mode carries exact commands and no real secret", () => { assert.match(joined, /ompweb-launchd install/); assert.match(joined, /ompweb --install-tray/); assert.doesNotMatch(joined, /scrypt\$1\$/); + // No command carries a value: a plaintext password or a hash on the command + // line would land in the shell history and in `ps`. Each install method + // reads the hash at a hidden prompt instead. + for (const command of methods.flatMap((method) => method.commands)) { + assert.doesNotMatch(command, /OMP_WEB_PASSWORD(_HASH)?=['"]/, `command must not assign a secret inline: ${command}`); + } + assert.match(joined, /read -rsp 'OMP_WEB_PASSWORD_HASH: '/); + assert.match(joined, /Read-Host -AsSecureString/); }); +/** Run `body` with the given environment variables set, restoring them after. */ +async function withEnv(vars, body) { + const previous = {}; + for (const [name, value] of Object.entries(vars)) { + previous[name] = process.env[name]; + process.env[name] = value; + } + try { + return await body(); + } finally { + for (const [name, value] of Object.entries(previous)) { + if (value === undefined) delete process.env[name]; + else process.env[name] = value; + } + } +} + +// A well-formed hash this build accepts. Fixed, so the leak assertion below +// runs whether or not the calling environment has a password configured. +const KNOWN_HASH = "scrypt$12$8$1$BwcHBwcHBwcHBwcHBwcHBw$CQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQk"; + 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\$…/); + await withEnv({ OMP_WEB_PASSWORD_HASH: KNOWN_HASH }, async () => { + 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)); + // The test sets the hash itself, so this asserts the contract instead of + // skipping when the machine happens to have no password configured. + assert.equal(body.password.configured, true); + assert.equal(body.password.problem, false); + 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"]); + assert.equal(JSON.stringify(body).includes(KNOWN_HASH), false, "the configured hash never leaves the server"); + assert.equal(JSON.stringify(body).includes("CQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQk"), false, "not even the digest half"); + }); +}); + +test("the route prefers the bound port over the request URL and PORT", async () => { + const route = await jiti.import("../app/api/mobile-access/route.ts"); + // Production records the actual listener in OMP_WEB_PORT (server/app.ts). + // Behind a proxy the request URL names the proxy's port, and PORT is only + // the launcher's intent, so both must lose against the bound port. + await withEnv({ OMP_WEB_PORT: "30180", PORT: "30181" }, async () => { + const body = await (await route.GET(new Request("http://localhost:30999/api/mobile-access"))).json(); + assert.equal(body.binding.port, 30180); + assert.ok(body.addresses.every((address) => address.url.endsWith(":30180"))); + }); + + // No bound port (dev server): the request URL is the next best fact. + await withEnv({ OMP_WEB_PORT: undefined, PORT: "30181" }, async () => { + const body = await (await route.GET(new Request("http://localhost:30999/api/mobile-access"))).json(); + assert.equal(body.binding.port, 30999); + }); }); diff --git a/lib/mobile-access.ts b/lib/mobile-access.ts index b0f7eb159..1edf39917 100644 --- a/lib/mobile-access.ts +++ b/lib/mobile-access.ts @@ -1,7 +1,8 @@ import { execFile } from "node:child_process"; -import { networkInterfaces } from "node:os"; +import { networkInterfaces, type NetworkInterfaceInfo } from "node:os"; import { join } from "node:path"; import { existsSync } from "node:fs"; +import { getAccessibleAddresses } from "../bin/network-addresses"; import { createChildProcessEnvironment } from "./project-command-env"; /** @@ -61,44 +62,63 @@ export function classifyExposure(hostname: string | null): MobileExposure { 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; -} +/** + * The map `os.networkInterfaces()` returns, named so callers and tests do not + * have to spell out (or infer) the Node type at every call site. + */ +export type NetworkInterfaceMap = Record; /** - * 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. + * Addresses to type into the app, from the same binding-aware enumeration the + * launcher prints (`bin/network-addresses.js`): a specific-IP bind yields that + * one address, a loopback bind yields none a phone can use, and a wildcard + * bind yields the interface addresses. Duplicating the enumeration here once + * offered six interface addresses for a single-IP bind. + * + * Two deliberate differences from the launcher's list: + * + * - The `Local` entry (`http://localhost:…`) is dropped: a phone cannot reach + * this machine's loopback, and the card is addressed to a phone. + * - Tailscale addresses come before LAN ones. The launcher prints LAN first + * because that is the common case for a browser; a phone that is away from + * home needs the Tailscale address, so it is listed first here. + * + * MagicDNS is prepended when Tailscale reports a name. */ export function candidateAddresses({ - interfaces, + hostname, port, magicDnsName, + interfaces = networkInterfaces(), }: { - interfaces: ReturnType; + hostname: string | null; port: number; magicDnsName?: string | null; + interfaces?: NetworkInterfaceMap; }): MobileAddress[] { const magic = magicDnsName?.trim().replace(/\.$/, ""); const magicdn: MobileAddress[] = magic ? [{ url: `http://${magic}:${port}`, label: "magicdns" }] : []; + // `null` means the launch flags were not visible. The default bind is + // loopback, so listing interface addresses would advertise a reachability + // this server may not have; the card says "unknown" and shows no address. + const { entries, hint } = getAccessibleAddresses({ hostname: hostname ?? "127.0.0.1", port, interfaces }); + // The helper's hint is its own "not exposed to the network" signal (it is + // set for a loopback bind). Nothing it lists is reachable from a phone then, + // MagicDNS included: that name resolves to an address this server is not + // listening on. The card's network hint tells the user to rebind instead. + if (hint) return []; 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" }); - } + for (const entry of entries) { + if (seen.has(entry.url)) continue; + // `Local` is loopback: right for the browser, unreachable from a phone. + if (entry.label === "Local") continue; + seen.add(entry.url); + // The helper labels a Tailscale address by interface or CGNAT range; both + // arrive as "Tailscale". Everything else is a bound name or a LAN address. + if (entry.label === "Tailscale") tailscale.push({ url: entry.url, label: "tailscale" }); + else lan.push({ url: entry.url, label: "lan" }); } return [...magicdn, ...tailscale, ...lan]; } @@ -176,36 +196,52 @@ export async function probeMagicDnsName(timeoutMs = 1500): Promise