diff --git a/AGENTS.md b/AGENTS.md index dfc78bbcb..10e1c523a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -147,6 +147,7 @@ app/api/ models/route.ts GET { models, modelList, defaultModel } models-config/route.ts GET/PUT — read/write ~/.omp/agent/models.yml models-config/test/route.ts POST test a configured model/provider + mobile-access/route.ts GET read-only Settings → Mobile app facts: bound hostname/port, exposure, password-configured boolean, phone-reachable addresses (MagicDNS/Tailscale/LAN) and the installer commands; never a credential and never changes the binding omp-settings/route.ts GET/PUT native config.yml settings (allow-listed) web-settings/route.ts GET/PUT omp-web's own server settings (auto-resume, agent tools, agent env, browser transport; a transport change is pushed to every open browser) mcp/route.ts GET/POST/PUT/DELETE project MCP servers; `GET ?sessionId=&attach=1` reads a running session's live MCP status and never starts one (a cluster session on another member) @@ -237,6 +238,7 @@ lib/ session-match-listing.ts server: lists a session's search hits counted per rendered text node (remark parse) session-resume.ts running-session list for auto-resume after a restart web-auth.ts password-hash check + session cookie signing + mobile-access.ts Settings → Mobile app facts: bind classification, phone-reachable addresses (a specific bind keeps its kind — a CGNAT `100.64.0.0/10` or Tailscale IPv6 `fd7a:115c:a1e0::/48` address is `tailscale`; IPv6 is bracketed), MagicDNS only when the bind covers the tailnet, and the installer command sequences web-auth-secret.ts per-installation session-signing key (~/.omp/agent/omp-web/web-auth-secret.json) web-password-hash.ts typed view of bin/omp-web-password-hash.js (the scrypt hash format) web-settings.ts omp-web server settings (~/.omp/agent/omp-web-settings.json) diff --git a/CHANGELOG.md b/CHANGELOG.md index 548e9ad55..674667594 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 shows how to reach this server from a phone.** The new card reports the bind (loopback, network or unknown), the port, whether a password is configured, and the addresses to type into the app: the Tailscale address first for a phone that is away from home, then LAN. MagicDNS appears only when the bind actually covers the tailnet — a wildcard bind, or a specific bind on the Tailscale IP — because a socket bound to a LAN address does not listen on the Tailscale one. A specific bind keeps its address kind (a CGNAT `100.64.0.0/10` or Tailscale IPv6 `fd7a:115c:a1e0::/48` address is labelled Tailscale, not LAN), and IPv6 addresses are bracketed so the URL parses. Each installer's command sequence is shown as a hidden-input flow that keeps the password and its hash out of the shell history and `ps`. The card is backed by `GET /api/mobile-access`, which is read-only, rides the normal auth gate and returns only whether a password is configured — never the hash. + ## [v0.7.4] - 2026-11-20 ### Fixed diff --git a/app/api/mobile-access/route.ts b/app/api/mobile-access/route.ts new file mode 100644 index 000000000..36cf1109c --- /dev/null +++ b/app/api/mobile-access/route.ts @@ -0,0 +1,53 @@ +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"; + +/** + * 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 + * whether one is configured). + */ +export async function GET(req: Request) { + const hostname = detectBindHostname(); + 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(); + return Response.json({ + binding: { + hostname, + exposure: classifyExposure(hostname), + port, + }, + password: { + configured: isWebPasswordEnabled(), + problem: webPasswordConfigurationProblem() !== null, + }, + addresses: candidateAddresses({ hostname, port, magicDnsName, interfaces: networkInterfaces() }), + methods: mobileAccessMethods(), + }); +} diff --git a/bin/network-addresses.js b/bin/network-addresses.js index 62805f5e7..73ee2ff46 100644 --- a/bin/network-addresses.js +++ b/bin/network-addresses.js @@ -48,10 +48,26 @@ function isTailscaleAddress(ifaceName, address) { if (parts.length === 4 && parts[0] === 100 && parts[1] >= 64 && parts[1] <= 127) { return true; } + // Tailscale IPv6 uses the ULA range fd7a:115c:a1e0::/48. A bind on that + // address is the tailnet address just like a CGNAT IPv4 one; without this + // an IPv6 tailnet bind was reported as plain LAN. + if (isTailscaleIpv6(address)) return true; } return false; } +/** First 48 bits of `fd7a:115c:a1e0::/48`; brackets and a zone id are tolerated. */ +function isTailscaleIpv6(address) { + const bare = address.trim().replace(/^\[|\]$/g, "").split("%")[0].toLowerCase(); + if (!bare.includes(":")) return false; + // Only the leading groups matter for a /48. With `::` compression the groups + // after it are zeros, so a prefix that ends before the third group cannot be + // this range. + const groups = bare.split("::")[0].split(":"); + if (groups.length < 3) return false; + return parseInt(groups[0], 16) === 0xfd7a && parseInt(groups[1], 16) === 0x115c && parseInt(groups[2], 16) === 0xa1e0; +} + function isIgnoredAddress(ifaceName, address) { if (!address || typeof address !== "string") return true; // APIPA (Automatic Private IP Addressing: 169.254.0.0/16) @@ -106,8 +122,14 @@ function getAccessibleAddresses({ hostname, port, interfaces = os.networkInterfa } if (!isWildcardHost(hostname)) { + // A specific-IP bind listens on that address only, so it is one entry — but + // it is still the Tailscale address when the bind is on the tailnet, and a + // bare IPv6 host needs brackets in a URL (`getBrowserUrl` adds them). return { - entries: [{ label: "Network", url: `http://${hostname}:${port}` }], + entries: [{ + label: isTailscaleAddress(undefined, hostname.trim()) ? "Tailscale" : "Network", + url: getBrowserUrl(hostname.trim(), port), + }], }; } 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..6218f41c5 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 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 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": "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": "Paste the hash into a hidden prompt, then run the installer; it writes the unit. Without a password hash the service refuses to start on a network address, so the unit would restart-loop.", + "settingsConfig.mobileAppLaunchd": "launchd service", + "settingsConfig.mobileAppLaunchdHint": "Paste the hash into a hidden prompt, then run the installer; it writes the plist. Without a password hash the service refuses to start on a network address, so the job would restart-loop.", + "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..2574308de 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": "非表示のプロンプトでハッシュを生成し、2 つ目の非表示プロンプトに貼り付けてから、すべてのインターフェースで 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..eac4a9490 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。密码和哈希都不会回显,也不会留在 shell 历史中。", + "settingsConfig.mobileAppWindowsTray": "Windows 托盘应用", + "settingsConfig.mobileAppWindowsTrayHint": "生成哈希,将其粘贴到为用户保存的隐藏提示中,然后安装绑定所有接口的托盘应用。哈希绝不会出现在命令行上。", + "settingsConfig.mobileAppSystemd": "systemd 服务", + "settingsConfig.mobileAppSystemdHint": "将哈希粘贴到隐藏提示中,然后运行安装程序,它会写入 unit。没有密码哈希时,服务会拒绝在网络地址上启动,unit 会反复重启。", + "settingsConfig.mobileAppLaunchd": "launchd 服务", + "settingsConfig.mobileAppLaunchdHint": "将哈希粘贴到隐藏提示中,然后运行安装程序,它会写入 plist。没有密码哈希时,服务会拒绝在网络地址上启动,任务会反复重启。", + "settingsConfig.mobileAppLoadFailed": "无法加载移动访问详情。" } diff --git a/lib/i18n/locales/zh-TW.json b/lib/i18n/locales/zh-TW.json index 24d6ea266..ca752dfe0 100644 --- a/lib/i18n/locales/zh-TW.json +++ b/lib/i18n/locales/zh-TW.json @@ -2045,5 +2045,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。密碼與雜湊都不會回顯,也不會留在 shell 歷史紀錄中。", + "settingsConfig.mobileAppWindowsTray": "Windows 系統匣應用程式", + "settingsConfig.mobileAppWindowsTrayHint": "產生雜湊,貼到會為你的使用者儲存的隱藏提示中,然後安裝綁定所有網路介面的系統匣應用程式。雜湊永遠不會出現在指令列上。", + "settingsConfig.mobileAppSystemd": "systemd 服務", + "settingsConfig.mobileAppSystemdHint": "將雜湊貼到隱藏提示中,然後執行安裝程式;它會寫入 unit。沒有密碼雜湊時,服務會拒絕在網路位址上啟動,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..c12d72fd4 --- /dev/null +++ b/lib/mobile-access.test.mjs @@ -0,0 +1,369 @@ +import assert from "node:assert/strict"; +import { existsSync, 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, + 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 OMP_WEB_HOSTNAME, which every entry point writes", () => { + assert.equal(detectBindHostname({ OMP_WEB_HOSTNAME: "0.0.0.0" }), "0.0.0.0"); + assert.equal(detectBindHostname({ OMP_WEB_HOSTNAME: " 192.168.1.5 " }), "192.168.1.5"); + assert.equal(detectBindHostname({}), null); + assert.equal(detectBindHostname({ OMP_WEB_HOSTNAME: " " }), 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 })], + }; + // 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" }, + { url: "http://192.168.178.21:30177", label: "lan" }, + ]); +}); + +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({ 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({ hostname: "0.0.0.0", interfaces, port: 1 }).map((entry) => entry.url), + ["http://100.64.0.1:1"], + ); +}); + +test("MagicDNS is advertised only when the bind covers the Tailscale address", () => { + // RFC 5737 documentation addresses: a LAN-shaped bind without publishing a + // real network's numbering. + const interfaces = { + Ethernet: [iface("203.0.113.10")], + Tailscale: [iface("100.101.102.103")], + }; + // A socket bound to one LAN IP does not listen on the Tailscale IP, so the + // MagicDNS name would resolve to an address nothing is listening on. + assert.deepEqual( + candidateAddresses({ hostname: "203.0.113.10", port: 30177, magicDnsName: "node.example.ts.net", interfaces }), + [{ url: "http://203.0.113.10:30177", label: "lan" }], + ); + // A specific bind on a non-Tailscale address is the same case, with no + // interface map at all. + assert.deepEqual( + candidateAddresses({ hostname: "203.0.113.11", port: 30177, magicDnsName: "node.example.ts.net", interfaces: {} }), + [{ url: "http://203.0.113.11:30177", label: "lan" }], + ); + // A wildcard bind listens on every interface, so the name is reachable. + assert.deepEqual( + candidateAddresses({ hostname: "0.0.0.0", port: 30177, magicDnsName: "node.example.ts.net", interfaces: {} }), + [{ url: "http://node.example.ts.net:30177", label: "magicdns" }], + ); + // A bind on the Tailscale address itself covers it, and the bound address is + // the Tailscale one — both values sit in the helper's CGNAT range, so the + // entry is labelled `tailscale` rather than `lan`. + assert.deepEqual( + candidateAddresses({ hostname: "100.64.0.1", port: 30177, magicDnsName: "node.example.ts.net", interfaces }), + [ + { url: "http://node.example.ts.net:30177", label: "magicdns" }, + { url: "http://100.64.0.1:30177", label: "tailscale" }, + ], + ); + assert.deepEqual( + candidateAddresses({ hostname: "100.127.255.254", port: 30177, magicDnsName: "node.example.ts.net", interfaces: {} }), + [ + { url: "http://node.example.ts.net:30177", label: "magicdns" }, + { url: "http://100.127.255.254:30177", label: "tailscale" }, + ], + ); +}); + +test("a specific-IP bind keeps its address kind and brackets IPv6", () => { + // A bind on the tailnet IP is the Tailscale address, not a LAN one: the card + // labels it so the user knows which network it needs to be on. + assert.deepEqual( + candidateAddresses({ hostname: "100.90.1.2", port: 30177, interfaces: {} }), + [{ url: "http://100.90.1.2:30177", label: "tailscale" }], + ); + // The same for the IPv6 tailnet range (fd7a:115c:a1e0::/48): a bind there is + // the tailnet address, and its URL must be bracketed — a bare + // `http://fd7a:...:30177` reads as host `fd7a` and a nonsense port. + assert.deepEqual( + candidateAddresses({ hostname: "fd7a:115c:a1e0::1", port: 30177, interfaces: {} }), + [{ url: "http://[fd7a:115c:a1e0::1]:30177", label: "tailscale" }], + ); + assert.deepEqual( + candidateAddresses({ hostname: "fd7a:115c:a1e0::1", port: 30177, magicDnsName: "node.example.ts.net", interfaces: {} }), + [ + { url: "http://node.example.ts.net:30177", label: "magicdns" }, + { url: "http://[fd7a:115c:a1e0::1]:30177", label: "tailscale" }, + ], + "an IPv6 bind on the tailnet covers it, so MagicDNS is advertised", + ); + // A non-tailnet IPv6 bind is still LAN, and still bracketed. + assert.deepEqual( + candidateAddresses({ hostname: "2001:db8::5", port: 30177, magicDnsName: "node.example.ts.net", interfaces: {} }), + [{ url: "http://[2001:db8::5]:30177", label: "lan" }], + "an IPv6 bind that is not the Tailscale address does not advertise MagicDNS", + ); +}); + +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\$/); + // 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 -rs OMP_WEB_PASSWORD_HASH/); + assert.match(joined, /Read-Host -AsSecureString/); + // `read -p` is a zsh coprocess read, not a prompt: macOS's default shell + // would fail with `read: -p: no coprocess` and never read the hash. + assert.doesNotMatch(joined, /read -[a-z]*p/, "no POSIX-shell read may use -p: zsh reads a coprocess instead"); +}); + +/** Locate a POSIX shell that can run the generated sequences. */ +function shellForFlow() { + if (process.platform === "win32") { + const gitBash = "C:\\Program Files\\Git\\bin\\bash.exe"; + return existsSync(gitBash) ? { binary: gitBash, args: [] } : null; + } + return existsSync("/bin/bash") ? { binary: "/bin/bash", args: [] } : null; +} + +test("the launchd setup reads, exports and hands the hash to the installer in a real shell", async (t) => { + const shell = shellForFlow(); + if (!shell) { + t.skip("no POSIX shell available to execute the generated commands"); + return; + } + const dir = mkdtempSync(join(tmpdir(), "omp-web-launchd-flow-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + + // Stub `ompweb` and `ompweb-launchd` on PATH, so the exact generated strings + // run unmodified and the installer reports what it actually received. + const stub = (name, body) => { + const file = join(dir, name); + writeFileSync(file, `#!/bin/sh\n${body}\n`, { mode: 0o755 }); + return file; + }; + stub("ompweb", 'echo "STUB_HASH_PASSWORD"'); + stub( + "ompweb-launchd", + 'echo "LAUNCHD hostname=$OMP_WEB_HOSTNAME hash=${OMP_WEB_PASSWORD_HASH}"', + ); + + const launchd = mobileAccessMethods().find((method) => method.id === "launchd"); + assert.ok(launchd); + const script = [ + "set -u", + ...launchd.commands, + ].join("\n"); + + const { spawnSync } = await import("node:child_process"); + const result = spawnSync(shell.binary, [...shell.args, "-c", script], { + input: `${KNOWN_HASH}\n`, + encoding: "utf8", + env: { + ...process.env, + PATH: `${dir}${delimiter}${process.env.PATH ?? ""}`, + // A stale value must be replaced by the hidden read, not inherited. + OMP_WEB_PASSWORD_HASH: "stale-value-from-the-parent-shell", + }, + }); + + assert.equal(result.status, 0, `the generated flow must succeed; stderr: ${result.stderr}`); + assert.match(result.stdout, /STUB_HASH_PASSWORD/, "the hash-password step runs first"); + // The prompt is printed by printf, so it appears even though the read is hidden. + assert.match(result.stdout, /OMP_WEB_PASSWORD_HASH: /, "the hidden read prints its prompt"); + // The value reached the installer through the environment, not argv. + assert.match(result.stdout, new RegExp(`LAUNCHD hostname=0\\.0\\.0\\.0 hash=${KNOWN_HASH.replace(/\$/g, "\\$")}`)); + assert.doesNotMatch(result.stdout, /stale-value-from-the-parent-shell/); +}); + +test("the exported hash survives into the installer's environment, not its command line", async (t) => { + const shell = shellForFlow(); + if (!shell) { + t.skip("no POSIX shell available to execute the generated commands"); + return; + } + const dir = mkdtempSync(join(tmpdir(), "omp-web-launchd-argv-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + // The installer records its own argv; the hash must not be in it. + const file = join(dir, "ompweb-launchd"); + writeFileSync(file, '#!/bin/sh\nfor arg in "$@"; do echo "ARG:$arg"; done\n', { mode: 0o755 }); + const readHash = mobileAccessMethods() + .find((method) => method.id === "launchd") + .commands + .find((command) => command.includes("read -rs")); + assert.ok(readHash); + + const { spawnSync } = await import("node:child_process"); + const result = spawnSync(shell.binary, [...shell.args, "-c", `${readHash}\nOMP_WEB_HOSTNAME=0.0.0.0 ompweb-launchd install`], { + input: `${KNOWN_HASH}\n`, + encoding: "utf8", + env: { ...process.env, PATH: `${dir}${delimiter}${process.env.PATH ?? ""}` }, + }); + assert.equal(result.status, 0, `stderr: ${result.stderr}`); + assert.match(result.stdout, /ARG:install/); + assert.doesNotMatch(result.stdout, /scrypt\$/, "the hash must never appear in argv"); +}); + +/** 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"); + 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 new file mode 100644 index 000000000..e4df927e7 --- /dev/null +++ b/lib/mobile-access.ts @@ -0,0 +1,253 @@ +import { execFile } from "node:child_process"; +import { networkInterfaces, type NetworkInterfaceInfo } from "node:os"; +import { join } from "node:path"; +import { existsSync } from "node:fs"; +import { getAccessibleAddresses, isTailscaleAddress, isWildcardHost } from "../bin/network-addresses"; +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; +} + +/** + * The bind this server was launched with. `startProduction` (server/app.ts) + * writes `OMP_WEB_HOSTNAME` from the bound listener before serving, and the dev + * entry point (server/dev.ts) writes it the same way after its own bind, so the + * environment is the authoritative source for every entry point — there is no + * argv to fall back to. + */ +export function detectBindHostname(env: NodeJS.ProcessEnv = process.env): string | null { + return env.OMP_WEB_HOSTNAME?.trim() || 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"; +} + +/** + * 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, 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 advertised only when the bind actually covers the Tailscale + * address: a wildcard bind listens on every interface, and a specific-IP bind + * does so only when that IP is itself the Tailscale address. A socket bound to + * a LAN IP does not listen on the Tailscale IP, so the MagicDNS name would + * resolve to an address nothing is listening on. + */ +export function candidateAddresses({ + hostname, + port, + magicDnsName, + interfaces = networkInterfaces(), +}: { + hostname: string | null; + port: number; + magicDnsName?: string | null; + interfaces?: NetworkInterfaceMap; +}): MobileAddress[] { + // `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 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" }); + } + // The bind covers the Tailscale address when it listens on every interface, + // or when the specific IP it is bound to is the Tailscale address itself. + const coversTailscale = isWildcardHost(hostname) + || (typeof hostname === "string" && isTailscaleAddress(undefined, hostname.trim())); + const magic = coversTailscale ? magicDnsName?.trim().replace(/\.$/, "") : undefined; + const magicdn: MobileAddress[] = magic ? [{ url: `http://${magic}:${port}`, label: "magicdns" }] : []; + 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. + * + * No command line carries a secret, and no secret is echoed. `ompweb + * hash-password` reads the password at a hidden prompt and prints the hash; + * every flow pastes that hash into a *hidden* prompt (`read -rs`, `Read-Host + * -AsSecureString`) and hands it to the next command through the environment, + * so neither the password nor the hash lands in the shell history or in `ps`. + * All four installers accept `OMP_WEB_PASSWORD_HASH` directly, so the + * plaintext never has to be exported at all. + */ +export function mobileAccessMethods(): MobileAccessMethod[] { + // The prompt is printed by `printf`, not by `read -p`: on macOS the default + // shell is zsh, where `read -p` reads from a coprocess instead of printing a + // prompt and the whole sequence fails with `read: -p: no coprocess`. `-r` + // and `-s` mean the same in bash and zsh, so this sequence works in either. + // `-s` keeps the input off the terminal; `echo` ends the line the hidden + // prompt left open. The value goes into the environment, never into argv. + const readHash = "printf 'OMP_WEB_PASSWORD_HASH: ' && read -rs OMP_WEB_PASSWORD_HASH && export OMP_WEB_PASSWORD_HASH && echo"; + return [ + { + id: "cli", + commands: [ + "ompweb hash-password", + readHash, + "ompweb -H 0.0.0.0", + ], + }, + { + id: "windowsTray", + commands: [ + "ompweb hash-password", + // User scope is what the service script reads at logon; the session + // variable makes the same value visible to the command below. + "$s = Read-Host -AsSecureString 'OMP_WEB_PASSWORD_HASH'; $h = [Net.NetworkCredential]::new('', $s).Password; [Environment]::SetEnvironmentVariable('OMP_WEB_PASSWORD_HASH', $h, 'User'); $env:OMP_WEB_PASSWORD_HASH = $h", + "ompweb --install-tray -H 0.0.0.0", + ], + }, + { + id: "systemd", + commands: [ + "ompweb hash-password", + readHash, + "OMP_WEB_HOSTNAME=0.0.0.0 ompweb-systemd install", + ], + }, + { + id: "launchd", + commands: [ + "ompweb hash-password", + readHash, + "OMP_WEB_HOSTNAME=0.0.0.0 ompweb-launchd install", + ], + }, + ]; +} diff --git a/lib/network-addresses.test.mjs b/lib/network-addresses.test.mjs index f7eb005f5..4a032ba81 100644 --- a/lib/network-addresses.test.mjs +++ b/lib/network-addresses.test.mjs @@ -60,6 +60,27 @@ test("identifies Tailscale interface or CGNAT IP range", () => { assert.equal(isTailscaleAddress("Ethernet", "192.168.1.1"), false); }); +// Tailscale hands every node an address from fd7a:115c:a1e0::/48; a bind on it +// is the tailnet address, exactly like a CGNAT IPv4 one. The counterexamples +// matter as much: a neighbouring ULA prefix or a global unicast address must +// stay LAN, or a phone is told to join a tailnet it is not on. +test("identifies the Tailscale IPv6 ULA range", () => { + assert.equal(isTailscaleAddress(undefined, "fd7a:115c:a1e0::1"), true); + assert.equal(isTailscaleAddress(undefined, "fd7a:115c:a1e0:ab12::99"), true); + assert.equal(isTailscaleAddress(undefined, "FD7A:115C:A1E0::1"), true); + assert.equal(isTailscaleAddress(undefined, "[fd7a:115c:a1e0::1]"), true); + assert.equal(isTailscaleAddress(undefined, "fd7a:115c:a1e0::1%eth0"), true); + assert.equal(isTailscaleAddress(undefined, "fd7a:115c:a1e0:0:0:0:0:1"), true); + + assert.equal(isTailscaleAddress(undefined, "fd7a:115c:a1e1::1"), false); + assert.equal(isTailscaleAddress(undefined, "fd7a:115c::1"), false); + assert.equal(isTailscaleAddress(undefined, "fd7b:115c:a1e0::1"), false); + assert.equal(isTailscaleAddress(undefined, "2001:db8::5"), false); + assert.equal(isTailscaleAddress(undefined, "fe80::1"), false); + assert.equal(isTailscaleAddress(undefined, "::1"), false); + assert.equal(isTailscaleAddress(undefined, "100.64.0.1"), true); +}); + test("filters out ignored addresses like APIPA and TUN fake-ip", () => { assert.equal(isIgnoredAddress("Tailscale", "169.254.83.107"), true); assert.equal(isIgnoredAddress("Meta", "198.18.0.1"), true); diff --git a/server/dev.test.ts b/server/dev.test.ts index 55081317c..f98cc09c3 100644 --- a/server/dev.test.ts +++ b/server/dev.test.ts @@ -105,3 +105,63 @@ test("hot reload of a shared worker dependency keeps the dev server listening", assert.match(await (await fetch(`${origin}/event-stream-worker.js`)).text(), /hot-reload-worker-probe/); assert.equal(parent.exitCode, null); }); + +// `npm run dev:lan` starts server/dev.ts with `-H 0.0.0.0`. Settings → Mobile +// app reads the bind from OMP_WEB_HOSTNAME, which startProduction writes for +// every production entry point; the dev entry point must write it too, or the +// card reports an unknown bind and offers no address at all. The assertion goes +// through the real HTTP route, so it fails if either the env write or the +// route's read regresses. +test("dev.ts publishes its bind so the Mobile app card can list addresses", { timeout: 60_000 }, async (t) => { + const home = mkdtempSync(path.join(os.tmpdir(), "omp-web-dev-bind-")); + // The OMP_WEB_PUBLIC_* values are set here so dev.ts does not re-run itself + // with them (`bunfig.toml` inlines them at startup): the test then owns the + // one process it started and can stop it. + const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("OMP_WEB_"))); + const parent = Bun.spawn([process.execPath, "server/dev.ts", "-H", "0.0.0.0", "-p", "0"], { + cwd: repo, + env: { + ...env, + HOME: home, + PI_CODING_AGENT_DIR: path.join(home, ".omp", "agent"), + OMP_WEB_OMP_BIN: "/nonexistent/omp", + OMP_WEB_DISABLE_AUTOUPDATE: "1", + OMP_WEB_PUBLIC_APP_VERSION: "0.0.0-test", + OMP_WEB_PUBLIC_COMMIT_HASH: "", + OMP_WEB_PUBLIC_COMMIT_DATE: "", + OMP_WEB_PUBLIC_EVENT_STREAM_WORKER_VERSION: "test", + }, + stdout: "pipe", + stderr: "ignore", + }); + t.after(async () => { + parent.kill("SIGKILL"); + await parent.exited; + rmSync(home, { recursive: true, force: true }); + }); + + // Read without cancelling: a closed pipe could kill the server on its next log line and fake a pass. + const reader = parent.stdout.getReader(); + const decoder = new TextDecoder(); + let output = ""; + while (!/\[omp-web\] Ready on (http:\/\/[^\s]+)/.test(output)) { + const { done, value } = await reader.read(); + assert.equal(done, false, output); + output += decoder.decode(value); + } + // The Ready line names the bound origin; a wildcard bind is reached over loopback. + const ready = /\[omp-web\] Ready on (\S+)/.exec(output); + assert.ok(ready, output); + const port = Number(new URL(ready[1]).port); + assert.ok(port > 0, output); + + // No password is configured in this temp home, so the gate lets the request through. + const response = await fetch(`http://127.0.0.1:${port}/api/mobile-access`); + assert.equal(response.status, 200); + const body = await response.json(); + assert.equal(body.binding.hostname, "0.0.0.0", "dev.ts must publish the bind it was started with"); + assert.equal(body.binding.exposure, "network"); + assert.equal(body.binding.port, port, "the bound port, not the request URL's"); + // The point of the card: a phone needs an address, and a wildcard bind has them. + assert.ok(body.addresses.length > 0, `a network bind must offer an address: ${JSON.stringify(body.addresses)}`); +}); diff --git a/server/dev.ts b/server/dev.ts index c144b106b..70ce2a6c4 100644 --- a/server/dev.ts +++ b/server/dev.ts @@ -25,7 +25,13 @@ if (Object.keys(env).some((name) => process.env[name] === undefined)) { Object.assign(process.env, { NODE_ENV: "development" }); const { parseListenArgs, startServer } = await import("./app"); -const server = startServer({ ...parseListenArgs(Bun.argv.slice(2), 30178), dev: true, root, html, worker }); +const listen = parseListenArgs(Bun.argv.slice(2), 30178); +const server = startServer({ ...listen, dev: true, root, html, worker }); +// The local daemon link and the update worker dial this address, and Settings → +// Mobile app reads the bind from here (lib/mobile-access.ts). startProduction +// writes both after its bind; the dev entry point must do the same or +// `npm run dev:lan` reports an unknown bind and offers no address. +Object.assign(process.env, { OMP_WEB_PORT: String(server.port), OMP_WEB_HOSTNAME: listen.hostname }); // `bun --hot` re-evaluates this file on every edit; register() must run once per process. globalThis.__ompWebRegistered ??= import("../instrumentation.node").then(({ register }) => register()); await globalThis.__ompWebRegistered; 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,