From 0d325e4390cd3caf775d479ca074fb729219222a Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 11 Nov 2026 10:51:02 +0900 Subject: [PATCH 1/2] feat(dashboard): remember devices behind an operator-named reverse proxy A standalone dashboard behind a TLS-terminating proxy could not use Remember this device: OpenCodex saw plain HTTP and refused (#8338). The opt-in dashboardTrustedProxy setting names one exact https origin, the proxy's own IP addresses, and which of X-Forwarded-Host/Proto to trust. The public listener records the kernel-observed peer; a request from a listed address whose Host (or trusted forwarded host) and scheme match the origin then resolves to that origin in managementRequestOrigin, so the Origin gate, enrollment and session admission agree. Forwarded values that contradict the origin or list several hops refuse even when untrusted. The setting is ignored on a loopback bind and outside standalone mode, a malformed hand edit disables it, and live writes refuse it with the reason. Without the setting nothing changes. --- .../content/docs/fr/guides/web-dashboard.md | 2 +- .../src/content/docs/guides/remote-hub.md | 7 + .../src/content/docs/guides/web-dashboard.md | 33 ++- .../content/docs/ja/guides/web-dashboard.md | 2 +- .../content/docs/ko/guides/web-dashboard.md | 2 +- .../docs/reference/configuration/server.md | 1 + .../content/docs/reference/management-api.md | 2 +- .../content/docs/ru/guides/web-dashboard.md | 2 +- .../content/docs/tr/guides/web-dashboard.md | 2 +- .../docs/zh-cn/guides/web-dashboard.md | 2 +- .../docs/zh-tw/guides/web-dashboard.md | 2 +- .../layout-persistent-dashboard.json | 1 + src/config/dashboard-trusted-proxy.ts | 81 +++++++ src/config/diagnostics.ts | 10 + src/config/schema/config-schema.ts | 4 + src/server/auth-cors.ts | 57 +++++ src/server/index/serve-options.ts | 7 +- src/server/persistent-gui-session.ts | 9 +- src/types/config.ts | 13 ++ structure/gui-and-management-api.md | 2 +- tests/fixtures/test-layout-expected.json | 1 + .../server-dashboard-trusted-proxy.test.ts | 211 ++++++++++++++++++ 22 files changed, 437 insertions(+), 16 deletions(-) create mode 100644 src/config/dashboard-trusted-proxy.ts create mode 100644 tests/server/server-dashboard-trusted-proxy.test.ts diff --git a/docs-site/src/content/docs/fr/guides/web-dashboard.md b/docs-site/src/content/docs/fr/guides/web-dashboard.md index c0133287a27..a90aad41e04 100644 --- a/docs-site/src/content/docs/fr/guides/web-dashboard.md +++ b/docs-site/src/content/docs/fr/guides/web-dashboard.md @@ -39,7 +39,7 @@ remplissage automatique. Le tableau de bord lui-même ne conserve le jeton qu'en dans `localStorage` ni dans `sessionStorage` ; son enregistrement dépend entièrement du navigateur ou du gestionnaire de mots de passe. -**Mémoriser cet appareil** est désactivé par défaut. Sur un tableau de bord HTTPS direct (ou en boucle locale), le serveur échange le jeton administrateur contre un cookie d’appareil HttpOnly, SameSite=Strict et une preuve distincte stockée dans le localStorage de ce site. Le cookie est Secure en HTTPS et limité à l’hôte. Ni le cookie ni la preuve ne sont le jeton administrateur, et aucun ne fonctionne seul. Les cookies sont partagés entre les ports d’un même nom d’hôte ; la preuve, limitée à l’origine, lie l’appareil mémorisé à l’origine de ce tableau de bord. Préférez tout de même un nom d’hôte dédié. Le jeton administrateur n’est jamais écrit dans localStorage ou sessionStorage. Si le stockage du navigateur est indisponible ou ne peut enregistrer la preuve, la mémorisation est signalée comme indisponible. Pour un tableau de bord autonome derrière un proxy inverse qui termine TLS, OpenCodex voit une requête HTTP simple et refuse donc la mémorisation pour cette adresse ; la fenêtre de connexion l’explique et désactive l’option, et la connexion sans mémorisation fonctionne toujours. Un écouteur de gestion Hub de confiance fait exception et peut toujours mémoriser les appareils. +**Mémoriser cet appareil** est désactivé par défaut. Sur un tableau de bord HTTPS direct (ou en boucle locale), le serveur échange le jeton administrateur contre un cookie d’appareil HttpOnly, SameSite=Strict et une preuve distincte stockée dans le localStorage de ce site. Le cookie est Secure en HTTPS et limité à l’hôte. Ni le cookie ni la preuve ne sont le jeton administrateur, et aucun ne fonctionne seul. Les cookies sont partagés entre les ports d’un même nom d’hôte ; la preuve, limitée à l’origine, lie l’appareil mémorisé à l’origine de ce tableau de bord. Préférez tout de même un nom d’hôte dédié. Le jeton administrateur n’est jamais écrit dans localStorage ou sessionStorage. Si le stockage du navigateur est indisponible ou ne peut enregistrer la preuve, la mémorisation est signalée comme indisponible. Pour un tableau de bord autonome derrière un proxy inverse qui termine TLS, OpenCodex voit une requête HTTP simple et refuse donc la mémorisation pour cette adresse ; la fenêtre de connexion l’explique et désactive l’option, et la connexion sans mémorisation fonctionne toujours. Un écouteur de gestion Hub de confiance fait exception et peut toujours mémoriser les appareils. Exception : en mode autonome, le réglage `dashboardTrustedProxy` autorise la mémorisation à travers ce seul proxy (origine HTTPS exacte, adresses IP du proxy et en-têtes de confiance ; voir « Remember behind a reverse proxy » dans la version anglaise du guide). Le fichier privé dashboard-sessions.json conserve les empreintes du cookie, de la preuve, du jeton administrateur et de l’identité du navigateur, l’origine du serveur et une expiration fixe de 30 jours. La relance de l’application Safari reprend une session courte tant que cet appareil reste autorisé. Les sessions mémorisées ne peuvent pas approuver les actions de consentement : étoile GitHub, consommation de crédits de réinitialisation, modification des couches de prompt, connexion Meta Muse, changements de compatibilité du bureau ou validation des quotas. Utilisez une nouvelle session locale ou appairée pour ces actions. Les tableaux de bord relayés, inter-origines ou HTTP distant ne prennent pas en charge la mémorisation. L’expiration, un changement d’identité du navigateur ou la rotation du jeton suivie d’un redémarrage imposent une nouvelle connexion. diff --git a/docs-site/src/content/docs/guides/remote-hub.md b/docs-site/src/content/docs/guides/remote-hub.md index e6d2014e398..dc6c9e6e7fd 100644 --- a/docs-site/src/content/docs/guides/remote-hub.md +++ b/docs-site/src/content/docs/guides/remote-hub.md @@ -340,6 +340,13 @@ The positive browser test must use a real signed-in Tailscale session; a bare `c identity headers needed for automatic session issuance. Pairing remains the fallback when the HTTPS frontend cannot provide trustworthy Tailscale identity. +**Remember this device** works on this management origin: the hub's management listener is the +trusted ingress, so a dashboard opened at `hub.managementPublicOrigin` can remember a device. A +standalone instance behind its own TLS-terminating proxy has no such listener; it can remember devices +only after you set `dashboardTrustedProxy` (see +[Remember behind a reverse proxy](/guides/web-dashboard/#remember-behind-a-reverse-proxy)). A hub +ignores that setting. + ### Giving the data listener TLS The Serve mapping above publishes the **management** ingress only. That ingress never serves diff --git a/docs-site/src/content/docs/guides/web-dashboard.md b/docs-site/src/content/docs/guides/web-dashboard.md index 2344a57ac40..54412349bea 100644 --- a/docs-site/src/content/docs/guides/web-dashboard.md +++ b/docs-site/src/content/docs/guides/web-dashboard.md @@ -37,7 +37,7 @@ password manager can offer to save and autofill it. The dashboard itself still k in memory and does not write it to `localStorage` or `sessionStorage`; whether it is saved is entirely the browser or password manager's decision. -**Remember this device** is off by default. On a direct HTTPS dashboard (or local loopback), it exchanges the admin token for a server-issued HttpOnly, SameSite=Strict device cookie plus a separate device proof stored in this site's localStorage. HTTPS cookies are Secure and host-only. Neither the cookie nor the proof is the admin token, and neither works alone. Cookies are shared across ports of the same hostname; the origin-scoped proof binds the remembered device to this dashboard origin. Still prefer a dedicated hostname. The admin token is never written to localStorage or sessionStorage. If browser storage is unavailable or cannot save the proof, Remember reports unavailable. On a standalone dashboard behind a TLS-terminating reverse proxy, OpenCodex sees a plain HTTP request, so it refuses Remember for that address; the sign-in dialog says so and turns the option off, and signing in without Remember still works. A trusted Hub management listener is the exception and can still remember devices. +**Remember this device** is off by default. On a direct HTTPS dashboard (or local loopback), it exchanges the admin token for a server-issued HttpOnly, SameSite=Strict device cookie plus a separate device proof stored in this site's localStorage. HTTPS cookies are Secure and host-only. Neither the cookie nor the proof is the admin token, and neither works alone. Cookies are shared across ports of the same hostname; the origin-scoped proof binds the remembered device to this dashboard origin. Still prefer a dedicated hostname. The admin token is never written to localStorage or sessionStorage. If browser storage is unavailable or cannot save the proof, Remember reports unavailable. On a standalone dashboard behind a TLS-terminating reverse proxy, OpenCodex sees a plain HTTP request, so by default it refuses Remember for that address; the sign-in dialog says so and turns the option off, and signing in without Remember still works. To allow it, name that one proxy with `dashboardTrustedProxy` (see [Remember behind a reverse proxy](#remember-behind-a-reverse-proxy)). A trusted Hub management listener can also remember devices. The private dashboard-sessions.json stores hashes of the cookie, proof, admin credential and browser identity, the server origin and a fixed 30-day expiry. Relaunching the Safari home-screen app resumes a short-lived GUI session while that device record is valid. Remembered sessions cannot approve consent actions: GitHub stars, reset-credit consumption, prompt-layer edits, Meta Muse sign-in, desktop compatibility changes or quota validation. Use a fresh local or paired session for those actions. Cross-origin/relayed dashboards and remote plaintext HTTP do not support Remember. Expiry, a browser identity change, or rotating the admin token and restarting the server requires sign-in again. @@ -45,6 +45,37 @@ Successful **Forget this device** in the sidebar or mobile action bar (and sessi An already-issued session that is otherwise valid can still **Forget this device** after a browser User-Agent change; ordinary access and resumption continue to require the original browser identity. +### Remember behind a reverse proxy + +This is opt-in and applies to a standalone instance only. Tell OpenCodex the exact origin the browser +uses and the addresses the proxy connects from: + +```json +"dashboardTrustedProxy": { + "origin": "https://ocx.example.com", + "proxyAddresses": ["192.168.1.20"], + "trustHeaders": ["x-forwarded-proto"] +} +``` + +- `origin` must be one exact `https://` origin. An `http://` origin, a wildcard, a path or + credentials are refused. +- `proxyAddresses` are the proxy's own IP addresses as this machine sees them (`127.0.0.1` when the + proxy runs on the same host). Ranges, wildcards and host names are refused. A request from any + other address is never treated as proxied, whatever headers it carries. +- By default the browser's host is read from `Host`, so the proxy must pass the original `Host` + through (Caddy does by default). List `x-forwarded-host` in `trustHeaders` to read it from + `X-Forwarded-Host` instead, and `x-forwarded-proto` to also require `X-Forwarded-Proto: https`. +- An `X-Forwarded-Host` or `X-Forwarded-Proto` value that contradicts the configured origin, or that + lists more than one hop, refuses the request even when that header is not trusted. +- The setting is honored only on a non-loopback bind, where the admin token is required. A Hub + ignores it and uses its management listener instead. + +Remember still needs the admin token; a client certificate checked by the proxy grants nothing on its +own. The Origin checks, the 30-day expiry, Forget and the consent restrictions above are unchanged. +`ocx config set` refuses a malformed value with the reason, and a malformed hand edit disables the +setting. Restart OpenCodex after changing it. + ### Finding the admin token You only need this on a non-loopback bind. A local dashboard never asks, and if a local one diff --git a/docs-site/src/content/docs/ja/guides/web-dashboard.md b/docs-site/src/content/docs/ja/guides/web-dashboard.md index 541d28d9314..247860ed73b 100644 --- a/docs-site/src/content/docs/ja/guides/web-dashboard.md +++ b/docs-site/src/content/docs/ja/guides/web-dashboard.md @@ -27,7 +27,7 @@ bun run dev:gui リモートダッシュボードでは標準のパスワードフォームが表示され、ブラウザのパスワードマネージャーで保存・自動入力できます。ダッシュボード自体はトークンをメモリ内だけに保持し、`localStorage` や `sessionStorage` には書き込みません。保存するかどうかはブラウザまたはパスワードマネージャーだけが決定します。 -**このデバイスを記憶する** は既定でオフです。直接アクセスする HTTPS ダッシュボード(またはローカルループバック)で、管理者トークンをサーバー発行の HttpOnly・SameSite=Strict デバイス Cookie と、このサイトの localStorage に保存する別のデバイス証明に交換します。HTTPS の Cookie は Secure でホスト限定です。Cookie も証明も管理者トークンではなく、どちらも単独では機能しません。同じホスト名のポート間では Cookie が共有されるため、オリジン単位の証明が記憶したデバイスをこのダッシュボードのオリジンに結び付けます。それでも専用ホスト名を推奨します。管理者トークンは localStorage や sessionStorage に保存しません。ブラウザーのストレージが使えない、または証明を保存できない場合、記憶機能は利用不可と表示されます。スタンドアロンのダッシュボードを TLS を終端するリバースプロキシ経由で使う場合、 OpenCodex には通常の HTTP リクエストとして見えるため、そのアドレスでは記憶を拒否します。サインイン画面がその旨を表示してオプションをオフにし、記憶なしのサインインは引き続き使えます。信頼された Hub の管理リスナーは例外で、引き続きデバイスを記憶できます。 +**このデバイスを記憶する** は既定でオフです。直接アクセスする HTTPS ダッシュボード(またはローカルループバック)で、管理者トークンをサーバー発行の HttpOnly・SameSite=Strict デバイス Cookie と、このサイトの localStorage に保存する別のデバイス証明に交換します。HTTPS の Cookie は Secure でホスト限定です。Cookie も証明も管理者トークンではなく、どちらも単独では機能しません。同じホスト名のポート間では Cookie が共有されるため、オリジン単位の証明が記憶したデバイスをこのダッシュボードのオリジンに結び付けます。それでも専用ホスト名を推奨します。管理者トークンは localStorage や sessionStorage に保存しません。ブラウザーのストレージが使えない、または証明を保存できない場合、記憶機能は利用不可と表示されます。スタンドアロンのダッシュボードを TLS を終端するリバースプロキシ経由で使う場合、 OpenCodex には通常の HTTP リクエストとして見えるため、そのアドレスでは記憶を拒否します。サインイン画面がその旨を表示してオプションをオフにし、記憶なしのサインインは引き続き使えます。信頼された Hub の管理リスナーは例外で、引き続きデバイスを記憶できます。例外として、スタンドアロンでは `dashboardTrustedProxy` を設定すると、その 1 つのプロキシ経由でも記憶できます(正確な HTTPS オリジン、プロキシの IP アドレス、信頼するヘッダーを指定します。詳細は英語版ガイドの「Remember behind a reverse proxy」を参照してください)。 非公開の dashboard-sessions.json は Cookie・証明・管理者認証情報・ブラウザー識別のハッシュ、サーバーのオリジンと固定30日間の有効期限を保存します。Safari ホーム画面アプリを再起動すると、有効なデバイス記録から短期セッションを再開します。記憶したセッションでは、GitHub スター、リセットクレジットの消費、プロンプト層の編集、Meta Muse サインイン、デスクトップ互換性の変更、クォータ検証などの同意操作を承認できません。これらには新しいローカルまたはペアリング済みセッションを使ってください。中継・別オリジン・リモートの平文 HTTP は記憶機能に対応しません。期限切れ、ブラウザー識別の変更、管理者トークン変更後のサーバー再起動では再ログインが必要です。 diff --git a/docs-site/src/content/docs/ko/guides/web-dashboard.md b/docs-site/src/content/docs/ko/guides/web-dashboard.md index 05cf8b5402d..68c796201c7 100644 --- a/docs-site/src/content/docs/ko/guides/web-dashboard.md +++ b/docs-site/src/content/docs/ko/guides/web-dashboard.md @@ -27,7 +27,7 @@ bun run dev:gui 원격 대시보드는 표준 비밀번호 폼을 표시하므로 브라우저 비밀번호 관리자가 토큰 저장과 자동 완성을 제안할 수 있습니다. 대시보드 자체는 토큰을 메모리에만 보관하며 `localStorage`나 `sessionStorage`에 쓰지 않습니다. 저장 여부는 전적으로 브라우저 또는 비밀번호 관리자가 결정합니다. -**이 기기 기억하기**는 기본적으로 꺼져 있습니다. 직접 HTTPS 대시보드(또는 로컬 루프백)에서 관리자 토큰을 서버 발급 HttpOnly, SameSite=Strict 기기 쿠키와 이 사이트의 localStorage에 저장하는 별도의 기기 증명으로 교환합니다. HTTPS 쿠키는 Secure이며 해당 호스트에만 적용됩니다. 쿠키와 증명은 모두 관리자 토큰이 아니며, 어느 쪽도 단독으로 작동하지 않습니다. 같은 호스트명의 여러 포트는 쿠키를 공유하므로, 오리진별 저장소의 증명이 기억한 기기를 이 대시보드 오리진에 묶습니다. 그래도 전용 호스트명을 권장합니다. 관리자 토큰은 localStorage나 sessionStorage에 저장하지 않습니다. 브라우저 저장소를 사용할 수 없거나 증명 저장에 실패하면 기억하기는 사용 불가로 표시됩니다. 독립 실행형 대시보드가 TLS를 종료하는 리버스 프록시 뒤에 있으면 OpenCodex가 일반 HTTP 요청으로 보기 때문에 해당 주소에서는 기억하기를 거부합니다. 로그인 창이 이를 안내하고 옵션을 끄며, 기억하기 없이 로그인하는 것은 계속 가능합니다. 신뢰된 Hub 관리 리스너는 예외이며 계속 기기를 기억할 수 있습니다. +**이 기기 기억하기**는 기본적으로 꺼져 있습니다. 직접 HTTPS 대시보드(또는 로컬 루프백)에서 관리자 토큰을 서버 발급 HttpOnly, SameSite=Strict 기기 쿠키와 이 사이트의 localStorage에 저장하는 별도의 기기 증명으로 교환합니다. HTTPS 쿠키는 Secure이며 해당 호스트에만 적용됩니다. 쿠키와 증명은 모두 관리자 토큰이 아니며, 어느 쪽도 단독으로 작동하지 않습니다. 같은 호스트명의 여러 포트는 쿠키를 공유하므로, 오리진별 저장소의 증명이 기억한 기기를 이 대시보드 오리진에 묶습니다. 그래도 전용 호스트명을 권장합니다. 관리자 토큰은 localStorage나 sessionStorage에 저장하지 않습니다. 브라우저 저장소를 사용할 수 없거나 증명 저장에 실패하면 기억하기는 사용 불가로 표시됩니다. 독립 실행형 대시보드가 TLS를 종료하는 리버스 프록시 뒤에 있으면 OpenCodex가 일반 HTTP 요청으로 보기 때문에 해당 주소에서는 기억하기를 거부합니다. 로그인 창이 이를 안내하고 옵션을 끄며, 기억하기 없이 로그인하는 것은 계속 가능합니다. 신뢰된 Hub 관리 리스너는 예외이며 계속 기기를 기억할 수 있습니다. 예외로, 독립 실행형에서 `dashboardTrustedProxy`를 설정하면 그 프록시 하나를 거쳐도 기억하기를 쓸 수 있습니다(정확한 HTTPS origin, 프록시 IP 주소, 신뢰할 헤더를 지정합니다. 자세한 내용은 영어 가이드의 "Remember behind a reverse proxy"를 참고하세요). 비공개 dashboard-sessions.json에는 쿠키·증명·관리자 인증 정보·브라우저 식별 해시, 서버 오리진과 고정 30일 만료를 저장합니다. Safari 홈 화면 앱을 다시 열면 유효한 기기 기록으로 단기 세션을 재개합니다. 기억한 세션으로는 GitHub 스타, 리셋 크레딧 소비, 프롬프트 계층 편집, Meta Muse 로그인, 데스크톱 호환성 변경, 할당량 검증에 동의할 수 없습니다. 이 작업에는 새 로컬 세션이나 페어링한 세션을 사용하세요. 릴레이·다른 오리진·원격 평문 HTTP에서는 기억하기를 지원하지 않습니다. 만료, 브라우저 식별 변경, 관리자 토큰 교체 후 서버 재시작 시 다시 로그인해야 합니다. diff --git a/docs-site/src/content/docs/reference/configuration/server.md b/docs-site/src/content/docs/reference/configuration/server.md index e3ea042a0c8..6dea9021b9f 100644 --- a/docs-site/src/content/docs/reference/configuration/server.md +++ b/docs-site/src/content/docs/reference/configuration/server.md @@ -36,6 +36,7 @@ passthrough, including native WebSocket output, retain their existing stop behav | `nativeReasoningRetention?` | `{ modelSwitch?: boolean; accountSwitch?: boolean }` | both `false` | Permit reasoning ciphertext forwarding across a known model or account change on the same canonical ChatGPT backend. Account retention is experimental. See [Native reasoning retention](#native-reasoning-retention). | | `workflowBudget?` | `{ maxConcurrentChildren?: number; maxPhysicalSends?: number; maxDistinctChildren?: number }` | `8` / `256` / `64` | Per-task fan-out ceilings: turns running at once, upstream sends per 10-minute window, and distinct subagent threads per window. Omitted fields keep the built-in value. See [Workflow limits](#workflow-limits). | | `corsAllowOrigins?` | `string[]` | `[]` | Additional exact origins allowed by CORS. Loopback origins are always allowed. Authority-based browser extension origins such as `chrome-extension://` are supported; `*` is not a wildcard. Firefox and Safari regenerate the extension UUID (per install / per browser launch), so update the entry when the origin changes. | +| `dashboardTrustedProxy?` | `{ origin: string; proxyAddresses: string[]; trustHeaders?: ("x-forwarded-host" \| "x-forwarded-proto")[] }` | unset | Standalone only, opt-in: lets **Remember this device** work through one TLS-terminating reverse proxy. `origin` is one exact `https://` origin, `proxyAddresses` are the proxy's exact IP addresses (no ranges or wildcards), and `trustHeaders` reads the browser host from `X-Forwarded-Host` and/or requires `X-Forwarded-Proto: https` (default: `Host` only). Ignored on a loopback bind or a Hub. See [Remember behind a reverse proxy](/guides/web-dashboard/#remember-behind-a-reverse-proxy). | | `apiKeys?` | `OcxApiKey[]` | `[]` | Generated `ocx_…` data-plane admission credentials on non-loopback binds. They do not authorize management APIs; management access uses the separate credential documented in the [management reference](/reference/management-api/). Dashboard-managed. | | `storageCleanupPolicy?` | `StorageCleanupPolicy` | disabled | Opt-in archived-session cleanup policy. Never enabled implicitly. | | `usageLedgerMaxBytes?` | `number` | unset | Opt-in ceiling in bytes for `usage.jsonl`. Absent means the request history grows without limit, which stays the default. See [usage history size](#usage-history-size). | diff --git a/docs-site/src/content/docs/reference/management-api.md b/docs-site/src/content/docs/reference/management-api.md index 056fb6db708..c14968ba1b0 100644 --- a/docs-site/src/content/docs/reference/management-api.md +++ b/docs-site/src/content/docs/reference/management-api.md @@ -61,7 +61,7 @@ route-specific results rather than repeating this table. | --- | --- | --- | | 401 | `opencodex admin token required` | The admin token or GUI session is missing, invalid, expired, origin-mismatched, or missing CSRF evidence | | 403 | `cross-origin request blocked` | The request origin is outside the management allowlist | -| 403 | `code: "remember_requires_direct_origin"` | `POST /api/session/remember` only: this dashboard address cannot hold a remembered device (for example a standalone dashboard behind a TLS-terminating proxy); sign in without Remember. The `error` text is `cross-origin request blocked` when the origin check refuses the request, and `Remember requires a direct HTTPS dashboard (or loopback) and matching Origin` when the origin check allows the request but the route still refuses it, for example because the address is not a direct HTTPS or loopback dashboard or no matching `Origin` header was sent; match on `code` | +| 403 | `code: "remember_requires_direct_origin"` | `POST /api/session/remember` only: this dashboard address cannot hold a remembered device (for example a standalone dashboard behind a TLS-terminating proxy without `dashboardTrustedProxy`, or a proxied request that did not come from one of its `proxyAddresses` or whose host, scheme or `Origin` does not match its `origin`); sign in without Remember. The `error` text is `cross-origin request blocked` when the origin check refuses the request, and `Remember requires a direct HTTPS dashboard (or loopback) and matching Origin` when the origin check allows the request but the route still refuses it, for example because the address is not a direct HTTPS, loopback or configured-proxy dashboard or no matching `Origin` header was sent; match on `code` | | 404 | `not_found` | No management route matched the method and path | | 413 | `request body too large` | A POST, PUT, or PATCH body exceeds the 2 MiB management limit | | 503 | `management API unavailable` | Admin credential initialization or hardening is unavailable | diff --git a/docs-site/src/content/docs/ru/guides/web-dashboard.md b/docs-site/src/content/docs/ru/guides/web-dashboard.md index c202469b659..cc2edac1a84 100644 --- a/docs-site/src/content/docs/ru/guides/web-dashboard.md +++ b/docs-site/src/content/docs/ru/guides/web-dashboard.md @@ -30,7 +30,7 @@ bun run dev:gui Удалённый дашборд показывает стандартную форму пароля, поэтому менеджер паролей браузера может предложить сохранить и автозаполнять токен. Сам дашборд хранит токен только в памяти и не записывает его в `localStorage` или `sessionStorage`; решение о сохранении полностью остаётся за браузером или менеджером паролей. -**Запомнить это устройство** по умолчанию выключено. При прямом HTTPS-доступе (или локальном loopback) сервер обменивает токен администратора на cookie устройства HttpOnly, SameSite=Strict и отдельное доказательство устройства в localStorage этого сайта. В HTTPS cookie имеет Secure и привязку к хосту. Ни cookie, ни доказательство не являются токеном администратора и не работают по отдельности. Cookie общие для портов одного имени хоста; доказательство в хранилище конкретного origin привязывает запомненное устройство к origin этой панели. Всё же предпочтительно отдельное имя хоста. Токен администратора не записывается в localStorage или sessionStorage. Если хранилище браузера недоступно или доказательство нельзя сохранить, запоминание сообщает о недоступности. Для автономной панели за обратным прокси, который завершает TLS, OpenCodex видит обычный HTTP-запрос и поэтому отказывает в запоминании для этого адреса; окно входа сообщает об этом и отключает опцию, а вход без запоминания по-прежнему работает. Исключение — доверенный управляющий слушатель Hub: он по-прежнему может запоминать устройства. +**Запомнить это устройство** по умолчанию выключено. При прямом HTTPS-доступе (или локальном loopback) сервер обменивает токен администратора на cookie устройства HttpOnly, SameSite=Strict и отдельное доказательство устройства в localStorage этого сайта. В HTTPS cookie имеет Secure и привязку к хосту. Ни cookie, ни доказательство не являются токеном администратора и не работают по отдельности. Cookie общие для портов одного имени хоста; доказательство в хранилище конкретного origin привязывает запомненное устройство к origin этой панели. Всё же предпочтительно отдельное имя хоста. Токен администратора не записывается в localStorage или sessionStorage. Если хранилище браузера недоступно или доказательство нельзя сохранить, запоминание сообщает о недоступности. Для автономной панели за обратным прокси, который завершает TLS, OpenCodex видит обычный HTTP-запрос и поэтому отказывает в запоминании для этого адреса; окно входа сообщает об этом и отключает опцию, а вход без запоминания по-прежнему работает. Исключение — доверенный управляющий слушатель Hub: он по-прежнему может запоминать устройства. Исключение: в автономном режиме настройка `dashboardTrustedProxy` разрешает запоминание через один такой прокси (точный HTTPS origin, IP-адреса прокси и доверенные заголовки; подробности — в разделе «Remember behind a reverse proxy» английской версии руководства). Приватный dashboard-sessions.json хранит хеши cookie, доказательства, учётных данных администратора и идентичности браузера, origin сервера и фиксированный срок 30 дней. Повторный запуск приложения Safari возобновляет короткую сессию, пока запись действительна. Запомненные сессии не могут подтверждать действия, требующие согласия: звезду GitHub, расход кредитов сброса, изменение слоёв промпта, вход Meta Muse, изменения совместимости настольного приложения или проверку квот. Для них используйте новую локальную или сопряжённую сессию. Релейный доступ, доступ с другого origin и удалённый HTTP без шифрования не поддерживают запоминание. Истечение срока, смена идентичности браузера или смена токена с перезапуском сервера требуют нового входа. diff --git a/docs-site/src/content/docs/tr/guides/web-dashboard.md b/docs-site/src/content/docs/tr/guides/web-dashboard.md index eb8f438d17c..e316b91c6e4 100644 --- a/docs-site/src/content/docs/tr/guides/web-dashboard.md +++ b/docs-site/src/content/docs/tr/guides/web-dashboard.md @@ -41,7 +41,7 @@ yalnızca bellekte tutar ve `localStorage` veya `sessionStorage`'a yazmaz; kaydedilip kaydedilmeyeceği tamamen tarayıcının veya şifre yöneticisinin kararıdır. -**Bu cihazı hatırla** varsayılan olarak kapalıdır. Doğrudan HTTPS panelinde (veya yerel loopback üzerinden) yönetici belirteci, sunucunun verdiği HttpOnly, SameSite=Strict cihaz çerezi ve bu sitenin localStorage alanında saklanan ayrı bir cihaz kanıtıyla değiştirilir. HTTPS çerezi Secure ve ana makineyle sınırlıdır. Çerez de kanıt da yönetici belirteci değildir; hiçbiri tek başına çalışmaz. Aynı ana makine adının portları çerezleri paylaşır; origin kapsamındaki kanıt, hatırlanan cihazı bu panelin origin’ine bağlar. Yine de ayrı bir ana makine adı tercih edin. Yönetici belirteci localStorage veya sessionStorage içine yazılmaz. Tarayıcı depolaması kullanılamıyorsa veya kanıt kaydedilemiyorsa Hatırla işlemi kullanılamadığını bildirir. TLS'i sonlandıran bir ters proxy arkasındaki bağımsız bir panelde OpenCodex düz bir HTTP isteği görür ve bu adres için Hatırla'yı reddeder; oturum açma penceresi bunu açıklar ve seçeneği kapatır, Hatırla olmadan oturum açmak çalışmaya devam eder. Güvenilen bir Hub yönetim dinleyicisi istisnadır ve cihazları hatırlamaya devam edebilir. +**Bu cihazı hatırla** varsayılan olarak kapalıdır. Doğrudan HTTPS panelinde (veya yerel loopback üzerinden) yönetici belirteci, sunucunun verdiği HttpOnly, SameSite=Strict cihaz çerezi ve bu sitenin localStorage alanında saklanan ayrı bir cihaz kanıtıyla değiştirilir. HTTPS çerezi Secure ve ana makineyle sınırlıdır. Çerez de kanıt da yönetici belirteci değildir; hiçbiri tek başına çalışmaz. Aynı ana makine adının portları çerezleri paylaşır; origin kapsamındaki kanıt, hatırlanan cihazı bu panelin origin’ine bağlar. Yine de ayrı bir ana makine adı tercih edin. Yönetici belirteci localStorage veya sessionStorage içine yazılmaz. Tarayıcı depolaması kullanılamıyorsa veya kanıt kaydedilemiyorsa Hatırla işlemi kullanılamadığını bildirir. TLS'i sonlandıran bir ters proxy arkasındaki bağımsız bir panelde OpenCodex düz bir HTTP isteği görür ve bu adres için Hatırla'yı reddeder; oturum açma penceresi bunu açıklar ve seçeneği kapatır, Hatırla olmadan oturum açmak çalışmaya devam eder. Güvenilen bir Hub yönetim dinleyicisi istisnadır ve cihazları hatırlamaya devam edebilir. İstisna: bağımsız modda `dashboardTrustedProxy` ayarı, hatırlamayı bu tek proxy üzerinden de mümkün kılar (tam HTTPS origin, proxy IP adresleri ve güvenilen başlıklar belirtilir; ayrıntılar için kılavuzun İngilizce sürümündeki "Remember behind a reverse proxy" bölümüne bakın). Özel dashboard-sessions.json çerezin, kanıtın, yönetici kimlik bilgisinin ve tarayıcı kimliğinin özetlerini, sunucu origin’ini ve sabit 30 günlük süreyi saklar. Safari ana ekran uygulaması yeniden açılınca geçerli cihaz kaydı kısa bir oturumu yeniler. Hatırlanan oturumlar onay gerektiren işlemleri yetkilendiremez: GitHub yıldızı, sıfırlama kredisi tüketimi, istem katmanı düzenlemeleri, Meta Muse girişi, masaüstü uyumluluk değişiklikleri veya kota doğrulaması. Bunlar için yeni bir yerel veya eşleştirilmiş oturum kullanın. Relay, başka origin ve uzak düz HTTP Hatırla seçeneğini desteklemez. Süre dolması, tarayıcı kimliği değişmesi veya belirtecin değiştirilip sunucunun yeniden başlatılması yeniden giriş gerektirir. diff --git a/docs-site/src/content/docs/zh-cn/guides/web-dashboard.md b/docs-site/src/content/docs/zh-cn/guides/web-dashboard.md index bf79353d62a..0222d683539 100644 --- a/docs-site/src/content/docs/zh-cn/guides/web-dashboard.md +++ b/docs-site/src/content/docs/zh-cn/guides/web-dashboard.md @@ -26,7 +26,7 @@ bun run dev:gui 远程仪表盘会显示标准密码表单,浏览器密码管理器可以提示保存并自动填充 token。仪表盘本身只在内存中保存 token,不会写入 `localStorage` 或 `sessionStorage`;是否持久保存完全由浏览器或密码管理器决定。 -**记住此设备** 默认关闭。直接 HTTPS 仪表板(或本地回环)会将管理员令牌交换为服务器签发的 HttpOnly、SameSite=Strict 设备 Cookie,以及单独存入本站 localStorage 的设备证明。HTTPS 下 Cookie 启用 Secure 且仅限本主机。Cookie 和证明都不是管理员令牌,且都不能单独使用。同一主机名的不同端口共享 Cookie;按来源隔离的证明将记住的设备绑定到本仪表板来源。仍建议使用专用主机名。管理员令牌不存入 localStorage 或 sessionStorage。浏览器存储不可用或无法保存证明时,记住设备会报告不可用。对于位于终止 TLS 的反向代理之后的独立仪表板,OpenCodex 看到的是普通 HTTP 请求,因此会拒绝为该地址记住设备;登录对话框会说明原因并关闭该选项,不勾选记住设备仍可正常登录。受信任的 Hub 管理监听器例外,仍可记住设备。 +**记住此设备** 默认关闭。直接 HTTPS 仪表板(或本地回环)会将管理员令牌交换为服务器签发的 HttpOnly、SameSite=Strict 设备 Cookie,以及单独存入本站 localStorage 的设备证明。HTTPS 下 Cookie 启用 Secure 且仅限本主机。Cookie 和证明都不是管理员令牌,且都不能单独使用。同一主机名的不同端口共享 Cookie;按来源隔离的证明将记住的设备绑定到本仪表板来源。仍建议使用专用主机名。管理员令牌不存入 localStorage 或 sessionStorage。浏览器存储不可用或无法保存证明时,记住设备会报告不可用。对于位于终止 TLS 的反向代理之后的独立仪表板,OpenCodex 看到的是普通 HTTP 请求,因此会拒绝为该地址记住设备;登录对话框会说明原因并关闭该选项,不勾选记住设备仍可正常登录。受信任的 Hub 管理监听器例外,仍可记住设备。例外:独立模式下配置 `dashboardTrustedProxy` 后,经由这一个代理也可以记住设备(需指定确切的 HTTPS 来源、代理的 IP 地址和要信任的请求头;详见英文指南的“Remember behind a reverse proxy”)。 私有 dashboard-sessions.json 保存 Cookie、证明、管理员凭据和浏览器标识的哈希、服务器来源及固定30天有效期。重新打开 Safari 主屏幕应用时,有效设备记录可恢复短期会话。记住的会话不能批准需要同意的操作:GitHub 星标、重置额度消费、提示词层编辑、Meta Muse 登录、桌面兼容性更改或配额验证。这些操作请使用新的本地会话或已配对会话。中继、跨来源和远程明文 HTTP 不支持记住设备。过期、浏览器标识改变,或更换管理员令牌并重启服务器后需重新登录。 diff --git a/docs-site/src/content/docs/zh-tw/guides/web-dashboard.md b/docs-site/src/content/docs/zh-tw/guides/web-dashboard.md index 119aa2b6006..b848a78aa77 100644 --- a/docs-site/src/content/docs/zh-tw/guides/web-dashboard.md +++ b/docs-site/src/content/docs/zh-tw/guides/web-dashboard.md @@ -31,7 +31,7 @@ GUI session 簽發到服務的頁面中,並在到期或代理重啟時靜默 儀表板本身仍然只在記憶體中保留 token,不會寫入 `localStorage` 或 `sessionStorage`;是否儲存完全 由瀏覽器或密碼管理員決定。 -**記住此裝置** 預設關閉。直接 HTTPS 儀表板(或本機回環)會將管理員權杖交換為伺服器簽發的 HttpOnly、SameSite=Strict 裝置 Cookie,以及另外存入本站 localStorage 的裝置證明。HTTPS 下 Cookie 使用 Secure,且僅限本主機。Cookie 和證明都不是管理員權杖,且都不能單獨使用。同一主機名稱的不同連接埠共用 Cookie;依來源隔離的證明將記住的裝置綁定至本儀表板來源。仍建議使用專用主機名稱。管理員權杖不存入 localStorage 或 sessionStorage。瀏覽器儲存空間無法使用或無法儲存證明時,記住裝置會回報無法使用。對於位於終止 TLS 的反向代理後方的獨立儀表板,OpenCodex 看到的是一般 HTTP 請求,因此會拒絕為該位址記住裝置;登入對話框會說明原因並關閉該選項,不勾選記住裝置仍可正常登入。受信任的 Hub 管理監聽器例外,仍可記住裝置。 +**記住此裝置** 預設關閉。直接 HTTPS 儀表板(或本機回環)會將管理員權杖交換為伺服器簽發的 HttpOnly、SameSite=Strict 裝置 Cookie,以及另外存入本站 localStorage 的裝置證明。HTTPS 下 Cookie 使用 Secure,且僅限本主機。Cookie 和證明都不是管理員權杖,且都不能單獨使用。同一主機名稱的不同連接埠共用 Cookie;依來源隔離的證明將記住的裝置綁定至本儀表板來源。仍建議使用專用主機名稱。管理員權杖不存入 localStorage 或 sessionStorage。瀏覽器儲存空間無法使用或無法儲存證明時,記住裝置會回報無法使用。對於位於終止 TLS 的反向代理後方的獨立儀表板,OpenCodex 看到的是一般 HTTP 請求,因此會拒絕為該位址記住裝置;登入對話框會說明原因並關閉該選項,不勾選記住裝置仍可正常登入。受信任的 Hub 管理監聽器例外,仍可記住裝置。例外:獨立模式下設定 `dashboardTrustedProxy` 後,透過這一個代理也能記住裝置(需指定確切的 HTTPS 來源、代理的 IP 位址與要信任的標頭;詳見英文指南的「Remember behind a reverse proxy」)。 私有 dashboard-sessions.json 儲存 Cookie、證明、管理員憑證和瀏覽器識別的雜湊、伺服器來源及固定30天有效期。重新開啟 Safari 主畫面應用程式時,有效裝置記錄可恢復短期工作階段。記住的工作階段無法核准需要同意的操作:GitHub 星號、重設額度消耗、提示詞層編輯、Meta Muse 登入、桌面相容性變更或配額驗證。這些操作請使用新的本機工作階段或已配對工作階段。中繼、跨來源和遠端明文 HTTP 不支援記住裝置。過期、瀏覽器識別變更,或更換管理員權杖並重新啟動伺服器後需重新登入。 diff --git a/scripts/test-layout/layout-persistent-dashboard.json b/scripts/test-layout/layout-persistent-dashboard.json index 022ffb2e898..6ad67a50527 100644 --- a/scripts/test-layout/layout-persistent-dashboard.json +++ b/scripts/test-layout/layout-persistent-dashboard.json @@ -2,5 +2,6 @@ "persistent-dashboard-session.test.ts": "server", "persistent-dashboard-admission.test.ts": "server", "persistent-dashboard-consent.test.ts": "server", + "server-dashboard-trusted-proxy.test.ts": "server", "atomic-write-nofollow-streamed.test.ts": "config" } diff --git a/src/config/dashboard-trusted-proxy.ts b/src/config/dashboard-trusted-proxy.ts new file mode 100644 index 00000000000..57cd397ff6d --- /dev/null +++ b/src/config/dashboard-trusted-proxy.ts @@ -0,0 +1,81 @@ +import { isIP } from "node:net"; +import { z } from "zod"; + +/** + * `dashboardTrustedProxy` (#8338): the one reverse proxy a standalone dashboard may sit behind + * and still remember devices. Pure parsing shared by the load schema, the live-write check and + * the request path, so every reader applies the same rules. Nothing here trusts a header. + */ +export const DASHBOARD_TRUSTED_PROXY_HEADERS = ["x-forwarded-host", "x-forwarded-proto"] as const; +export type DashboardTrustedProxyHeader = typeof DASHBOARD_TRUSTED_PROXY_HEADERS[number]; +export const MAX_DASHBOARD_PROXY_ADDRESSES = 16; + +export interface DashboardTrustedProxySettings { + /** Canonical `https://host[:port]` origin the browser uses. */ + origin: string; + /** The origin's host as `URL.host` spells it (lowercase, default port removed). */ + host: string; + /** Normalized peer addresses of the proxy hop. */ + addresses: ReadonlySet; + trust: ReadonlySet; +} + +/** One IP literal in the form `requestIP()` reports, or null. IPv4-mapped IPv6 reads as IPv4. */ +export function normalizeProxyAddress(value: string): string | null { + const raw = value.trim(); + const version = isIP(raw); + if (version === 4) return raw; + if (version !== 6) return null; + let host: string; + try { host = new URL(`http://[${raw}]/`).hostname.slice(1, -1); } catch { return null; } + const mapped = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(host); + if (mapped) { + const high = Number.parseInt(mapped[1]!, 16); + const low = Number.parseInt(mapped[2]!, 16); + return [high >> 8, high & 255, low >> 8, low & 255].join("."); + } + return host; +} + +/** A parsed setting, or the reason it is unusable. Unknown fields are refused. */ +export function parseDashboardTrustedProxy(value: unknown): DashboardTrustedProxySettings | string { + if (!value || typeof value !== "object" || Array.isArray(value)) return "must be an object"; + const record = value as Record; + const unknown = Object.keys(record).find(key => key !== "origin" && key !== "proxyAddresses" && key !== "trustHeaders"); + if (unknown !== undefined) return `contains an unsupported field: ${unknown}`; + const { origin, proxyAddresses, trustHeaders } = record; + if (typeof origin !== "string" || origin.includes("*")) return "origin must be one exact https origin (no wildcards)"; + let parsed: URL; + try { parsed = new URL(origin); } catch { return "origin must be one exact https origin (no wildcards)"; } + if (parsed.protocol !== "https:") return "origin must use https"; + if (parsed.username || parsed.password || parsed.pathname !== "/" || parsed.search || parsed.hash || !parsed.hostname) { + return "origin must be an origin without credentials, path, query, or fragment"; + } + if (!Array.isArray(proxyAddresses) || proxyAddresses.length === 0 || proxyAddresses.length > MAX_DASHBOARD_PROXY_ADDRESSES) { + return `proxyAddresses must list 1 to ${MAX_DASHBOARD_PROXY_ADDRESSES} proxy IP addresses`; + } + const addresses = new Set(); + for (const entry of proxyAddresses) { + const address = typeof entry === "string" ? normalizeProxyAddress(entry) : null; + if (!address) return "proxyAddresses must be exact IP addresses (no ranges, wildcards, or host names)"; + addresses.add(address); + } + const trust = new Set(); + if (trustHeaders !== undefined) { + if (!Array.isArray(trustHeaders)) return "trustHeaders must be a list"; + for (const header of trustHeaders) { + const name = typeof header === "string" ? header.toLowerCase() : ""; + if (!(DASHBOARD_TRUSTED_PROXY_HEADERS as readonly string[]).includes(name)) { + return "trustHeaders may contain only x-forwarded-host and x-forwarded-proto"; + } + trust.add(name as DashboardTrustedProxyHeader); + } + } + return { origin: parsed.origin, host: parsed.host, addresses, trust }; +} + +/** Load schema: keeps the operator's spelling and refuses anything the parser refuses. */ +export const dashboardTrustedProxySchema = z.unknown().superRefine((value, ctx) => { + const parsed = parseDashboardTrustedProxy(value); + if (typeof parsed === "string") ctx.addIssue({ code: "custom", message: parsed }); +}) as unknown as z.ZodType<{ origin: string; proxyAddresses: string[]; trustHeaders?: DashboardTrustedProxyHeader[] }>; diff --git a/src/config/diagnostics.ts b/src/config/diagnostics.ts index 617db940f68..8cf9f186b02 100644 --- a/src/config/diagnostics.ts +++ b/src/config/diagnostics.ts @@ -1,3 +1,4 @@ +import { parseDashboardTrustedProxy } from "./dashboard-trusted-proxy"; import { readExistingSpendSalt, spendPoolAliasesError, validatePoolAliasOwners } from "../lib/spend-pool-alias-validation"; import { isSubagentModelEntry, rawSubagentModelForce } from "./subagent-models"; import { validRemainingQuotaAccountIds } from "../codex/account-use-remaining"; @@ -633,6 +634,14 @@ export function loopbackCompanionBindError( * this opt-in listener cannot discard providers or credentials. A live config mutation must not * get that leniency: it receives an exact field error before the degrading schema is applied. */ +/** #8338: the persisted schema drops a malformed trusted-proxy block; a live write gets the reason. */ +function dashboardTrustedProxyConfigError(value: unknown): string | null { + const raw = rawConfigRecord(value); + if (!raw || !Object.hasOwn(raw, "dashboardTrustedProxy") || raw.dashboardTrustedProxy === undefined) return null; + const parsed = parseDashboardTrustedProxy(raw.dashboardTrustedProxy); + return typeof parsed === "string" ? `schema_invalid: dashboardTrustedProxy: ${parsed}` : null; +} + function managementIngressConfigError(value: unknown): string | null { const raw = rawConfigRecord(value); if (!raw) return null; @@ -785,6 +794,7 @@ export function validateConfigCandidate(value: unknown): { ok: true; config: Ocx ?? clientRolePairError(value) ?? loopbackListenerPortError(value) ?? managementIngressConfigError(value) + ?? dashboardTrustedProxyConfigError(value) ?? metricsExportConfigError(value) ?? serviceHealthRecoveryConfigError(value) ?? telemetryConfigError(value) diff --git a/src/config/schema/config-schema.ts b/src/config/schema/config-schema.ts index 8eff59bbd32..1a6d4e4448d 100644 --- a/src/config/schema/config-schema.ts +++ b/src/config/schema/config-schema.ts @@ -1,3 +1,4 @@ +import { dashboardTrustedProxySchema } from "../dashboard-trusted-proxy"; import { MAIN_ACCOUNT_HARD_LOCK_MIN_PERCENT } from "../../codex/quota-types"; import { validRemainingQuotaAccountIds } from "../../codex/account-use-remaining"; import * as z from "zod/v4"; @@ -116,6 +117,9 @@ export const configSchema = z.object({ // Malformed optional remote blocks disable only remote GUI behavior. Live // candidates are rejected explicitly by remoteGuiConfigError below. hub: hubConfigSchema.optional().catch(undefined), + // #8338: a malformed hand edit disables only the trusted-proxy opt-in (Remember then stays direct + // HTTPS or loopback only); live writes get the exact reason from diagnostics.ts. + dashboardTrustedProxy: dashboardTrustedProxySchema.optional().catch(undefined), remoteGui: remoteGuiConfigSchema.optional().catch(undefined), // A malformed privacy block must never be read as "unmask": .catch(undefined) drops it and // emailMaskingEnabled then falls back to masked, which is also what an absent block means. diff --git a/src/server/auth-cors.ts b/src/server/auth-cors.ts index c9056aec260..094f0ac6f0d 100644 --- a/src/server/auth-cors.ts +++ b/src/server/auth-cors.ts @@ -43,6 +43,7 @@ import { effectiveGoogleMode, getProviderRegistryEntry, providerCodexAccountMode import { providerConfigSeed } from "../providers/derive"; import { anthropicOAuthInstanceConfigError } from "../config/schema/anthropic-account-pool"; import { accountAutoPausePolicySchema } from "../config/schema/account-auto-pause"; +import { normalizeProxyAddress, parseDashboardTrustedProxy } from "../config/dashboard-trusted-proxy"; import type { OcxConfig, OcxProviderConfig } from "../types"; import { openRouterRoutingConfigError } from "../providers/openrouter-routing"; import { modelAutoCompactTokenLimitsConfigError } from "../providers/auto-compact-budget"; @@ -65,6 +66,59 @@ export function markTrustedHubManagementRequest(req: Request): void { export function inheritTrustedHubManagementRequest(source: Request, target: Request): void { if (trustedHubManagementRequests.has(source)) trustedHubManagementRequests.add(target); + const peer = dashboardProxyPeers.get(source); + if (peer !== undefined) dashboardProxyPeers.set(target, peer); +} + +// #8338: the kernel-observed peer of a public-listener request, recorded by the serve layer the +// same way as the hub mark above. No header can create or change it. +const dashboardProxyPeers = new WeakMap(); + +export function markDashboardProxyPeer(req: Request, address: string | undefined): void { + const normalized = address ? normalizeProxyAddress(address) : null; + if (normalized) dashboardProxyPeers.set(req, normalized); +} + +/** One forwarded value: undefined when absent, null when empty or a multi-hop list. */ +function singleForwardedValue(req: Request, name: string): string | null | undefined { + const value = req.headers.get(name); + if (value === null) return undefined; + const trimmed = value.trim(); + return trimmed && !trimmed.includes(",") ? trimmed : null; +} + +function forwardedAuthorityHost(value: string): string | null { + try { + const url = new URL(`https://${value}`); + return url.username || url.password || url.pathname !== "/" || url.search || url.hash ? null : url.host; + } catch { + return null; + } +} + +/** + * The configured dashboard origin when, and only when, the configured proxy delivered this request + * (#8338). The peer must be one of `proxyAddresses`; the browser host comes from Host, or from + * X-Forwarded-Host when that header is trusted; X-Forwarded-Proto must say https when trusted. A + * forwarded host or scheme that contradicts the configured origin refuses even when that header is + * not trusted, so a forged value can never pass silently. Standalone with remote auth only: a + * loopback bind must never hand local trust to whatever the proxy forwards. + */ +export function dashboardProxyOrigin(req: Request, config: OcxConfig): string | null { + if (config.dashboardTrustedProxy === undefined) return null; + const peer = dashboardProxyPeers.get(req); + if (peer === undefined) return null; + if ((config.runtimeRole ?? "standalone") !== "standalone" || !isApiAuthRequired(config)) return null; + const settings = parseDashboardTrustedProxy(config.dashboardTrustedProxy); + if (typeof settings === "string" || !settings.addresses.has(peer)) return null; + const forwardedHost = singleForwardedValue(req, "X-Forwarded-Host"); + const forwardedProto = singleForwardedValue(req, "X-Forwarded-Proto"); + if (forwardedHost === null || forwardedProto === null) return null; + if (forwardedHost !== undefined && forwardedAuthorityHost(forwardedHost) !== settings.host) return null; + if (forwardedProto !== undefined && forwardedProto.toLowerCase() !== "https") return null; + if (settings.trust.has("x-forwarded-proto") && forwardedProto === undefined) return null; + const authority = settings.trust.has("x-forwarded-host") ? forwardedHost : req.headers.get("Host"); + return authority && forwardedAuthorityHost(authority) === settings.host ? settings.origin : null; } export function setCorsOrigin(port: number): void { _corsOrigin = `http://localhost:${port}`; } @@ -152,6 +206,9 @@ function comparableOrigin(value: string): string | null { } export function managementRequestOrigin(req: Request, config: OcxConfig): string | null { + // #8338: a request the configured dashboard proxy delivered speaks for the configured origin. + const proxied = dashboardProxyOrigin(req, config); + if (proxied) return proxied; const host = req.headers.get("Host"); const parsedHost = parseHttpHost(host); if (!host || !parsedHost) return null; diff --git a/src/server/index/serve-options.ts b/src/server/index/serve-options.ts index 8174de67ba5..b4f5745fc4b 100644 --- a/src/server/index/serve-options.ts +++ b/src/server/index/serve-options.ts @@ -99,6 +99,7 @@ import { isAllowedManagementOrigin, isApiAuthRequired, isLoopbackHostname, + markDashboardProxyPeer, markTrustedHubManagementRequest, jsonResponse, admissionFields, @@ -330,9 +331,9 @@ export function createServeOptions(ctx: ServeOptionsContext) { const ingress = ingressForServer(requestServer); // Bind management-origin trust to the actual Bun listener object resolved above. // Neither Host nor any X-Forwarded-* header can manufacture this process-local mark. - if (ingress === "hub-management" && config.runtimeRole === "hub") { - markTrustedHubManagementRequest(req); - } + if (ingress === "hub-management" && config.runtimeRole === "hub") markTrustedHubManagementRequest(req); + // #8338: the kernel-observed peer, so the configured standalone dashboard proxy can be verified. + else if (ingress === "public" && config.dashboardTrustedProxy !== undefined) markDashboardProxyPeer(req, requestServer.requestIP(req)?.address); const requestUrl = codexCompatibleUrl(req.url); const linkPolicyView = ingress === "hub-link" ? linkPolicy() : undefined; // The unauthenticated loopback listener (#1102) serves a fixed allowlist and nothing diff --git a/src/server/persistent-gui-session.ts b/src/server/persistent-gui-session.ts index d45c08f2dcd..19d5e460caa 100644 --- a/src/server/persistent-gui-session.ts +++ b/src/server/persistent-gui-session.ts @@ -5,7 +5,7 @@ import { getConfigDir } from "../config/paths"; import { withConfigMutationLockSync } from "../config/mutation-lock"; import { atomicWriteFileNoFollowStreamed } from "../config/atomic-write"; import type { OcxConfig } from "../types"; -import { isLoopbackHostname, isTrustedHubManagementRequest, managementRequestOrigin } from "./auth-cors"; +import { dashboardProxyOrigin, isLoopbackHostname, isTrustedHubManagementRequest, managementRequestOrigin } from "./auth-cors"; import { mintSession, type GuiSessionRecord, type GuiSessionState } from "./gui-session"; export const REMEMBERED_GUI_TTL_MS = 30 * 86400_000; @@ -28,8 +28,11 @@ function directOrigin(req: Request, config: OcxConfig): string | null { if (!origin) return null; const url = new URL(origin); // The process-marked hub management listener sits behind a local TLS terminator, so its - // request URL is http: while the canonical public origin is https:. Nothing forwarded is trusted. - if (new URL(req.url).origin !== origin && !isTrustedHubManagementRequest(req)) return null; + // request URL is http: while the canonical public origin is https:. The configured standalone + // dashboard proxy (#8338) is the same shape, proven by its peer address. Nothing else forwarded + // is trusted. + if (new URL(req.url).origin !== origin && !isTrustedHubManagementRequest(req) + && dashboardProxyOrigin(req, config) !== origin) return null; if (url.protocol !== "https:" && !(url.protocol === "http:" && isLoopbackHostname(url.hostname))) return null; const browser = req.headers.get("Origin"); if (browser !== null && browser !== origin) return null; diff --git a/src/types/config.ts b/src/types/config.ts index 59a331c929c..52660af8bd5 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -1411,6 +1411,19 @@ export interface OcxConfig { tokenGuardian?: OcxTokenGuardianConfig; /** Additional exact origins allowed for CORS (e.g. HTTPS or chrome-extension://). Loopback origins are always allowed. */ corsAllowOrigins?: string[]; + /** + * #8338, opt-in, standalone only: the one reverse proxy a dashboard may sit behind and still + * remember devices. `origin` is the exact https origin the browser uses; `proxyAddresses` are + * the proxy hop's own IP addresses as this process observes them (never a range); and + * `trustHeaders` names the forwarded headers that carry the browser's host and scheme (default: + * Host only, scheme from `origin`). Absent, Remember stays direct HTTPS or loopback only. Parsed by + * src/config/dashboard-trusted-proxy.ts; enforced in managementRequestOrigin (src/server/auth-cors.ts). + */ + dashboardTrustedProxy?: { + origin: string; + proxyAddresses: string[]; + trustHeaders?: Array<"x-forwarded-host" | "x-forwarded-proto">; + }; /** * OCX-11 fallback off: refuse model or provider fallback per scope, and record per-device local * fallback permission. Absent keeps every chain as it was. See src/routing/fallback-policy.ts. diff --git a/structure/gui-and-management-api.md b/structure/gui-and-management-api.md index 0d81a6fa6bd..5d07643beb5 100644 --- a/structure/gui-and-management-api.md +++ b/structure/gui-and-management-api.md @@ -119,7 +119,7 @@ OpenCodex uses three mutually exclusive reusable admission credential classes: The service token file remains a delivery mechanism for the data-plane environment token; it is not a fourth credential class. A management credential that equals any configured data-plane credential -does not enable management access. The data plane may continue to start, but `/api/*` remains closed. The opt-in bodyless `POST /api/session/remember` returns a short-lived GUI session plus a device proof for this site's origin-scoped localStorage alongside a host-only HttpOnly, SameSite=Strict device cookie (Secure on HTTPS); neither is the admin token or works alone, and because cookies span ports on one hostname, the proof binds resume to the dashboard origin (a dedicated hostname is still preferred). `src/server/persistent-gui-session.ts` owns the private hash-only `dashboard-sessions.json` store (128 devices/128 KiB), server-origin/browser/admin-credential binding and fixed 30-day expiry; enrollment requires direct same-origin HTTPS or loopback (a refusal, including the management Origin gate on this path, carries `code: "remember_requires_direct_origin"`, which the sign-in dialog turns into an explanation, an unticked Remember and a kept token), browser-storage failure is reported unavailable, bootstrap alone sends the proof header, `remembered-admin` sessions never authorize pairing, data-key reveal or consent actions (GitHub star, reset-credit consumption, prompt-layer edits, Meta Muse sign-in, desktop compatibility changes and quota validation require a fresh local or paired session), and successful Forget/logout immediately revokes the record and derived sessions after content fsync and publication, removes the browser proof (failed logout retains it for retry), with directory-entry crash durability best effort and legacy bearer keys purged without reading or migration; tests: `tests/server/persistent-dashboard-session.test.ts`. +does not enable management access. The data plane may continue to start, but `/api/*` remains closed. The opt-in bodyless `POST /api/session/remember` returns a short-lived GUI session plus a device proof for this site's origin-scoped localStorage alongside a host-only HttpOnly, SameSite=Strict device cookie (Secure on HTTPS); neither is the admin token or works alone, and because cookies span ports on one hostname, the proof binds resume to the dashboard origin (a dedicated hostname is still preferred). `src/server/persistent-gui-session.ts` owns the private hash-only `dashboard-sessions.json` store (128 devices/128 KiB), server-origin/browser/admin-credential binding and fixed 30-day expiry; enrollment requires direct same-origin HTTPS or loopback, or (#8338, opt-in, standalone with a non-loopback bind only) a request whose kernel-observed peer is one of `dashboardTrustedProxy.proxyAddresses` and whose Host, or trusted X-Forwarded-Host/Proto, matches its exact https `origin`; a contradicting or multi-hop forwarded value refuses even when untrusted. `src/config/dashboard-trusted-proxy.ts` parses the setting for load, live writes and requests, `serve-options.ts` records the public-listener peer, and `managementRequestOrigin` then answers the configured origin so the Origin gate, enrollment and session admission agree; tests: `tests/server/server-dashboard-trusted-proxy.test.ts` (a refusal, including the management Origin gate on this path, carries `code: "remember_requires_direct_origin"`, which the sign-in dialog turns into an explanation, an unticked Remember and a kept token), browser-storage failure is reported unavailable, bootstrap alone sends the proof header, `remembered-admin` sessions never authorize pairing, data-key reveal or consent actions (GitHub star, reset-credit consumption, prompt-layer edits, Meta Muse sign-in, desktop compatibility changes and quota validation require a fresh local or paired session), and successful Forget/logout immediately revokes the record and derived sessions after content fsync and publication, removes the browser proof (failed logout retains it for retry), with directory-entry crash durability best effort and legacy bearer keys purged without reading or migration; tests: `tests/server/persistent-dashboard-session.test.ts`. CLI health collection follows the same boundary without transporting the reusable management credential. Its local-read HMAC capability is an additional single-use, route-scoped admission mechanism, not a reusable credential class. `ocx doctor` and OAuth health derive these capabilities diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 60ab418ac54..eb1f29f9db4 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1368,6 +1368,7 @@ "persistent-dashboard-session.test.ts": "server", "persistent-dashboard-admission.test.ts": "server", "persistent-dashboard-consent.test.ts": "server", + "server-dashboard-trusted-proxy.test.ts": "server", "atomic-write-nofollow-streamed.test.ts": "config", "server-management-log-admission.test.ts": "server", "server-opencode-go-goal-streaming.test.ts": "server", "server-rate-limit-retry-e2e.test.ts": "server", diff --git a/tests/server/server-dashboard-trusted-proxy.test.ts b/tests/server/server-dashboard-trusted-proxy.test.ts new file mode 100644 index 00000000000..b150a803945 --- /dev/null +++ b/tests/server/server-dashboard-trusted-proxy.test.ts @@ -0,0 +1,211 @@ +/** + * #8338: Remember this device on a standalone dashboard behind a reverse proxy, only through the + * operator's `dashboardTrustedProxy`. The proxy hop is proven by the kernel-observed peer; the + * browser's host and scheme come only from the headers the operator trusts, and any forwarded + * value that contradicts the configured origin is refused. + */ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { saveConfig, validateConfigCandidate } from "../../src/config"; +import { configSchema } from "../../src/config/schema/config-schema"; +import { startServer } from "../../src/server"; +import * as authCors from "../../src/server/auth-cors"; +import { createManagementSessionControl, initializeManagementAuthState, issueGuiSession, requireManagementAuth } from "../../src/server/management-auth"; +import type { ManagementContext } from "../../src/server/management/context"; +import { handleSessionRoutes } from "../../src/server/management/session-routes"; +import type { OcxConfig } from "../../src/types"; +import { drainAndRemoveFixtureRoots } from "../helpers/fixture-teardown"; +import { remoteConfig } from "../helpers/management-auth-fixture"; + +const PUBLIC = "https://ocx.example.test"; +const PROXY = "192.0.2.10"; +type Proxy = NonNullable; +const keys = ["OPENCODEX_HOME", "CODEX_HOME", "OPENCODEX_API_AUTH_TOKEN", "OPENCODEX_ADMIN_AUTH_TOKEN"] as const; +let previous: Record; +let home: string; + +beforeEach(() => { + previous = Object.fromEntries(keys.map(key => [key, process.env[key]])); + home = mkdtempSync(join(tmpdir(), "ocx-dashboard-proxy-")); + process.env.OPENCODEX_HOME = home; + process.env.CODEX_HOME = home; + process.env.OPENCODEX_API_AUTH_TOKEN = "ocx_data_fixture"; + process.env.OPENCODEX_ADMIN_AUTH_TOKEN = "ocx_admin_fixture"; +}); +afterEach(async () => { + await drainAndRemoveFixtureRoots({ roots: [{ path: home }], restoreEnvironment: () => { + for (const key of keys) { + if (previous[key] === undefined) delete process.env[key]; + else process.env[key] = previous[key]; + } + } }); +}); + +function withProxy(proxy: Partial | null = {}, base: OcxConfig = remoteConfig()): OcxConfig { + return proxy === null ? base : { ...base, dashboardTrustedProxy: { origin: PUBLIC, proxyAddresses: [PROXY], ...proxy } as Proxy }; +} + +/** A request as the proxy delivers it: plain HTTP to this process, Host kept, browser Origin https. */ +function proxied(path = "/api/session/remember", options: { peer?: string | null; headers?: Record; method?: string } = {}) { + const req = new Request("http://ocx.example.test" + path, { method: options.method ?? "POST", headers: { + Host: "ocx.example.test", Origin: PUBLIC, "User-Agent": "proxy-fixture", "X-OpenCodex-API-Key": "ocx_admin_fixture", + ...options.headers, + } }); + const peer = options.peer === undefined ? PROXY : options.peer; + if (peer !== null) authCors.markDashboardProxyPeer(req, peer); + return req; +} + +function remember(config: OcxConfig, req: Request) { + const state = initializeManagementAuthState(config); + const response = handleSessionRoutes({ req, url: new URL(req.url), config, principal: "admin-token", + sessionControl: createManagementSessionControl(state) } as ManagementContext)!; + return { state, response }; +} + +/** `sameOrigin`: the request does come from the configured origin, and only Remember refuses it. */ +async function expectRefused(config: OcxConfig, req: Request, sameOrigin = false) { + const { response } = remember(config, req); + expect(response.status).toBe(403); + expect((await response.json()).code).toBe("remember_requires_direct_origin"); + expect(response.headers.get("set-cookie")).toBeNull(); + if (!sameOrigin) { + expect(authCors.isAllowedManagementOrigin(req, config) && authCors.managementRequestOrigin(req, config) === PUBLIC).toBe(false); + } +} + +describe("without the setting", () => { + test("a proxied request still cannot remember the device", async () => { + await expectRefused(withProxy(null), proxied()); + }); +}); + +describe("through the configured proxy", () => { + test("Remember issues a Secure host-only device for the configured origin, which resumes and authorizes", async () => { + const config = withProxy(); + const req = proxied(); + expect(authCors.managementRequestOrigin(req, config)).toBe(PUBLIC); + expect(authCors.isAllowedManagementOrigin(req, config)).toBe(true); + const { state, response } = remember(config, req); + expect(response.status).toBe(200); + const cookie = response.headers.get("set-cookie")!; + expect(cookie).toStartWith("__Host-ocx_dashboard_"); + expect(cookie).toContain("Secure"); + expect(cookie).toContain("SameSite=Strict"); + const { device } = await response.json(); + const pair = cookie.split(";")[0]!; + const resumed = issueGuiSession(proxied("/opencodex-session", { method: "GET", + headers: { Cookie: pair, "X-OpenCodex-Device-Proof": device.proof } }), config, initializeManagementAuthState(config)); + expect(resumed?.issuance).toBe("remembered-admin"); + const resumedState = initializeManagementAuthState(config); + const session = issueGuiSession(proxied("/opencodex-session", { method: "GET", + headers: { Cookie: pair, "X-OpenCodex-Device-Proof": device.proof } }), config, resumedState)!; + const read = proxied("/api/config", { method: "GET", headers: { Cookie: pair, "X-OpenCodex-API-Key": session.token, "X-OpenCodex-GUI-Origin": PUBLIC } }); + expect(requireManagementAuth(read, resumedState, config)).toBeNull(); + // The same cookie and proof from a client that is not the proxy resume nothing. + expect(issueGuiSession(proxied("/opencodex-session", { method: "GET", peer: "192.0.2.99", + headers: { Cookie: pair, "X-OpenCodex-Device-Proof": device.proof } }), config, state)).toBeNull(); + }); + + test("a mapped IPv4 peer matches its IPv4 address", () => { + const { response } = remember(withProxy(), proxied("/api/session/remember", { peer: "::ffff:192.0.2.10" })); + expect(response.status).toBe(200); + }); + + test("trusting X-Forwarded-Host reads the browser host from it, never from Host", async () => { + const config = withProxy({ trustHeaders: ["x-forwarded-host"] }); + const upstream = { Host: "pc-a.internal:10100" }; + expect(remember(config, proxied(undefined, { headers: { ...upstream, "X-Forwarded-Host": "ocx.example.test" } })).response.status).toBe(200); + await expectRefused(config, proxied(undefined, { headers: upstream })); + }); + + test("trusting X-Forwarded-Proto requires it to say https", async () => { + const config = withProxy({ trustHeaders: ["x-forwarded-proto"] }); + expect(remember(config, proxied(undefined, { headers: { "X-Forwarded-Proto": "https" } })).response.status).toBe(200); + await expectRefused(config, proxied()); + }); +}); + +describe("refusals", () => { + const cases: Array<[string, Partial | null, Parameters[1]]> = [ + ["a client that is not the proxy, even with matching forwarded headers", {}, + { peer: "192.0.2.99", headers: { "X-Forwarded-Host": "ocx.example.test", "X-Forwarded-Proto": "https" } }], + ["a request with no observed peer", {}, { peer: null }], + ["a forged X-Forwarded-Proto: http", {}, { headers: { "X-Forwarded-Proto": "http" } }], + ["a forged X-Forwarded-Host naming another site", {}, { headers: { "X-Forwarded-Host": "evil.example.test" } }], + ["a chained X-Forwarded-Host", { trustHeaders: ["x-forwarded-host"] }, { headers: { "X-Forwarded-Host": "evil.example.test, ocx.example.test" } }], + ["a chained X-Forwarded-Proto", {}, { headers: { "X-Forwarded-Proto": "http, https" } }], + ["a Host that is not the configured origin", {}, { headers: { Host: "other.example.test" } }], + ["a browser Origin that is not the configured origin", {}, { headers: { Origin: "https://evil.example.test" } }], + ["an http browser Origin for the same host", {}, { headers: { Origin: "http://ocx.example.test" } }], + ["an http origin written straight into the live config", { origin: "http://ocx.example.test" }, {}], + ["a wildcard origin written straight into the live config", { origin: "https://*.example.test" }, {}], + ["an address range written straight into the live config", { proxyAddresses: ["192.0.2.0/24"] }, {}], + ["a wildcard address written straight into the live config", { proxyAddresses: ["*"] }, {}], + ]; + for (const [name, proxy, options] of cases) { + test(name, async () => { await expectRefused(withProxy(proxy), proxied(undefined, options)); }); + } + + test("a cross-site fetch from the configured origin still cannot remember", async () => { + await expectRefused(withProxy(), proxied(undefined, { headers: { "Sec-Fetch-Site": "cross-site" } }), true); + }); + + test("a loopback bind or a non-standalone role never honors the setting", async () => { + await expectRefused(withProxy({}, { ...remoteConfig(), hostname: "127.0.0.1" }), proxied()); + await expectRefused(withProxy({}, { ...remoteConfig(), runtimeRole: "client" }), proxied()); + }); +}); + +describe("configuration", () => { + const invalid: Array<[string, unknown]> = [ + ["http origin", { origin: "http://ocx.example.test", proxyAddresses: [PROXY] }], + ["wildcard origin", { origin: "https://*.example.test", proxyAddresses: [PROXY] }], + ["origin with a path", { origin: "https://ocx.example.test/dash", proxyAddresses: [PROXY] }], + ["no proxy address", { origin: PUBLIC, proxyAddresses: [] }], + ["address range", { origin: PUBLIC, proxyAddresses: ["192.0.2.0/24"] }], + ["wildcard address", { origin: PUBLIC, proxyAddresses: ["*"] }], + ["host name instead of an address", { origin: PUBLIC, proxyAddresses: ["proxy.internal"] }], + ["Host listed as a header", { origin: PUBLIC, proxyAddresses: [PROXY], trustHeaders: ["host"] }], + ["unknown field", { origin: PUBLIC, proxyAddresses: [PROXY], allowAll: true }], + ]; + for (const [name, value] of invalid) { + test(`a live write refuses ${name}`, () => { + const result = validateConfigCandidate({ ...remoteConfig(), dashboardTrustedProxy: value }); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error).toContain("dashboardTrustedProxy"); + }); + } + + test("a malformed hand edit loads with the setting dropped, and a valid one loads intact", () => { + const dropped = configSchema.parse({ ...remoteConfig(), dashboardTrustedProxy: { origin: "http://ocx.example.test", proxyAddresses: [PROXY] } }); + expect((dropped as OcxConfig).dashboardTrustedProxy).toBeUndefined(); + const kept = { origin: PUBLIC, proxyAddresses: [PROXY, "::1"], trustHeaders: ["x-forwarded-proto"] }; + expect(validateConfigCandidate({ ...remoteConfig(), dashboardTrustedProxy: kept }).ok).toBe(true); + expect((configSchema.parse({ ...remoteConfig(), dashboardTrustedProxy: kept }) as OcxConfig).dashboardTrustedProxy).toEqual(kept as Proxy); + }); +}); + +describe("the real listener", () => { + async function rememberThroughListener(proxyAddresses: string[]) { + saveConfig(withProxy({ proxyAddresses })); + const server = startServer(0); + try { + const url = new URL("/api/session/remember", server.url); + const response = await fetch(url, { method: "POST", headers: { Host: "ocx.example.test", Origin: PUBLIC, + "User-Agent": "proxy-fixture", "X-OpenCodex-API-Key": "ocx_admin_fixture" } }); + return { status: response.status, cookie: response.headers.get("set-cookie"), body: await response.json() as { code?: string } }; + } finally { await server.stop(true); } + } + + test("records the connecting peer, so a listed proxy address remembers and an unlisted one is refused", async () => { + const listed = await rememberThroughListener(["127.0.0.1", "::1"]); + expect(listed.status).toBe(200); + expect(listed.cookie).toStartWith("__Host-ocx_dashboard_"); + const unlisted = await rememberThroughListener([PROXY]); + expect(unlisted.status).toBe(403); + expect(unlisted.body.code).toBe("remember_requires_direct_origin"); + }); +}); From fa89e2a00956592bbe23a1eed47d719a4a512595 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 11 Nov 2026 12:42:31 +0900 Subject: [PATCH 2/2] fix(dashboard): refuse an encoded wildcard in the trusted proxy origin The URL parser decodes %2A, so https://%2A.example.test passed the raw wildcard check; the parsed hostname is now checked too. Also moves the live-write check above the ingress doc comment it was inserted under, and documents the forwarded-port and plaintext-vhost cases for operators. --- docs-site/src/content/docs/guides/web-dashboard.md | 4 ++++ src/config/dashboard-trusted-proxy.ts | 2 ++ src/config/diagnostics.ts | 14 +++++++------- .../server/server-dashboard-trusted-proxy.test.ts | 1 + 4 files changed, 14 insertions(+), 7 deletions(-) diff --git a/docs-site/src/content/docs/guides/web-dashboard.md b/docs-site/src/content/docs/guides/web-dashboard.md index 54412349bea..19852999310 100644 --- a/docs-site/src/content/docs/guides/web-dashboard.md +++ b/docs-site/src/content/docs/guides/web-dashboard.md @@ -68,6 +68,10 @@ uses and the addresses the proxy connects from: `X-Forwarded-Host` instead, and `x-forwarded-proto` to also require `X-Forwarded-Proto: https`. - An `X-Forwarded-Host` or `X-Forwarded-Proto` value that contradicts the configured origin, or that lists more than one hop, refuses the request even when that header is not trusted. +- If the origin carries a non-default port and you trust `x-forwarded-host`, the proxy must forward + the port as well (in nginx, `$http_host` rather than `$host`); otherwise the request is refused. +- If the same proxy also answers plain HTTP for this host, trust `x-forwarded-proto` so a plaintext + request is refused instead of being treated as the HTTPS origin. - The setting is honored only on a non-loopback bind, where the admin token is required. A Hub ignores it and uses its management listener instead. diff --git a/src/config/dashboard-trusted-proxy.ts b/src/config/dashboard-trusted-proxy.ts index 57cd397ff6d..95be8cd3171 100644 --- a/src/config/dashboard-trusted-proxy.ts +++ b/src/config/dashboard-trusted-proxy.ts @@ -47,6 +47,8 @@ export function parseDashboardTrustedProxy(value: unknown): DashboardTrustedProx if (typeof origin !== "string" || origin.includes("*")) return "origin must be one exact https origin (no wildcards)"; let parsed: URL; try { parsed = new URL(origin); } catch { return "origin must be one exact https origin (no wildcards)"; } + // The URL parser decodes %2A, so the raw-string check alone would let an encoded wildcard through. + if (parsed.hostname.includes("*")) return "origin must be one exact https origin (no wildcards)"; if (parsed.protocol !== "https:") return "origin must use https"; if (parsed.username || parsed.password || parsed.pathname !== "/" || parsed.search || parsed.hash || !parsed.hostname) { return "origin must be an origin without credentials, path, query, or fragment"; diff --git a/src/config/diagnostics.ts b/src/config/diagnostics.ts index 8cf9f186b02..2e86e7eda51 100644 --- a/src/config/diagnostics.ts +++ b/src/config/diagnostics.ts @@ -627,13 +627,6 @@ export function loopbackCompanionBindError( + "loopback bind already admits local callers without a credential."; } -/** - * Validate the hub management ingress at the live-write boundary. - * - * The persisted schema intentionally degrades a malformed hand edit to disabled so a typo in - * this opt-in listener cannot discard providers or credentials. A live config mutation must not - * get that leniency: it receives an exact field error before the degrading schema is applied. - */ /** #8338: the persisted schema drops a malformed trusted-proxy block; a live write gets the reason. */ function dashboardTrustedProxyConfigError(value: unknown): string | null { const raw = rawConfigRecord(value); @@ -642,6 +635,13 @@ function dashboardTrustedProxyConfigError(value: unknown): string | null { return typeof parsed === "string" ? `schema_invalid: dashboardTrustedProxy: ${parsed}` : null; } +/** + * Validate the hub management ingress at the live-write boundary. + * + * The persisted schema intentionally degrades a malformed hand edit to disabled so a typo in + * this opt-in listener cannot discard providers or credentials. A live config mutation must not + * get that leniency: it receives an exact field error before the degrading schema is applied. + */ function managementIngressConfigError(value: unknown): string | null { const raw = rawConfigRecord(value); if (!raw) return null; diff --git a/tests/server/server-dashboard-trusted-proxy.test.ts b/tests/server/server-dashboard-trusted-proxy.test.ts index b150a803945..2c6914e207d 100644 --- a/tests/server/server-dashboard-trusted-proxy.test.ts +++ b/tests/server/server-dashboard-trusted-proxy.test.ts @@ -163,6 +163,7 @@ describe("configuration", () => { const invalid: Array<[string, unknown]> = [ ["http origin", { origin: "http://ocx.example.test", proxyAddresses: [PROXY] }], ["wildcard origin", { origin: "https://*.example.test", proxyAddresses: [PROXY] }], + ["percent-encoded wildcard origin", { origin: "https://%2A.example.test", proxyAddresses: [PROXY] }], ["origin with a path", { origin: "https://ocx.example.test/dash", proxyAddresses: [PROXY] }], ["no proxy address", { origin: PUBLIC, proxyAddresses: [] }], ["address range", { origin: PUBLIC, proxyAddresses: ["192.0.2.0/24"] }],