From a5a14ef420932a967342a6817f5686367d45f6ba Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 9 Oct 2026 22:53:26 +0000 Subject: [PATCH 1/3] feat(auth): skip the password for requests a trusted proxy vouches for OMP_WEB_TRUSTED_HEADER_SHA256 holds the SHA-256 digest of a secret a reverse proxy sends in X-Omp-Web-Auth for trusted client ranges; a matching request counts as signed in. omp-web never holds the secret, and the digest is stripped from child processes like the other omp-web secrets. Service installers and the Windows launchers pass it on. The Windows tray (native and PowerShell) and background service now read OMP_WEB_PASSWORD_HASH, the legacy OMP_WEB_PASSWORD and the digest fresh from the user, then system, environment on every server start, so rotating or removing them with setx takes effect at the next restart. bin/omp-web-tray.exe is rebuilt from native/tray. README documents the nginx setup (realip for Cloudflare, Cloudflare Tunnel and other proxies, DNS-rebinding guard) and generating the secret without it reaching shell history. --- CHANGELOG.md | 2 + DESIGN.md | 8 +- README.ja.md | 1 + README.md | 122 ++++++++++++++++++++++++++++ README.zh-CN.md | 1 + bin/omp-web-launchd.js | 2 + bin/omp-web-systemd.js | 1 + bin/omp-web-systemd.test.mjs | 2 + bin/omp-web-tray.exe | Bin 174690 -> 175678 bytes lib/project-command-env.test.mjs | 2 +- lib/project-command-env.ts | 2 +- lib/web-auth.test.mjs | 39 +++++++++ lib/web-auth.ts | 14 +++- native/tray/Program.cs | 22 +++++ proxy.ts | 5 +- scripts/windows/omp-web-service.ps1 | 28 ++++--- scripts/windows/omp-web-tray.ps1 | 29 ++++--- 17 files changed, 253 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 281295861..b10bfd61b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f - **Expand thinking blocks by default**, an off-by-default switch next to **Keep tool calls collapsed** in Settings → Interface & Behavior. Turn it on to read the model's reasoning without expanding every block; each block still collapses and expands by hand, and the choice applies to a block that is still streaming as well. Tool-call collapsing is unchanged. - List every account omp stores for a subscription provider in Settings → API Keys & Providers and disconnect a single account with its **Disconnect** button; the other accounts stay connected and omp keeps choosing and rotating between them. The sign-in button of a connected provider now reads **Add account**: signing in with another account adds it, and signing in with a connected account refreshes it. Requires omp 18.7.0 or later ([can1357/oh-my-pi#14588](https://github.com/can1357/oh-my-pi/pull/14588)); older omp keeps the read-only account list from `omp usage` and explains how to disconnect from a terminal. - Add **Settings → Notifications**: desktop and mobile notifications for a finished task (after the prompt and any background work it started are done; subagents never notify), a question or approval waiting for you, a run that failed after retries and fallbacks, and a model switch omp made on its own (for example Fable falling back to Opus after a refusal, or a usage-limit fallback). Each browser chooses its own events and whether to show an in-app toast or a system notification while you use omp-web in another tab. Nothing is shown for the session you are viewing, and clicking a notification opens its session; an in-app toast opens it from a click or tap anywhere on it, or Enter when it has keyboard focus. Over HTTPS (or on `localhost`) notifications arrive through Web Push even with no omp-web tab open, including the iPhone/iPad app added to the Home Screen; the push keys and device list live in `~/.omp/agent/omp-web/notifications.json`. Notifications are off until you turn them on. This replaces the previous completion notification for the open session, and the agent's `notify` tool now also works on Android. +- Skip the web password for clients your reverse proxy trusts: the proxy sends a secret in `X-Omp-Web-Auth` only for trusted address ranges, and omp-web holds only the secret's SHA-256 digest in `OMP_WEB_TRUSTED_HEADER_SHA256`. Other clients still sign in with the password. The README shows how to generate the secret without it reaching shell history, and an nginx setup, including how to trust the real client address behind Cloudflare, Cloudflare Tunnel or another proxy, and how to guard against DNS rebinding. The service installers preserve the setting, and the digest never reaches child processes. - Choose **Classifier** or **Vendor default** in Settings → AI Model Defaults → **Auto Thinking Source** when Reasoning is `auto`. The choice is saved in omp's native config for newly started or restarted agents. Vendor mode prefers the publisher's effort, then omp's per-model default, then normal Auto fallback. Requires an omp release containing [can1357/oh-my-pi#14114](https://github.com/can1357/oh-my-pi/pull/14114). - Show conflicting skill names and deduplicated installations when an OMP session starts, with resolution details, a **×** button that dismisses the notice for the session until the diagnostic report changes, and a persisted **Turn off** action that disables startup notices. Inspect a running session manually in **Settings → Extensions & Tools → Skills**, even when notices are off; inspection never resumes a stopped session. Requires an OMP runtime with the skill-diagnostics RPC commands; older runtimes report live diagnostics as unavailable. - Ask a side question with `/btw `: omp answers from the current conversation in a panel above the composer, even while the agent is working, and the question never enters the chat. Cancel a running answer, copy it, or ask follow-ups in the same topic. `/btw` on its own lists the session's past side questions, including ones asked in the terminal, each expandable to all its turns with **Copy** and **Follow up**. Side questions are text-only: with an attachment in the composer, `/btw` is refused and the draft is kept. An answer that omp lost (for example after its process restarted) shows as **Interrupted** instead of spinning. Requires an omp with the `btw` RPC commands; older omp shows "/btw requires a newer omp" instead of sending the text to the model. @@ -49,6 +50,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f - Submitting a message while the agent is working now queues it by default instead of steering, in Settings → Interface & Behavior → **Message during active run**: steering a long tool or shell command could abort the turn mid-task and left the new message undelivered. A previously saved choice is kept; only an empty setting changes meaning. Sending during omp-web's own `!!` shell command no longer fails with "Cannot send a prompt while a shell command is running": the message is handed to omp's queue instead of aborting anything, the optimistic bubble is withdrawn, and a notice says it was queued behind the running command. - Keep omp-web's own secrets out of every child process it starts, not only the `omp` session processes: plugin install and upgrade, skill install/update/search, update checks and the self-update worker, agent unpack, and the Git commands the file panel runs. A session environment no longer contains the web password hash, so `env` inside an agent no longer prints anything that grants access to this server. `OMP_WEB_*` values that are configuration rather than secrets (the `omp` binary path, port, package dir) keep reaching the processes that need them. - Sign web sessions with a per-installation random key (created on first start at `~/.omp/agent/omp-web/web-auth-secret.json`, mode `0600`) mixed with the password hash, instead of the hash itself. Anyone who reads the hash out of a service environment file can no longer forge a session cookie, and changing the password still signs every browser out. +- On Windows, changing or removing the web password hash with `setx` now takes effect at the next server restart. The tray (native and PowerShell) and the background service read `OMP_WEB_PASSWORD_HASH` from the user, then system, environment each time they start the server, instead of preferring the copy they captured at logon, so an old password no longer keeps working after you rotate it. The native tray previously did not pass the hash on at all. - Word-completion ghost text in a scrolled composer now appears right after the caret. When the draft had text after the caret, it used to be drawn lines further down. - Show a single plus sign on the **Add provider** buttons in Models settings, and none in the Add provider dialog title. The translated label no longer repeats the button's **+** icon. - Links in a Markdown file preview no longer navigate omp-web away. A relative link the file panel cannot open, such as one in a Markdown file outside the workspace, shows as plain text with its target on hover; web links open in a new tab. An image the panel cannot load shows its alt text instead of a broken image. diff --git a/DESIGN.md b/DESIGN.md index 9db2e4b5a..8857ab2db 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -179,9 +179,13 @@ Deploy the frontend and API support together; no native OMP upgrade is required. the signing key is a per-installation random value mixed with the hash, so a copied password hash cannot forge a session and changing the password still invalidates existing sessions. Exposed deployments require HTTPS through a - trusted reverse proxy or VPN. + trusted reverse proxy or VPN. With `OMP_WEB_TRUSTED_HEADER_SHA256` set, a + request whose `X-Omp-Web-Auth` header hashes to that digest counts as signed + in; omp-web never holds the secret itself. Deciding which clients get the + header is the reverse proxy's job, because omp-web has no client address it + can trust. - omp-web's own secrets (`OMP_WEB_PASSWORD`, `OMP_WEB_PASSWORD_HASH`, - `OMP_WEB_TRUSTED_HEADER_SECRET`) are stripped from every child process + `OMP_WEB_TRUSTED_HEADER_SHA256`) are stripped from every child process environment through `createChildProcessEnvironment` (`lib/project-command-env.ts`). `OMP_WEB_*` values that are configuration rather than secrets (`OMP_WEB_PACKAGE_DIR`, `OMP_WEB_OMP_BIN`, ...) are kept. diff --git a/README.ja.md b/README.ja.md index 47fa7a209..749f94d93 100644 --- a/README.ja.md +++ b/README.ja.md @@ -115,6 +115,7 @@ Linux トレイ、Windows サービス)はインストール時に `OMP_WEB_PA | `PORT` | サーバーポート | `30177` | | `OMP_WEB_HOSTNAME` | バインドホスト | `127.0.0.1` | | `OMP_WEB_PASSWORD_HASH` | Web ログイン用パスワードの scrypt ハッシュ(`ompweb hash-password` で生成)。非ループバックバインドには必須 | _なし(認証無効)_ | +| `OMP_WEB_TRUSTED_HEADER_SHA256` | 信頼できるリバースプロキシが `X-Omp-Web-Auth` ヘッダーで送るシークレットの SHA-256 ダイジェスト(16 進)。ヘッダーのハッシュが一致したリクエストはパスワードなしで通ります。omp-web はシークレット自体を保持しません。生成方法と nginx の設定例は英語版 README の「Skipping the password on trusted networks」を参照してください | _なし(無効)_ | | `OMP_WEB_NO_OPEN` | `1` でブラウザ自動起動を無効化 | `0` | | `OMP_WEB_DISABLE_AUTOUPDATE` | `1` で更新チェックとアプリ内更新を無効化(変更後は再起動) | `0` | | `OMP_WEB_NAME` | ブラウザのタブとインストールしたアプリに表示する名前。`url`・`host`・`domain`(大文字小文字を区別しない)を指定すると、ブラウザが接続したホスト名(ポートなし)を使用します(localhost と IP アドレスは `omp web` のまま)。それ以外の値はそのまま使用します(変更後は再起動) | `omp web` | diff --git a/README.md b/README.md index ee6254182..0bea4784c 100644 --- a/README.md +++ b/README.md @@ -159,6 +159,12 @@ Linux tray, and the Windows service) still accept `OMP_WEB_PASSWORD` at install time and hash it before writing it to their configuration. Only the hash is stored. +On Windows, the tray and background service read `OMP_WEB_PASSWORD_HASH` from +your user or system environment (for example `setx OMP_WEB_PASSWORD_HASH +"scrypt$…"`) each time they start the server, not from the environment they were +started with. Changing or removing the hash takes effect at the next server +restart, without signing out of Windows. + ### Run as a Windows Service (System Tray) Install ompweb as a Windows background service with a system tray icon and autostart at login: @@ -318,6 +324,7 @@ host (KDE Plasma, and most Wayland/X11 desktops). | `PORT` | Server port | `30177` | | `OMP_WEB_HOSTNAME` | Server bind host | `127.0.0.1` | | `OMP_WEB_PASSWORD_HASH` | Optional scrypt hash of the web login password, from `ompweb hash-password`. Required for a non-loopback bind | _None (auth disabled)_ | +| `OMP_WEB_TRUSTED_HEADER_SHA256` | SHA-256 hex digest of the secret a trusted reverse proxy sends in `X-Omp-Web-Auth` to skip the password for that request; see [Skipping the password on trusted networks](#skipping-the-password-on-trusted-networks) | _None (disabled)_ | | `OMP_WEB_NO_OPEN` | Set to `1` to prevent auto-opening browser | `0` | | `OMP_WEB_DISABLE_AUTOUPDATE` | Set to `1` to disable update checks and in-app updates; restart after changing | `0` | | `OMP_WEB_NAME` | Name shown in browser tabs and installed-app names. `url`, `host` or `domain` (any case) uses the hostname the browser connected to, without port; localhost and IP addresses keep `omp web`. Any other value is used as-is. Restart after changing | `omp web` | @@ -330,6 +337,121 @@ host (KDE Plasma, and most Wayland/X11 desktops). **`OMP_WEB_NAME` and installed apps.** An installed app (PWA) is usually named after the page it was installed from. If you later change `OMP_WEB_NAME`, or reach omp-web through a different address while `OMP_WEB_NAME` is `url`, `host` or `domain`, your operating system may rename the installed app as well. Leave `OMP_WEB_NAME` empty, or set a name that identifies this omp-web server whatever domain name or address is used to reach it. +## Skipping the password on trusted networks + +omp-web cannot see the client's address itself, so it leaves the decision to +your reverse proxy. The proxy sends a secret in the `X-Omp-Web-Auth` header, +and omp-web holds only that secret's SHA-256 digest in +`OMP_WEB_TRUSTED_HEADER_SHA256`. A request whose header hashes to that digest +is treated as signed in. Everyone else still signs in with the password whose +hash is in `OMP_WEB_PASSWORD_HASH`; without a password there is nothing to +skip, and the header is ignored. Keep omp-web bound to `127.0.0.1` so only the +proxy reaches it. + +Generate the secret and its digest without typing the secret on a command line, +so it never lands in your shell history. This writes a random secret straight +into an nginx include file readable only by root and nginx, and prints only the +digest: + +```bash +secret=$(openssl rand -hex 32) +if [[ $secret =~ ^[A-Za-z0-9._~-]+$ ]]; then + printf 'map $ompweb_trusted $ompweb_auth {\n 1 "%s";\n default "";\n}\n' "$secret" \ + | sudo install -m 0640 -o root -g www-data /dev/stdin /etc/nginx/ompweb-auth.conf + printf %s "$secret" | sha256sum | cut -d' ' -f1 +else + echo "unsupported characters: use only letters, digits, . _ ~ and -" >&2 +fi +unset secret +``` + +Use your nginx group in place of `www-data` (`nginx` on some distributions). +Set the printed digest as `OMP_WEB_TRUSTED_HEADER_SHA256`. The command history +holds only the commands, never the secret. On Windows, the tray and background +service read it from your user or system environment, like +`OMP_WEB_PASSWORD_HASH`. + +To use a secret you already have, replace the first line with `read -rs secret` +to enter it at a hidden prompt. It must contain only letters, digits, `.`, `_`, +`~` and `-`, because nginx would expand or reject other characters inside the +quoted `map` value while the digest is computed from the original. The check +above refuses any other secret before writing anything; generate a new one +instead. + +With nginx, send the secret only to the address ranges you trust: + +```nginx +# http {} context +geo $ompweb_trusted { + default 0; + 10.0.0.0/16 1; +} +include /etc/nginx/ompweb-auth.conf; # the map written above + +# the location that proxies to omp-web +proxy_set_header X-Omp-Web-Auth $ompweb_auth; +``` + +Always set the header, as above: the empty value for other clients replaces any +`X-Omp-Web-Auth` a client sends itself. nginx only inherits `proxy_set_header` +from outer blocks when a block sets none of its own, so put this line next to +the location's other `proxy_set_header` lines. + +Serve omp-web only for its own hostname: give its `server` block an explicit +`server_name`, and add a `default_server` block that answers every other +hostname with `return 444;`. Otherwise a web page that a trusted browser visits +can point its own domain name at your nginx (DNS rebinding) and have nginx add +the secret to its requests. + +`geo` checks `$remote_addr`, the address that connected to nginx. When clients +reach nginx through another proxy, use the +[`realip` module](https://nginx.org/en/docs/http/ngx_http_realip_module.html) to +replace it with the real client address. It does so only for connections from +addresses you list in `set_real_ip_from`: + +- **Cloudflare (proxied DNS):** trust `CF-Connecting-IP`, and only from + Cloudflare. List every range from and + , and keep them up to date. Use this only + when Cloudflare is really in front. + + ```nginx + set_real_ip_from 173.245.48.0/20; # ...one line per Cloudflare range + real_ip_header CF-Connecting-IP; + ``` + + Also refuse connections that come neither from Cloudflare nor from your + trusted ranges. `$realip_remote_addr` is the address that actually + connected, before `realip` replaced it: + + ```nginx + geo $realip_remote_addr $ompweb_peer_allowed { + default 0; + 173.245.48.0/20 1; # ...every Cloudflare range + 10.0.0.0/16 1; + } + # in the server block + if ($ompweb_peer_allowed = 0) { return 403; } + ``` + +- **Cloudflare Tunnel (`cloudflared`):** the tunnel connects to nginx from + `cloudflared`'s address (`127.0.0.1` when it runs on the same machine), so + trust `CF-Connecting-IP` from there: `set_real_ip_from 127.0.0.1;` and + `real_ip_header CF-Connecting-IP;`. Any local process can then send its own + `CF-Connecting-IP` to nginx and claim a trusted address, and a local + connection without that header keeps `127.0.0.1`, so listing `127.0.0.1` in + `$ompweb_trusted` trusts every local process that connects to nginx. +- **Any other proxy or load balancer:** + + ```nginx + set_real_ip_from ; + real_ip_header X-Forwarded-For; + real_ip_recursive on; + ``` + + `real_ip_recursive on` reads `X-Forwarded-For` from the right and skips the + hops listed in `set_real_ip_from`. Addresses a client adds itself are + ignored. + ## Development ```bash diff --git a/README.zh-CN.md b/README.zh-CN.md index 7ad58f5a6..abc198d60 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -109,6 +109,7 @@ Windows 服务)仍在安装时接受 `OMP_WEB_PASSWORD`,但在写入配置 | `PORT` | 服务端口 | `30177` | | `OMP_WEB_HOSTNAME` | 绑定主机名 | `127.0.0.1` | | `OMP_WEB_PASSWORD_HASH` | Web 登录密码的 scrypt 哈希(由 `ompweb hash-password` 生成)。绑定非回环地址时必须设置 | _无(未启用验证)_ | +| `OMP_WEB_TRUSTED_HEADER_SHA256` | 受信任的反向代理在 `X-Omp-Web-Auth` 请求头中发送的密钥的 SHA-256 摘要(十六进制);请求头哈希匹配的请求无需密码。omp-web 不保存密钥本身。生成方法和 nginx 配置示例见英文 README 的 “Skipping the password on trusted networks” 一节 | _无(未启用)_ | | `OMP_WEB_NO_OPEN` | 设为 `1` 时禁止自动打开浏览器 | `0` | | `OMP_WEB_DISABLE_AUTOUPDATE` | 设为 `1` 时禁用更新检查和应用内更新;修改后需重启 | `0` | | `OMP_WEB_NAME` | 浏览器标签页和已安装应用中显示的名称。设为 `url`、`host` 或 `domain`(不区分大小写)时使用浏览器所连接的主机名(不含端口),localhost 和 IP 地址仍显示 `omp web`;其他值按原样使用。修改后需重启 | `omp web` | diff --git a/bin/omp-web-launchd.js b/bin/omp-web-launchd.js index dd7f2f0ee..f29ad4c30 100644 --- a/bin/omp-web-launchd.js +++ b/bin/omp-web-launchd.js @@ -88,6 +88,7 @@ function install(pkgArg) { } catch (error) { fail(error instanceof Error ? error.message : String(error)); } + const trustedHeaderDigest = process.env.OMP_WEB_TRUSTED_HEADER_SHA256; const agentDir = process.env.PI_CODING_AGENT_DIR?.replace(/^~(?=\/|$)/, HOME); const asdfBin = which("asdf"); @@ -110,6 +111,7 @@ function install(pkgArg) { ...(disableAutoUpdate ? { OMP_WEB_DISABLE_AUTOUPDATE: disableAutoUpdate } : {}), ...(installName ? { OMP_WEB_NAME: installName } : {}), ...(passwordHash ? { OMP_WEB_PASSWORD_HASH: passwordHash } : {}), + ...(trustedHeaderDigest ? { OMP_WEB_TRUSTED_HEADER_SHA256: trustedHeaderDigest } : {}), ...(ompBin ? { OMP_WEB_OMP_BIN: ompBin } : {}), ...(agentDir ? { PI_CODING_AGENT_DIR: agentDir } : {}), }; diff --git a/bin/omp-web-systemd.js b/bin/omp-web-systemd.js index 46ecb0215..2e6716962 100644 --- a/bin/omp-web-systemd.js +++ b/bin/omp-web-systemd.js @@ -329,6 +329,7 @@ function install(options = {}) { ...(process.env.OMP_WEB_DISABLE_AUTOUPDATE ? { OMP_WEB_DISABLE_AUTOUPDATE: process.env.OMP_WEB_DISABLE_AUTOUPDATE } : {}), ...(process.env.OMP_WEB_NAME ? { OMP_WEB_NAME: process.env.OMP_WEB_NAME } : {}), ...(passwordHash ? { OMP_WEB_PASSWORD_HASH: passwordHash } : {}), + ...(process.env.OMP_WEB_TRUSTED_HEADER_SHA256 ? { OMP_WEB_TRUSTED_HEADER_SHA256: process.env.OMP_WEB_TRUSTED_HEADER_SHA256 } : {}), ...(ompBin ? { OMP_WEB_OMP_BIN: ompBin } : {}), ...(agentDir ? { PI_CODING_AGENT_DIR: agentDir } : {}), }, envPath); diff --git a/bin/omp-web-systemd.test.mjs b/bin/omp-web-systemd.test.mjs index cbe99e943..12d552d42 100644 --- a/bin/omp-web-systemd.test.mjs +++ b/bin/omp-web-systemd.test.mjs @@ -164,6 +164,7 @@ test("install creates the env file and unit with LAN settings", { skip: process. OMP_WEB_HOSTNAME: "0.0.0.0", OMP_WEB_PASSWORD: "test-password", OMP_WEB_NO_OPEN: "0", + OMP_WEB_TRUSTED_HEADER_SHA256: "a".repeat(64), OMP_WEB_DISABLE_AUTOUPDATE: "1", OMP_WEB_NAME: "My Box", PORT: "40123", @@ -193,6 +194,7 @@ test("install creates the env file and unit with LAN settings", { skip: process. OMP_WEB_NO_OPEN: "0", OMP_WEB_DISABLE_AUTOUPDATE: "1", OMP_WEB_NAME: "My Box", + OMP_WEB_TRUSTED_HEADER_SHA256: "a".repeat(64), }); assert.match(readFileSync(unitPath, "utf8"), /EnvironmentFile=.*web-service\.env/); assert.match(result.stdout, /config:.*web-service\.env/); diff --git a/bin/omp-web-tray.exe b/bin/omp-web-tray.exe index aa4863b01ae2a955ab3daa6a05a3640b14abb2ed..f81b93056e37f3e9750e1b5301b8ce3095f09874 100644 GIT binary patch delta 10405 zcmb_i34B!5)j#*XnKw&jh9p2jAd*Q)V$7bf1_-hwCL&8h0w|(kNQNYksG(E6l-z$uxhmwTU%G`_rLc|k_q%{`}=+0LZ{R796eqseB%( z-izn+N0u#p6VHQ1FH}E|=Sxq&uvEo!S;5Ovep$iKs(%4`Nn>q;u+^J9CaR*8sBWuD zL^t&QwU-4CZecSR9!L39_Jrj~LrVGEjDohp-+eSeAu7MwItg_7_R`00di!Z6w5${Q z-fK$ZXHOnwZ|alfeLv6=SaILawWI91z8hPU*p+<`wT@>q`;N7iu`_)! zZ5h^A-(;lp-O@UaJ>0jVZ9Lo2x3R5^%|3XvZ8jUJoDgnGQfJ?EHtgrqzEOb*?3KQ0 zfvZ_tpAo2JiG3dhc3N*a&WKAh>-zQt$Fl`}hk|7Yg0)}7-t5b2_p(EM3)&Oeu7i#3 zTV}Db2mgF<(g=3yVCwU)7P7d5fBoAu#!mEQe?ETfkE$7MInw@a`AzPAp#K}f%xbI>yX-l3v$Y;P^3rUYM;bNbuaSZ@9h?Fx#Jh-mG)ZEG zfVH%SCQEKU@Tp;{kfwo~kN0Ho{4^1Ct<)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Syl z71BY4G`*D`f}3X~o?xPVifyGr+eO(XE;u$G5v+hDCPxv2BfjxCA1gFuTBh$m}R(vjyyN_FJrq z>!@ElPvnpCAM!isGJQpV!zONP7F&1pXErX*IFP$Or+Kp?h-ls)a9g^W7defK)XmJ( z{OB!;r}>&&co%RJytS_nr%O-A7x>YCptlmo6VAox2v2j41FC1|)BH=EU^nwN%k*ue z;G9#$HG}<#9u>T?3pTDFUtU@|qNp@4m&PuvFVpLnhRPR)^i3gM3i3sBo?v?e}fZBc1HIuuI}1yRz{9>j=f$;fD; zFq#+@O%w^cQH=Kf_wo)~`=|HuL}s|Q@p0|TxA7Qz`@K8)D-Pqmy*#shWE+3R8B04G z>INKcKRfm4GGoiRv_p#V@ss?hQsC%g9N5oujE?>M^+=+_QH=8 zwBZ2pc^s+_A9TfkSoQmyPM^c(Z*G-de*iSp1AM@czAm`*xAcu|Ns?|``U-keV(qZ4OP^KS7^0$*_%VnXvS=`lnS#4;urmqV_c&Et>1km+|FYpxK zoT-Z@YkDYWVqG127#m*T$#I=JO_qsH?ObLmWOpf;jg_6QDzx>htE(_Mbs@dJIwTyz zPwb1lq_ne3`s9U6r_WiisC4ndsikO5nY(mh>Eh|7%O=jARXT6M+!<3RFPc7g&O&ru zT~-qgnf;o?3((Xk8tMAR_4U=Yp+#kSRjA%{^4^O)cdn_N9( z3Y1HA4N65@KetYxjL=Lo9XlVanK7H=X_Ou0iN>mzuuv__lH(n2m67Rr&r5tjiYb?~ zUk)>N14WqRirn(&# z)X9wN%*D}J0FZ=3y79qb9=o_R%=GY@vXOcD=x&aW6^j^QdAgy#MV)&#E~_iM`|hb_ xGbmW;k6_1LV*K<7PjhxLFC5{y?(RND;>&#S{{VjEA2|R3 diff --git a/lib/project-command-env.test.mjs b/lib/project-command-env.test.mjs index 6bc987547..fcfca6f54 100644 --- a/lib/project-command-env.test.mjs +++ b/lib/project-command-env.test.mjs @@ -45,7 +45,7 @@ test("strips omp-web's own secrets from a child environment", () => { PATH: "/usr/bin", OMP_WEB_PASSWORD: "hunter2", OMP_WEB_PASSWORD_HASH: "scrypt$15$8$1$aaaa$bbbb", - OMP_WEB_TRUSTED_HEADER_SECRET: "shared-secret", + OMP_WEB_TRUSTED_HEADER_SHA256: "a".repeat(64), OMP_WEB_OMP_BIN: "/usr/local/bin/omp", OMP_WEB_PORT: "30177", HOME: "/home/u", diff --git a/lib/project-command-env.ts b/lib/project-command-env.ts index baa9d22a4..be34a8ee9 100644 --- a/lib/project-command-env.ts +++ b/lib/project-command-env.ts @@ -25,7 +25,7 @@ const HOST_RUNTIME_NAMES: readonly string[] = ["PORT", "NODE_ENV"]; export const OMP_WEB_SECRET_ENV_VARS: readonly string[] = [ "OMP_WEB_PASSWORD", "OMP_WEB_PASSWORD_HASH", - "OMP_WEB_TRUSTED_HEADER_SECRET", + "OMP_WEB_TRUSTED_HEADER_SHA256", ]; /** Prefixes that never reach a child process. */ diff --git a/lib/web-auth.test.mjs b/lib/web-auth.test.mjs index 856b54954..dfb96d979 100644 --- a/lib/web-auth.test.mjs +++ b/lib/web-auth.test.mjs @@ -1,4 +1,5 @@ import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -185,6 +186,44 @@ test("refuses every request while the password configuration is broken", () => { }); }); +test("accepts the trusted proxy header only when its SHA-256 matches the configured digest", () => { + const previousDigest = process.env.OMP_WEB_TRUSTED_HEADER_SHA256; + const digest = createHash("sha256").update("proxy-secret").digest("hex"); + const request = (path, value) => proxy(new NextRequest(`http://localhost:30177${path}`, { + headers: value === undefined ? {} : { "x-omp-web-auth": value }, + })); + withEnvVars({ OMP_WEB_PASSWORD_HASH: PASSWORD_HASH }, () => { + try { + process.env.OMP_WEB_TRUSTED_HEADER_SHA256 = digest; + assert.equal(request("/", "proxy-secret").status, 200); + assert.equal(request("/api/sessions", "proxy-secret").status, 200); + assert.equal(request("/login", "proxy-secret").headers.get("location"), "http://localhost:30177/"); + assert.equal(request("/api/sessions", "wrong").status, 401); + assert.equal(request("/api/sessions", "proxy-secretX").status, 401); + assert.equal(request("/api/sessions", "proxy-secre").status, 401); + assert.equal(request("/api/sessions", "PROXY-SECRET").status, 401); + assert.equal(request("/api/sessions", "").status, 401); + assert.equal(request("/api/sessions").status, 401); + // The digest itself is not a credential. + assert.equal(request("/api/sessions", digest).status, 401); + + process.env.OMP_WEB_TRUSTED_HEADER_SHA256 = digest.toUpperCase(); + assert.equal(request("/api/sessions", "proxy-secret").status, 200, "uppercase digest"); + + // Unset, empty or malformed digest disables the header; nginx's empty value never matches. + for (const value of [undefined, "", "proxy-secret", digest.slice(1), `${digest}0`, `${digest.slice(2)}zz`]) { + if (value === undefined) delete process.env.OMP_WEB_TRUSTED_HEADER_SHA256; + else process.env.OMP_WEB_TRUSTED_HEADER_SHA256 = value; + assert.equal(request("/api/sessions", "").status, 401, String(value)); + assert.equal(request("/api/sessions", "proxy-secret").status, 401, String(value)); + } + } finally { + if (previousDigest === undefined) delete process.env.OMP_WEB_TRUSTED_HEADER_SHA256; + else process.env.OMP_WEB_TRUSTED_HEADER_SHA256 = previousDigest; + } + }); +}); + test("leaves Next.js build assets outside password protection", () => { assert.equal(unstable_doesMiddlewareMatch({ config, nextConfig: {}, url: "/_next/static/chunks/app.js" }), false); assert.equal(unstable_doesMiddlewareMatch({ config, nextConfig: {}, url: "/api/sessions" }), true); diff --git a/lib/web-auth.ts b/lib/web-auth.ts index fff3e218c..f90543063 100644 --- a/lib/web-auth.ts +++ b/lib/web-auth.ts @@ -1,9 +1,11 @@ -import { createHmac, randomBytes, timingSafeEqual } from "node:crypto"; +import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto"; import { deriveSessionSigningKey } from "./web-auth-secret"; import { isPasswordHash, verifyPassword } from "./web-password-hash"; export const OMP_WEB_SESSION_COOKIE = "omp_web_session"; export const OMP_WEB_SESSION_MAX_AGE_SECONDS = 60 * 60 * 24 * 30; +// Set by a trusted reverse proxy (see README) to vouch for a request in place of a session. +export const OMP_WEB_TRUSTED_HEADER = "x-omp-web-auth"; /** * Password protection for the web UI (issue #239). Only a hash is accepted: @@ -32,6 +34,16 @@ export function isWebPasswordEnabled(env: NodeJS.ProcessEnv = process.env): bool return isPasswordHash(configuredHash(env)); } +// The proxy sends the secret itself; omp-web holds only its SHA-256 hex digest. +// The secret is random, so a fast hash suffices. +export function isTrustedProxyRequest( + value: string | null | undefined, + digest = process.env.OMP_WEB_TRUSTED_HEADER_SHA256, +): boolean { + if (!value || !digest || !/^[0-9a-f]{64}$/i.test(digest)) return false; + return timingSafeEqual(createHash("sha256").update(value, "utf8").digest(), Buffer.from(digest, "hex")); +} + /** Check a sign-in attempt against the configured hash. */ export function isValidWebPassword(candidate: string, env: NodeJS.ProcessEnv = process.env): boolean { const stored = configuredHash(env); diff --git a/native/tray/Program.cs b/native/tray/Program.cs index 2808628d2..a057905c7 100644 --- a/native/tray/Program.cs +++ b/native/tray/Program.cs @@ -228,6 +228,22 @@ private string FindNodeExecutable() return "node.exe"; } + // Copy an omp-web credential from the user (then system) environment into the child, + // or remove it there. The tray's own environment was captured at logon, so a value + // changed or removed with `setx` since then must not survive a server restart: the + // old password would keep working after rotation. + private static string? SetChildCredential(ProcessStartInfo psi, string name) + { + var value = Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.User); + if (string.IsNullOrEmpty(value)) + value = Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Machine); + if (string.IsNullOrEmpty(value)) + psi.EnvironmentVariables.Remove(name); + else + psi.EnvironmentVariables[name] = value; + return value; + } + private void StartWebServer() { if (_childProcess != null && !_childProcess.HasExited) return; @@ -262,6 +278,12 @@ private void StartWebServer() psi.EnvironmentVariables["OMP_WEB_HOSTNAME"] = _effectiveHostname; psi.EnvironmentVariables["OMP_WEB_SERVICE"] = "1"; psi.EnvironmentVariables["PORT"] = _effectivePort.ToString(); + // bin/omp-web.js refuses a non-loopback bind without a password hash. A plaintext + // OMP_WEB_PASSWORD is passed through only so the server can refuse it with instructions. + if (string.IsNullOrEmpty(SetChildCredential(psi, "OMP_WEB_PASSWORD_HASH"))) + WriteLog("WARN: OMP_WEB_PASSWORD_HASH not found in the user or system environment; a non-loopback bind will be refused by bin/omp-web.js (generate one with: ompweb hash-password)"); + SetChildCredential(psi, "OMP_WEB_PASSWORD"); + SetChildCredential(psi, "OMP_WEB_TRUSTED_HEADER_SHA256"); var proc = new Process { StartInfo = psi, EnableRaisingEvents = true }; proc.OutputDataReceived += (s, e) => { if (!string.IsNullOrEmpty(e.Data)) WriteLog($"[STDOUT] {e.Data}"); }; diff --git a/proxy.ts b/proxy.ts index 92508e857..bf9c261b6 100644 --- a/proxy.ts +++ b/proxy.ts @@ -1,10 +1,12 @@ import { NextResponse, type NextRequest } from "next/server"; import { isApiRequestOriginAllowed, shouldCheckApiRequestOrigin } from "@/lib/request-security"; import { + isTrustedProxyRequest, isValidWebSession, isWebPasswordEnabled, webPasswordConfigurationProblem, OMP_WEB_SESSION_COOKIE, + OMP_WEB_TRUSTED_HEADER, } from "@/lib/web-auth"; export function proxy(request: NextRequest) { @@ -29,7 +31,8 @@ export function proxy(request: NextRequest) { } const { pathname } = request.nextUrl; - const hasSession = isValidWebSession(request.cookies.get(OMP_WEB_SESSION_COOKIE)?.value); + const hasSession = isTrustedProxyRequest(request.headers.get(OMP_WEB_TRUSTED_HEADER)) + || isValidWebSession(request.cookies.get(OMP_WEB_SESSION_COOKIE)?.value); if (pathname === "/login") { return hasSession ? NextResponse.redirect(new URL("/", request.url)) : NextResponse.next(); } diff --git a/scripts/windows/omp-web-service.ps1 b/scripts/windows/omp-web-service.ps1 index ec2bd8666..2696b06e4 100644 --- a/scripts/windows/omp-web-service.ps1 +++ b/scripts/windows/omp-web-service.ps1 @@ -96,6 +96,17 @@ function Test-ServerHealth { } catch { return $false } } +# Copy an omp-web credential from the user (then system) environment into the +# child, or remove it there. This launcher's own environment was captured at +# logon, so a value changed or removed with `setx` since then must not survive +# a server restart: the old password would keep working after rotation. +function Set-ChildCredential($psi, [string]$name) { + $value = [Environment]::GetEnvironmentVariable($name, "User") + if ([string]::IsNullOrEmpty($value)) { $value = [Environment]::GetEnvironmentVariable($name, "Machine") } + if ([string]::IsNullOrEmpty($value)) { $psi.EnvironmentVariables.Remove($name) } else { $psi.EnvironmentVariables[$name] = $value } + return $value +} + function Start-WebServer { if ($script:ChildProcess -and !$script:ChildProcess.HasExited) { return } Write-ServiceLog "Starting web server in $EffectiveMode mode on ${EffectiveHostname}:$EffectivePort..." @@ -126,17 +137,14 @@ function Start-WebServer { $psi.EnvironmentVariables["OMP_WEB_HOSTNAME"] = [string]$EffectiveHostname $psi.EnvironmentVariables["OMP_WEB_SERVICE"] = "1" $psi.EnvironmentVariables["PORT"] = [string]$EffectivePort - # Pass the password hash explicitly: bin/omp-web.js refuses a non-loopback - # bind without one, and an inherited environment block can be stale. A - # plaintext password is hashed here and never forwarded as-is. - $childHash = [Environment]::GetEnvironmentVariable("OMP_WEB_PASSWORD_HASH", "Process") + # bin/omp-web.js refuses a non-loopback bind without a password hash. A + # plaintext OMP_WEB_PASSWORD is passed through only so the server can refuse + # it with instructions; generate a hash with `ompweb hash-password`. + $childHash = Set-ChildCredential $psi "OMP_WEB_PASSWORD_HASH" + $null = Set-ChildCredential $psi "OMP_WEB_PASSWORD" + $null = Set-ChildCredential $psi "OMP_WEB_TRUSTED_HEADER_SHA256" if ([string]::IsNullOrEmpty($childHash)) { - $childHash = [Environment]::GetEnvironmentVariable("OMP_WEB_PASSWORD_HASH", "User") - } - if (![string]::IsNullOrEmpty($childHash)) { - $psi.EnvironmentVariables["OMP_WEB_PASSWORD_HASH"] = $childHash - } else { - Write-ServiceLog "WARN: OMP_WEB_PASSWORD_HASH not found in the process or user environment; a non-loopback bind will be refused by bin/omp-web.js (generate one with: ompweb hash-password)" + Write-ServiceLog "WARN: OMP_WEB_PASSWORD_HASH not found in the user or system environment; a non-loopback bind will be refused by bin/omp-web.js (generate one with: ompweb hash-password)" } $proc = New-Object System.Diagnostics.Process $proc.StartInfo = $psi diff --git a/scripts/windows/omp-web-tray.ps1 b/scripts/windows/omp-web-tray.ps1 index bc3474e07..f456cc85c 100644 --- a/scripts/windows/omp-web-tray.ps1 +++ b/scripts/windows/omp-web-tray.ps1 @@ -203,6 +203,17 @@ function Find-NodeExecutable { $NodeExe = Find-NodeExecutable +# Copy an omp-web credential from the user (then system) environment into the +# child, or remove it there. This launcher's own environment was captured at +# logon, so a value changed or removed with `setx` since then must not survive +# a server restart: the old password would keep working after rotation. +function Set-ChildCredential($psi, [string]$name) { + $value = [Environment]::GetEnvironmentVariable($name, "User") + if ([string]::IsNullOrEmpty($value)) { $value = [Environment]::GetEnvironmentVariable($name, "Machine") } + if ([string]::IsNullOrEmpty($value)) { $psi.EnvironmentVariables.Remove($name) } else { $psi.EnvironmentVariables[$name] = $value } + return $value +} + function Start-WebServer { if ($script:ChildProcess -and !$script:ChildProcess.HasExited) { return @@ -247,18 +258,14 @@ function Start-WebServer { $psi.EnvironmentVariables["OMP_WEB_SERVICE"] = "1" $psi.EnvironmentVariables["PORT"] = [string]$EffectivePort - # bin/omp-web.js refuses a non-loopback bind without a password hash, so do not - # rely on inheritance alone: a logon-time environment block can be stale (e.g. - # after `setx OMP_WEB_PASSWORD_HASH`), and the child would then crash-loop on start. - # A plaintext password is never forwarded; generate a hash with `ompweb hash-password`. - $childHash = [Environment]::GetEnvironmentVariable("OMP_WEB_PASSWORD_HASH", "Process") + # bin/omp-web.js refuses a non-loopback bind without a password hash. A + # plaintext OMP_WEB_PASSWORD is passed through only so the server can refuse + # it with instructions; generate a hash with `ompweb hash-password`. + $childHash = Set-ChildCredential $psi "OMP_WEB_PASSWORD_HASH" + $null = Set-ChildCredential $psi "OMP_WEB_PASSWORD" + $null = Set-ChildCredential $psi "OMP_WEB_TRUSTED_HEADER_SHA256" if ([string]::IsNullOrEmpty($childHash)) { - $childHash = [Environment]::GetEnvironmentVariable("OMP_WEB_PASSWORD_HASH", "User") - } - if (![string]::IsNullOrEmpty($childHash)) { - $psi.EnvironmentVariables["OMP_WEB_PASSWORD_HASH"] = $childHash - } else { - Write-ServiceLog "WARN: OMP_WEB_PASSWORD_HASH not found in the process or user environment; a non-loopback bind will be refused by bin/omp-web.js (generate one with: ompweb hash-password)" + Write-ServiceLog "WARN: OMP_WEB_PASSWORD_HASH not found in the user or system environment; a non-loopback bind will be refused by bin/omp-web.js (generate one with: ompweb hash-password)" } $proc = New-Object System.Diagnostics.Process From f96233673de865d572eca1a3056bb02de2b257ec Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 9 Oct 2026 23:12:04 +0000 Subject: [PATCH 2/3] docs(auth): drop reusing a chosen proxy secret; require the generated one The digest is a fast unsalted SHA-256, safe only for a long random secret. --- README.md | 20 +++++++------------- 1 file changed, 7 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 0bea4784c..d353b4410 100644 --- a/README.md +++ b/README.md @@ -355,13 +355,9 @@ digest: ```bash secret=$(openssl rand -hex 32) -if [[ $secret =~ ^[A-Za-z0-9._~-]+$ ]]; then - printf 'map $ompweb_trusted $ompweb_auth {\n 1 "%s";\n default "";\n}\n' "$secret" \ - | sudo install -m 0640 -o root -g www-data /dev/stdin /etc/nginx/ompweb-auth.conf - printf %s "$secret" | sha256sum | cut -d' ' -f1 -else - echo "unsupported characters: use only letters, digits, . _ ~ and -" >&2 -fi +printf 'map $ompweb_trusted $ompweb_auth {\n 1 "%s";\n default "";\n}\n' "$secret" \ + | sudo install -m 0640 -o root -g www-data /dev/stdin /etc/nginx/ompweb-auth.conf +printf %s "$secret" | sha256sum | cut -d' ' -f1 unset secret ``` @@ -371,12 +367,10 @@ holds only the commands, never the secret. On Windows, the tray and background service read it from your user or system environment, like `OMP_WEB_PASSWORD_HASH`. -To use a secret you already have, replace the first line with `read -rs secret` -to enter it at a hidden prompt. It must contain only letters, digits, `.`, `_`, -`~` and `-`, because nginx would expand or reject other characters inside the -quoted `map` value while the digest is computed from the original. The check -above refuses any other secret before writing anything; generate a new one -instead. +Always generate the secret this way; do not reuse a password or another chosen +value. omp-web stores only a fast, unsalted SHA-256 digest, which is safe only +for a long random secret: anyone who reads the digest could recover a short or +guessable one with a dictionary attack. With nginx, send the secret only to the address ranges you trust: From 40d324ffc562db8581584471e44e5404948c3198 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 9 Oct 2026 23:30:27 +0000 Subject: [PATCH 3/3] fix(auth): keep stripping the legacy trusted-proxy secret name from child processes --- DESIGN.md | 3 ++- lib/project-command-env.test.mjs | 1 + lib/project-command-env.ts | 5 ++++- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 8857ab2db..0acea1901 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -185,7 +185,8 @@ Deploy the frontend and API support together; no native OMP upgrade is required. header is the reverse proxy's job, because omp-web has no client address it can trust. - omp-web's own secrets (`OMP_WEB_PASSWORD`, `OMP_WEB_PASSWORD_HASH`, - `OMP_WEB_TRUSTED_HEADER_SHA256`) are stripped from every child process + `OMP_WEB_TRUSTED_HEADER_SHA256` and its legacy name + `OMP_WEB_TRUSTED_HEADER_SECRET`) are stripped from every child process environment through `createChildProcessEnvironment` (`lib/project-command-env.ts`). `OMP_WEB_*` values that are configuration rather than secrets (`OMP_WEB_PACKAGE_DIR`, `OMP_WEB_OMP_BIN`, ...) are kept. diff --git a/lib/project-command-env.test.mjs b/lib/project-command-env.test.mjs index fcfca6f54..e04540017 100644 --- a/lib/project-command-env.test.mjs +++ b/lib/project-command-env.test.mjs @@ -45,6 +45,7 @@ test("strips omp-web's own secrets from a child environment", () => { PATH: "/usr/bin", OMP_WEB_PASSWORD: "hunter2", OMP_WEB_PASSWORD_HASH: "scrypt$15$8$1$aaaa$bbbb", + OMP_WEB_TRUSTED_HEADER_SECRET: "proxy-secret", OMP_WEB_TRUSTED_HEADER_SHA256: "a".repeat(64), OMP_WEB_OMP_BIN: "/usr/local/bin/omp", OMP_WEB_PORT: "30177", diff --git a/lib/project-command-env.ts b/lib/project-command-env.ts index be34a8ee9..b08450001 100644 --- a/lib/project-command-env.ts +++ b/lib/project-command-env.ts @@ -19,12 +19,15 @@ const HOST_RUNTIME_NAMES: readonly string[] = ["PORT", "NODE_ENV"]; /** * omp-web secrets. `OMP_WEB_PASSWORD` is the legacy plaintext (still listed so - * a dev server started from an old .env cannot leak it); the others are the + * a dev server started from an old .env cannot leak it), and + * `OMP_WEB_TRUSTED_HEADER_SECRET` is the pre-digest name of the trusted-proxy + * secret, which an old service env file may still carry; the others are the * values that grant access to this server. */ export const OMP_WEB_SECRET_ENV_VARS: readonly string[] = [ "OMP_WEB_PASSWORD", "OMP_WEB_PASSWORD_HASH", + "OMP_WEB_TRUSTED_HEADER_SECRET", "OMP_WEB_TRUSTED_HEADER_SHA256", ];