Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Serve OpenKnowledge remotely over any tunnel (UI + MCP) (#2902)
omar-inkeepb932885566c1
diff --git a/.changeset/remote-tunnel-v0.md b/.changeset/remote-tunnel-v0.mdnew file mode 100644index 000000000..6cc37a1e1--- /dev/null+++ b/.changeset/remote-tunnel-v0.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": minor+---++Serve your knowledge base's MCP endpoint to your other devices through any HTTPS tunnel — ngrok, Cloudflare Tunnel, Tailscale, or a reverse proxy: run the tunnel against the stable remote port (default 24550, `remote.port` to change) and start the server with `ok start --remote <url>` (or set `remote.url` in `.ok/config.yml` and pass a bare `--remote`). The model is trust-the-tunnel: OpenKnowledge does not authenticate remote callers — anyone who can reach the tunnel URL has full read-write access, and restricting reach is the tunnel's job (private tailnet, ngrok OAuth, Cloudflare Access). The trade is always explicit: remote access is armed only by the `--remote` flag (never by config alone), every remote start prints a warning banner, and a server started without the flag refuses tunneled requests with a fix-it hint instead of serving them. The web UI is served from the same tunnel URL (`/` = editor, `/mcp` = MCP — one port, one tunnel; browse and edit from your phone). Its collaborative surfaces work over the tunnel too: live editing and the Ask AI panel, which runs an agent on the machine hosting the server (using that host's own agent and credentials). Wrong-Host requests (DNS rebinding) are refused everywhere. Local loopback behavior is unchanged.diff --git a/docs/content/deploy/connecting-agents.mdx b/docs/content/deploy/connecting-agents.mdxnew file mode 100644index 000000000..df3fc5289--- /dev/null+++ b/docs/content/deploy/connecting-agents.mdx@@ -0,0 +1,77 @@+---+title: Connecting agents+icon: LuPlug+description: Point every agent (Claude Code, Cursor, Claude Desktop, agent harnesses) at one shared knowledge base.+---+Prerequisite: a running server with [remote access set up](/docs/deploy/remote-access). That page is also where access control lives (the tunnel decides who can reach the URL; the server itself does not authenticate remote callers). To connect someone else's machine, get them access to the tunnel first (e.g. a tailnet invite or an edge-auth allowlist entry), then send them here.++Your knowledge base is one URL: `https://<your-tunnel-url>/mcp`. Every client below connects to that same address, whether the server is your laptop, a Mac mini, or a VPS.++## Connect every agent in one command++[`add-mcp`](https://github.com/neon-solutions/add-mcp) detects which agents are installed on the machine and writes each one's MCP config for you — Claude Code, Cursor, Codex, VS Code, Windsurf, Goose, Zed, and more:++```bash+npx add-mcp https://<your-tunnel-url>/mcp --name ok-remote+```++If your `/mcp` endpoint is behind **Basic Auth** at the tunnel (see [Restrict who can reach it](/docs/deploy/remote-access#4-restrict-who-can-reach-it)), pass the credential as a header so the agent connects with no browser step:++```bash+npx add-mcp https://<your-tunnel-url>/mcp --name ok-remote \+ --header "Authorization: Basic $(printf 'user:pass' | base64)"+```++An **OAuth/SSO**-gated endpoint can't be used this way — a headless agent can't complete a browser login, so gate agent endpoints with Basic Auth, a [path-branched policy](/docs/deploy/remote-access#4-restrict-who-can-reach-it), or Tailscale instead.++## Claude Code++```bash+claude mcp add --transport http ok-remote https://<your-tunnel-url>/mcp+```++## Cursor++```json title="~/.cursor/mcp.json"+{+ "mcpServers": {+ "ok-remote": { "url": "https://<your-tunnel-url>/mcp" }+ }+}+```++## Codex++Recent Codex versions take the URL directly:++```toml title="~/.codex/config.toml"+[mcp_servers.ok-remote]+url = "https://<your-tunnel-url>/mcp"+```++## Claude Desktop++Claude Desktop only takes command-type servers, so it reaches the server through the [`mcp-remote`](https://www.npmjs.com/package/mcp-remote) bridge — a local process that forwards to your `/mcp` URL.++Its config file — `~/Library/Application Support/Claude/claude_desktop_config.json` on macOS, `%APPDATA%\Claude\claude_desktop_config.json` on Windows. In Claude Desktop open **Settings → Developer → Edit Config**, which creates the file and reveals it. Then add:++```json title="claude_desktop_config.json"+{+ "mcpServers": {+ "ok-remote": {+ "command": "npx",+ "args": ["-y", "mcp-remote", "https://<your-tunnel-url>/mcp"]+ }+ }+}+```++## Agent harnesses (OpenClaw, Hermes, etc.)++Add the `/mcp` URL to your harness's MCP server config, the same way as above. Its agents can then read and write your knowledge base.++## Cloud connectors (Claude.ai, ChatGPT, etc.)++Cloud-dialed clients connect from the vendor's cloud, so your tunnel URL must be publicly reachable over HTTPS. The Claude and ChatGPT connectors require OAuth, which OpenKnowledge does not support as a server (for now). Connectors that accept a bearer token or API key instead (Microsoft Copilot Studio, Perplexity, etc.) can use a token you enforce at the tunnel: gate `/mcp` with a static bearer token in your tunnel's edge auth, then paste that same token into the connector's settings, the way an on-device agent presents its credential as a header.++Claude Desktop is not a cloud connector; it uses the `mcp-remote` bridge covered above.diff --git a/docs/content/deploy/meta.json b/docs/content/deploy/meta.jsonnew file mode 100644index 000000000..cdd01cfe1--- /dev/null+++ b/docs/content/deploy/meta.json@@ -0,0 +1,5 @@+{+ "title": "Deploy",+ "icon": "LuServer",+ "pages": ["remote-access", "connecting-agents"]+}diff --git a/docs/content/deploy/remote-access.mdx b/docs/content/deploy/remote-access.mdxnew file mode 100644index 000000000..bcbbe16d3--- /dev/null+++ b/docs/content/deploy/remote-access.mdx@@ -0,0 +1,270 @@+---+title: Remote access+icon: LuGlobe+description: Reach your knowledge base from your other devices.+---+By default, only agents on the same machine as your knowledge base can reach it. Remote access puts that same endpoint behind an HTTPS tunnel (ngrok, Cloudflare Tunnel, Tailscale, or your own reverse proxy) so your other devices can connect to one shared knowledge base.++OpenKnowledge does not authenticate remote callers. Once you pass `--remote`, anyone who can reach your tunnel URL has full read-write control, so restricting who reaches it is up to the tunnel. Put it on a private network like Tailscale, add edge auth like ngrok OAuth or Cloudflare Access, or just keep the URL to yourself. The server ignores tunneled traffic until you start it with `--remote`, so you never expose the base by accident.++## Set up the machine++Remote access runs on the machine that holds your knowledge base. Pick where it lives and get OpenKnowledge running a project there.++### Your laptop or desktop++Your laptop or desktop, where OpenKnowledge is already installed and running your project. Nothing to prepare, so skip ahead to [Turn on remote access](#turn-on-remote-access).++The catch is that it's only reachable while that machine is awake. Close the lid and your agents lose access. For around-the-clock access, use a dedicated server instead.++### A dedicated server++A VPS, Mac mini, or any computer you can leave running. It keeps your knowledge base reachable around the clock, so agents never lose access. Set it up first.++<Callout>+**On a VPS:** providers like Hetzner, DigitalOcean, and Lightsail all work. Pick Ubuntu 24.04 (1 GB RAM is comfortable; 512 MB runs a small knowledge base), add your SSH key at creation, and `ssh root@<ip>` in. Every step below happens in that shell.+</Callout>++Install OpenKnowledge (and Node 24 first, on a fresh box):++```bash+curl -fsSL https://deb.nodesource.com/setup_24.x | sudo bash - && sudo apt-get install -y nodejs git+npm install -g @inkeep/open-knowledge+```++Create the project (`ok init` sets up git for you):++```bash+mkdir ~/knowledge && cd ~/knowledge && ok init+```++To start from existing notes, `git clone` them as the project directory instead of `mkdir`, then run `ok init` inside.++## Turn on remote access++Run these on the machine you set up.++### 1. Open a tunnel++Any HTTPS tunnel works. It forwards a public URL to the server's local port, `24550` by default (change it with `remote.port` in `.ok/config.yml`; see the [Configuration reference](/docs/reference/configuration)). Point your tunnel at that same port. Pick one:++<Callout type="info">+Install your tunnel's client on the machine first if it isn't already.+</Callout>++<Tabs groupId="ok-tunnel" persist items={['Tailscale', 'ngrok', 'Cloudflare Tunnel']}>++<Tab>++Private, only devices on your tailnet can reach it. Requires [HTTPS enabled in your tailnet](https://tailscale.com/kb/1153/enabling-https).++```bash+tailscale serve --bg 24550+# → https://<machine>.<tailnet>.ts.net+```++</Tab>++<Tab>++Public URL; add edge auth to restrict (see [Restrict who can reach it](#4-restrict-who-can-reach-it)).++```bash+ngrok http 24550+# → https://<something>.ngrok.app+```++</Tab>++<Tab>++Public URL on your own domain; pair with Cloudflare Access to restrict (see [Restrict who can reach it](#4-restrict-who-can-reach-it)).++```bash+cloudflared tunnel --url http://localhost:24550+```++</Tab>++</Tabs>++Each one gives you a public HTTPS URL. That URL is your `remote.url`.++### 2. Start the server with `--remote`++From the project directory:++```bash+ok start --remote https://<your-tunnel-url>+```++Or persist the URL in `.ok/config.yml` and start with a bare flag:++```yaml title=".ok/config.yml"+remote:+ url: https://<your-tunnel-url>+```++```bash+ok start --remote+```++The flag is required every start. A `remote.url` sitting in config never turns remote access on by itself, and the server prints a warning banner on every remote start so the exposure is never silent. Without `--remote`, tunneled requests are refused with a hint rather than served.++<Callout>+Remote access is a command-line feature (`ok start --remote`), not a desktop toggle. To see what you're exposing, open the tunnel URL in a browser; the desktop app only connects to its own local server. The desktop app and `ok start` also can't run against the same project at once.+</Callout>++On a **dedicated server**, run it as a service instead, so it survives logout and reboots:++```ini title="/etc/systemd/system/openknowledge.service"+[Unit]+Description=OpenKnowledge server+After=network-online.target++[Service]+User=root+WorkingDirectory=/root/knowledge+ExecStart=/usr/bin/env ok start --remote+Restart=on-failure++[Install]+WantedBy=multi-user.target+```++This matches the `ssh root@<ip>` VPS setup above (project at `/root/knowledge`, `remote.url` set in config). If you log in as a different user, set `User` and `WorkingDirectory` to that user and their project path.++```bash+sudo systemctl enable --now openknowledge+```++<Callout>+**On macOS**, there's no systemd. Run `ok start --remote` in a terminal, and set the machine not to sleep (System Settings → Energy) for always-on use.+</Callout>++### 3. Verify++From any device that can reach the tunnel, do a real handshake:++```bash+curl -sS -X POST https://<your-tunnel-url>/mcp \+ -H 'content-type: application/json' \+ -H 'accept: application/json, text/event-stream' \+ -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl","version":"0"}}}'+```++Your knowledge base introduces itself:++```json+{"result":{"protocolVersion":"2025-06-18","capabilities":{"tools":{"listChanged":true}},"serverInfo":{"name":"open-knowledge","version":"…"}},"jsonrpc":"2.0","id":1}+```++That's the whole path working. You now have an MCP URL for your knowledge base:++```+https://<your-tunnel-url>/mcp+```++### 4. Restrict who can reach it++The server admits whoever the tunnel lets through, so we recommend adding access control at the tunnel:++- **Tailscale `serve`** is restricted by construction: only devices on your tailnet can connect. Use [tailnet ACLs](https://tailscale.com/kb/1018/acls) to narrow it further. (`tailscale funnel` makes the URL public — treat it like any public tunnel.)+- **ngrok** can require a login at the edge before any request reaches you. Use **OAuth** (or **OIDC/SSO** — `--oidc`, for Okta / Azure AD / Google Workspace):++ ```bash+ ngrok http 24550 --oauth google --oauth-allow-email [email protected]+ ```++- **Cloudflare Tunnel** pairs with [Cloudflare Access](https://developers.cloudflare.com/cloudflare-one/policies/access/) — a login policy on the hostname, checked at Cloudflare's edge.++A public tunnel URL with no edge auth is a capable but *open* knowledge base: fine for a deliberate share, wrong as a default. The URL itself is the only secret, and URLs leak.++<Callout type="warn">+**For the web UI, use login-based edge auth (OAuth or SSO), not HTTP Basic Auth.** Live editing needs a WebSocket, and browsers can't send Basic Auth over one, so a Basic Auth gate leaves the editor stuck loading. A login sets a cookie, which does work. (Basic Auth is fine for agent-only access.)+</Callout>++<Callout type="info" title="Serving the UI and headless agents from one gated tunnel">+The UI and a headless MCP agent need *opposite* auth: the browser needs a login (cookie), a headless agent needs a credential it can send with no browser. A single OAuth gate can't do both — an agent hitting an OAuth-gated `/mcp` just gets the login HTML. **ngrok** resolves it with a path-branched traffic policy — OAuth on the UI, Basic Auth on `/mcp`:++```yaml title="policy.yaml"+on_http_request:+ - expressions: ["req.url.path.startsWith('/mcp')"]+ actions:+ - type: basic-auth+ config: { credentials: ["agent:CHANGE_ME"] }+ - expressions: ["!req.url.path.startsWith('/mcp')"]+ actions:+ - type: oauth+ config: { provider: google }+```++Run with `--traffic-policy-file policy.yaml`. The agent then connects headlessly by presenting the Basic credential as a header (see [Connecting agents](/docs/deploy/connecting-agents)). **Cloudflare Access** can express the same split (a path-scoped login policy for the UI plus a service token for `/mcp`), but that recipe is not documented here. **Tailscale** sidesteps the whole thing — its network-layer auth covers UI and agents at once.+</Callout>++## Share your knowledge base++Now that it's reachable, there are two ways in: a browser for people, and the MCP endpoint for agents.++### In a browser++The same tunnel URL serves the web UI:++```+https://<your-tunnel-url>/+```++Open it in any browser that can reach the tunnel to browse and edit+the knowledge base. The UI and the MCP endpoint share the one URL (`/` is the editor,+`/mcp` is for agents); there is no separate `ok ui` port in remote mode.++Editing is live: changes sync in real time between every connected browser and agent.+A few behaviors to know:++- **Every remote browser acts as the server's owner.** Same identity, full access.+- **The Ask AI panel runs on the server.** Each conversation spawns an agent on the+ machine hosting `ok start`, using that machine's installed agent and credentials (not+ anything on your device), and its edits sync back like any agent's. Install and sign in+ to an agent on the host for Ask AI to work over the tunnel.++Anyone you share the URL with can open it and edit alongside you, all as the same owner, since there are no per-person accounts. Share it deliberately and only with people you trust.++### With agents++Point any MCP client at your endpoint:++```+https://<your-tunnel-url>/mcp+```++See [Connecting agents](/docs/deploy/connecting-agents) for per-client setup (Claude, Cursor, Codex, and others), including how a headless agent passes edge-auth credentials.++Anyone who can reach this URL has full read-write access.++## Back up to a git remote++Optional, but recommended for a server. Your knowledge base is a plain git repository, and OpenKnowledge has a built-in sync engine: point it at a GitHub remote and it commits and pushes as agents write, on its own.++Create an empty **private** GitHub repo, then on the machine:++```bash+gh auth login # authorize this machine (or add a deploy key with write access)+cd ~/knowledge+git remote add origin https://github.com/you/knowledge.git+git branch -M main && git add -A && git commit -m "knowledge base" && git push -u origin main+```++Turn on auto-sync:++```bash+printf 'autoSync:\n enabled: true\n' > .ok/local/config.yml+sudo systemctl restart openknowledge+```++From now on every edit is committed and pushed automatically. The commit author comes from the machine's git identity (`git config user.name` / `user.email`). A fresh server has none set, so commits fall back to a service identity, **OpenKnowledge**. Signing in with `gh` handles pushing, not authorship. Set a git identity if you'd rather commits carry your name. See [GitHub sync](/docs/features/github-sync) for sync modes, conflict handling, and authentication.++The git remote is also a way to edit locally: `git clone` it on your laptop and open the clone in OK Desktop. That gives you a separate local copy with the full editor. It syncs with the server through git (each side pushes and pulls), not live, so changes cross over on the next sync rather than instantly.++## Turning it off++Stop the tunnel, or restart the server without `--remote` — either one closes remote access (without the flag, the server refuses tunneled requests outright). If the URL may have leaked further than intended, rotate it at the tunnel (ngrok and Cloudflare mint a fresh URL on restart; on Tailscale, tighten the ACL).diff --git a/docs/content/features/share.mdx b/docs/content/features/share.mdxindex 404f0b5c8..5c1ac8195 100644--- a/docs/content/features/share.mdx+++ b/docs/content/features/share.mdx@@ -6,6 +6,8 @@ description: Copy a link to any doc or folder and send it to a teammate. OpenKnoOpenKnowledge has a Share button in the editor toolbar. Click it and the app copies a `https://openknowledge.ai/d/…` URL to your clipboard. Anyone you send it to lands on a splash page that knows the project and target, and a single click opens it in their copy of OpenKnowledge.+Share links give each recipient their own copy, kept in sync through GitHub. For real-time editing where everyone works on one live server instead, see [Remote access](/docs/deploy/remote-access).+## Sending a share linkClick the Share button to copy a deep link to the current doc or folder to your clipboard. The sharing functionality is backed by GitHub and requires that your project has a remote origin.diff --git a/docs/content/get-started/overview.mdx b/docs/content/get-started/overview.mdxindex 8b8d4eadb..7eb271cb7 100644--- a/docs/content/get-started/overview.mdx+++ b/docs/content/get-started/overview.mdx@@ -20,6 +20,7 @@ OpenKnowledge is three layers working together: a "WYSIWYG" editor for you, MCP## Additional Features- "Ask AI" experience for opening your knowledge base in your favorite agent- No-code **team sharing** and **Auto-sync** powered by git/GitHub under the hood.+- **Remote access** to your knowledge base from your other devices and agents, over any tunnel. See [Remote access](/docs/deploy/remote-access).- A **built-in TUI** in the desktop app for Claude, Codex, OpenCode, and Cursor- Graph and wiki link visualizations- **Embeddable HTML** for writing engineering specs and visualized reports.diff --git a/docs/content/meta.json b/docs/content/meta.jsonindex c6e8399f0..cb3716de1 100644--- a/docs/content/meta.json+++ b/docs/content/meta.json@@ -11,6 +11,8 @@"...integrations","---FEATURES---","...features",+ "---DEPLOY---",+ "...deploy","---ADVANCED---","...advanced","---IMPORT & TRY---",diff --git a/docs/content/reference/cli.mdx b/docs/content/reference/cli.mdxindex 14eb71ff1..5ceb5468b 100644--- a/docs/content/reference/cli.mdx+++ b/docs/content/reference/cli.mdx@@ -108,6 +108,14 @@ Each project runs its own local server. These commands let you see and stop them| `ok stop` | Stop the server for the current directory — or pass a port, path, or PID to stop a specific server, or `all` to stop every server || `ok clean` | Remove stale lock files left behind by a crash (never touches live servers) |+## Remote access++Serve this project's web UI and `/mcp` endpoint to your other devices through any HTTPS tunnel, both on one URL. Full setup (and the access-control model) in [Remote access](/docs/deploy/remote-access); point agents at the URL with [Connecting agents](/docs/deploy/connecting-agents).++| Command | What it does |+| --- | --- |+| `ok start --remote [url]` | Start the server admitting requests from the tunnel URL (no server-side auth; restrict reach at the tunnel). Bare `--remote` uses `remote.url` from `.ok/config.yml` |+## More commands| Command | What it does |diff --git a/docs/content/reference/configuration.mdx b/docs/content/reference/configuration.mdxindex ee97c8a1a..863693c0f 100644--- a/docs/content/reference/configuration.mdx+++ b/docs/content/reference/configuration.mdx@@ -41,6 +41,8 @@ A key set in a file more specific than its scope (a user-scope key in `.ok/confi| `autoSync.mode` | `"off" \| "follow" \| "full" \| null` | `null` | project-local | Per-machine sync mode for this project: `off` (no sync), `follow` (one-directional — pull remote changes, never push your own; the earlier value `pull` is accepted as an alias), `full` (bidirectional pull and push). `null` means "unanswered"; the editor's onboarding modal triggers on first remote-detected open. Supersedes `autoSync.enabled`. || `autoSync.enabled` | `boolean \| null` | `null` | project-local | Legacy per-machine auto-sync toggle, superseded by `autoSync.mode`. Read only when `mode` is absent (`true` = full, `false` = off). `null` means "unanswered". || `autoSync.default` | `"off" \| "follow" \| "full" \| boolean \| null` | `null` | project | Committed seed for each machine's first-open sync mode: `off` / `follow` / `full`, or the legacy boolean (`true` = full, `false` = off). `null` = ask. Lets a maintainer pre-answer the onboarding prompt for everyone who clones; a per-machine `autoSync.mode` overrides it. Compatibility note: a committed string value (`off` / `follow` / `full`) is rejected by app versions released before `autoSync.mode` existed, resetting that machine to config defaults until it updates (it never silently syncs). The legacy boolean seed (`true` / `false`) stays readable by older apps — commit `follow` only once collaborators are on a current version. |+| `remote.url` | string | (unset) | project | Public tunnel URL remote clients connect to (e.g. `https://myproject.ngrok.app`); its host is admitted through the Host-header allowlist. Used only when the server is started with `ok start --remote` (config alone never enables remote access, and there is no server-side auth). See [Remote access](/docs/deploy/remote-access). |+| `remote.port` | number | `24550` | project | Fixed TCP port the server binds when remote access is enabled, so the tunnel's port mapping survives restarts. See [Remote access](/docs/deploy/remote-access). || `editor.wordWrap` | boolean | `true` | user | Soft-wrap long lines in the source-mode CodeMirror editor. A personal preference, not project-shared. Toggle from the Settings pane. || `appearance.preview.autoOpen` | boolean | `true` | user | Whether the agent should open or refresh the OpenKnowledge preview when it edits a doc through the MCP. Default `true` lets the agent route the preview by host capability: the host's in-app browser (Cursor preview pane, Codex's built-in browser, Claude Code Desktop) when one exists, the system browser otherwise. Set `false` to keep the agent's hands off your preview window. This is useful when you're already viewing the doc in OK Desktop, a browser tab on a second display, a non-default browser, or any flow where your extensions / accessibility tooling only work in your own browser. The agent then surfaces the URL on request but does not navigate. The change takes effect on the next preview-related tool call. Toggle from **Settings → Preferences → "Open preview when agent edits"**. || `terminal.enabled` | `boolean \| null` | `null` | project-local | Opt-out for the in-app terminal (a real OS shell at full user privilege). On by default; set `false` to disable it for this project on this machine. |diff --git a/docs/content/reference/mcp.mdx b/docs/content/reference/mcp.mdxindex b7b165ad6..9367879b2 100644--- a/docs/content/reference/mcp.mdx+++ b/docs/content/reference/mcp.mdx@@ -10,6 +10,8 @@ Every other read tool (`search`, `links`, `history`, etc.) and all write tools rThe surface is **21 tools**. The four write verbs — `write`, `edit`, `delete`, `move` — are native CRUD operations polymorphic over a target. `write`, `edit`, and `delete` nest per-target fields inside the address key (`write({ document: { path, content } })`) and take exactly one target per call: `document`, `folder`, `template`, or `skill` — plus `asset` for `write` and `delete`, and a `documents` batch on `write` that writes several docs in order, each entry carrying its own `summary`. `move` takes flat `from`/`to` paths and auto-detects a document, folder, or asset, with nested `template` and `skill` targets for those two.+To point an MCP client at this server, locally or over a tunnel from another machine, see [Connecting agents](/docs/deploy/connecting-agents).+## Tools| Tool | Purpose |diff --git a/packages/cli/src/commands/start.test.ts b/packages/cli/src/commands/start.test.tsindex 28ae6961e..d2570a102 100644--- a/packages/cli/src/commands/start.test.ts+++ b/packages/cli/src/commands/start.test.ts@@ -13,6 +13,7 @@ import {type BootedStartServer,bootStartServer,buildIdleShutdownHandler,+ coerceRemoteBindHost,computeConnectExitCode,connectUiSibling,decideUiSpawn,@@ -56,6 +57,33 @@ describe('resolveHost', () => {});});+describe('coerceRemoteBindHost', () => {+ test('no-op when remote access is disabled', () => {+ expect(coerceRemoteBindHost('::1', false)).toEqual({ host: '::1', coerced: false });+ expect(coerceRemoteBindHost('localhost', false)).toEqual({+ host: 'localhost',+ coerced: false,+ });+ });++ test('coerces IPv6/hostname binds to 127.0.0.1 in remote mode (tunnel proxy target)', () => {+ for (const host of ['::', '::1', '[::1]', 'localhost']) {+ expect(coerceRemoteBindHost(host, true)).toEqual({ host: '127.0.0.1', coerced: true });+ }+ });++ test('leaves loopback binds alone in remote mode', () => {+ expect(coerceRemoteBindHost('127.0.0.1', true)).toEqual({+ host: '127.0.0.1',+ coerced: false,+ });+ });++ test('coerces all-interfaces binds to loopback in remote mode', () => {+ expect(coerceRemoteBindHost('0.0.0.0', true)).toEqual({ host: '127.0.0.1', coerced: true });+ });+});+describe('formatShutdownNotice', () => {test('SIGINT includes the headline, the wait notice, and the force-quit hint', () => {const lines = formatShutdownNotice('SIGINT');@@ -615,6 +643,15 @@ describe('resolveCollabPort (collab vs UI-sibling port suppression)', () => {test('nothing set → undefined (kernel-allocated)', () => {expect(resolveCollabPort(undefined, undefined, undefined)).toBeUndefined();});+ test('with remote enabled, platform-injected env PORT is suppressed (tunnel targets remote.port)', () => {+ expect(resolveCollabPort(undefined, 6000, undefined, true)).toBeUndefined();+ });+ test('with remote enabled, explicit --port still wins (deliberate override)', () => {+ expect(resolveCollabPort(5000, 6000, undefined, true)).toBe(5000);+ });+ test('with remote enabled and nothing else set → undefined (caller falls back to remote.port)', () => {+ expect(resolveCollabPort(undefined, undefined, undefined, true)).toBeUndefined();+ });});describe('shouldConnectToExistingServer (main-checkout connect guard)', () => {diff --git a/packages/cli/src/commands/start.ts b/packages/cli/src/commands/start.tsindex 0693c29f2..14802834e 100644--- a/packages/cli/src/commands/start.ts+++ b/packages/cli/src/commands/start.ts@@ -23,7 +23,7 @@ import {import { closeSync, existsSync as fsExistsSync, mkdirSync as fsMkdirSync, openSync } from 'node:fs';import { rm } from 'node:fs/promises';import type { Server as HttpServer } from 'node:http';-import { basename, join } from 'node:path';+import { basename, join, resolve as pathResolve } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';import {DEFAULT_SERVER_HOST,@@ -67,6 +67,35 @@ export function resolveHost(return opts.host ?? env.HOST ?? DEFAULT_SERVER_HOST;}+/**+ * Bind-family guard for remote mode. Tunnel agents (ngrok, cloudflared,+ * tailscaled, …) proxy to an IPv4 loopback target (`127.0.0.1:<port>`), so an+ * IPv6-only bind (`::`, `::1`, or `localhost` resolving to `::1` first)+ * leaves the tunnel dialing a port nobody answers on — hit in practice during+ * the MVP. When remote access is enabled and the resolved host is one of+ * those shapes, coerce to `127.0.0.1` and tell the operator. Pure — returns+ * the corrected host and whether a coercion happened; caller logs.+ */+export function coerceRemoteBindHost(+ host: string,+ remoteEnabled: boolean,+): { host: string; coerced: boolean } {+ if (!remoteEnabled) return { host, coerced: false };+ if (+ host === '::' ||+ host === '::1' ||+ host === '[::1]' ||+ host === 'localhost' ||+ // 0.0.0.0 binds every interface; in remote mode the tunnel agent only+ // needs loopback, and an all-interfaces bind would let a LAN peer reach+ // the admitted surface directly, bypassing the tunnel's edge auth.+ host === '0.0.0.0'+ ) {+ return { host: '127.0.0.1', coerced: true };+ }+ return { host, coerced: false };+}+/** Hard cap on the project-name suffix in `process.title` to keep `ps`/Activity Monitor lines readable. */const PROCESS_TITLE_PROJECT_NAME_MAX = 64;@@ -201,19 +230,23 @@ export function spawnOkUi(opts: SpawnOkUiOptions): ChildProcess {/*** Resolve the collab server's port from the three sources, for `runStartCommand`.- * An explicit `--port` always wins. Otherwise, when `--ui-port` is set (the- * worktree-preview recipe) the env `PORT` is the UI sibling's intended port, NOT- * the collab server's — drop it so the brain kernel-allocates and the two can't- * contend. Without `--ui-port`, env `PORT` flows through as before. Pure so the- * suppression rule (the thing that prevents brain/UI port contention) is tested+ * An explicit `--port` always wins. Otherwise env `PORT` is dropped in two+ * cases: when `--ui-port` is set (the worktree-preview recipe) it is the UI+ * sibling's intended port, NOT the collab server's — drop it so the brain+ * kernel-allocates and the two can't contend; and when remote access is+ * enabled, because PaaS platforms (Railway, Fly, Render) inject `PORT` for+ * their own edge proxy — honoring it would silently move the server off the+ * stable `remote.port` the tunnel's port mapping targets, leaving the+ * tunnel dialing a dead port. Pure so both suppression rules are tested* directly.*/export function resolveCollabPort(portFromCli: number | undefined,portFromEnv: number | undefined,requestedUiPort: number | undefined,+ remoteEnabled = false,): number | undefined {- return portFromCli ?? (requestedUiPort !== undefined ? undefined : portFromEnv);+ return portFromCli ?? (requestedUiPort !== undefined || remoteEnabled ? undefined : portFromEnv);}/**@@ -756,6 +789,11 @@ interface BootStartServerOptions {* synthesized `.ok/config.yml`. Defaults to `cwd`.*/projectDir?: string;+ /**+ * Explicit remote-access opt-in (from `ok start --remote`). See+ * `BootServerOptions.enableRemote` — config alone never arms remote access.+ */+ enableRemote?: boolean;}export interface BootedStartServer {@@ -1035,6 +1073,7 @@ export async function bootStartServer(opts: BootStartServerOptions): Promise<BoocontentRoot: ephemeral ? undefined : config.content.dir,port: opts.port,host,+ ...(opts.enableRemote === true ? { enableRemote: true } : {}),quiet: false,detectGh,tokenStore,@@ -1177,6 +1216,13 @@ interface StartCommandOptions {/** From `--project-dir <dir>`. See `BootStartServerOptions.projectDir` — the* throwaway temp project root for the ephemeral single-file shape. */projectDir?: string;+ /**+ * From `--remote [url]`: explicit remote-access opt-in. `true` when the flag+ * is bare (url comes from `remote.url` in config); a string when the url is+ * supplied inline (used for this run, not persisted). Absent → loopback-only,+ * regardless of any `remote.url` in config.+ */+ remote?: string | boolean;}/**@@ -1265,7 +1311,16 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)const { accent, dim, error, warning } = await import('../ui/colors.ts');const cwd = process.cwd();- const activeConfig = config;+ // Remote access is an explicit `--remote [url]` opt-in. A `remote.url` left+ // in `.ok/config.yml` does NOT arm it by itself — the flag decides; the+ // config url fills in when the flag is bare, and a flag-supplied url wins+ // for this run without persisting.+ const remoteEnabled = opts.remote !== undefined && opts.remote !== false;+ const remoteUrlOverride = typeof opts.remote === 'string' ? opts.remote : undefined;+ const activeConfig: Config =+ remoteUrlOverride !== undefined+ ? { ...config, remote: { ...config.remote, url: remoteUrlOverride } }+ : config;// Set the process title as early as possible so Activity Monitor and// `ps -ax | grep open-knowledge-server` show each running server by@@ -1274,10 +1329,52 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)// action; the OS process list is the discovery path.process.title = deriveServerProcessTitle(cwd);+ // Fail loud BEFORE booting: --remote with no url anywhere is unusable, and+ // the error message is the fix instruction.+ if (+ remoteEnabled &&+ (typeof activeConfig.remote?.url !== 'string' || activeConfig.remote.url === '')+ ) {+ console.error(+ error(+ '--remote requires a public tunnel URL — pass it (`ok start --remote https://<your-tunnel-host>`) or set remote.url in .ok/config.yml.',+ ),+ );+ process.exit(78);+ }++ // The trust-the-tunnel warning. Deliberately unmissable: with --remote there+ // is NO server-side authentication — access control is entirely the+ // tunnel's job (edge auth), and every admitted caller has the full owner+ // surface. Printed on every remote start so the trade is never implicit.+ if (remoteEnabled) {+ console.warn(+ warning(+ [+ '',+ '⚠ REMOTE ACCESS ENABLED — no server-side authentication.',+ ` Anyone who can reach ${activeConfig.remote?.url} has FULL control of this`,+ ' knowledge base, including sync, publishing, credentials, and local operations.',+ ' Restrict who can reach it at the tunnel: ngrok OAuth, Cloudflare Access,',+ ' Tailscale ACLs, or equivalent edge auth.',+ '',+ ].join('\n'),+ ),+ );+ }+// Source-of-truth host + port resolution: CLI flag > env > application- // default. Both live as runtime knobs only — neither is a schema field- // (non-user-configurable either-scope fields are excluded from config).- const host = resolveHost(opts, process.env as { HOST?: string | undefined });+ // default. Host lives as a runtime knob only; the port additionally falls+ // back to `remote.port` when remote access is enabled (a stable tunnel+ // target is part of the remote contract — see coerceRemoteBindHost).+ const resolvedHost = resolveHost(opts, process.env as { HOST?: string | undefined });+ const hostCoercion = coerceRemoteBindHost(resolvedHost, remoteEnabled);+ if (hostCoercion.coerced) {+ console.warn(+ `remote access is enabled and ${resolvedHost} is not an IPv4 loopback bind — tunnels proxy to 127.0.0.1, so binding ${resolvedHost} would leave the tunnel dialing a dead port. Using 127.0.0.1.`,+ );+ }+ const host = hostCoercion.host;const portFromCli = opts.port !== undefined ? Number(opts.port) : undefined;const portFromEnv = process.env.PORT ? Number(process.env.PORT) : undefined;const requestedUiPort = opts.uiPort !== undefined ? Number(opts.uiPort) : undefined;@@ -1287,7 +1384,19 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)// env `PORT` for the collab in that case so the brain kernel-allocates; an// explicit `--port` still wins if the caller really wants a fixed collab// port. (Defense-in-depth: the recipe shell chain also unsets `PORT`.)- const port = resolveCollabPort(portFromCli, portFromEnv, requestedUiPort);+ // An explicit --port still wins everywhere; in remote mode the config port+ // fills the default slot and env PORT is suppressed (see resolveCollabPort).+ // A stable port matters in remote mode because the tailscale serve/funnel+ // mapping names a fixed target port — a kernel-assigned ephemeral port would+ // break the tunnel on every restart.+ if (remoteEnabled && portFromCli === undefined && portFromEnv !== undefined) {+ console.warn(+ `remote access is enabled — ignoring env PORT=${process.env.PORT}; the tunnel's port mapping targets the stable remote port (${activeConfig.remote?.port}). Pass --port to override deliberately.`,+ );+ }+ const port =+ resolveCollabPort(portFromCli, portFromEnv, requestedUiPort, remoteEnabled) ??+ (remoteEnabled ? activeConfig.remote?.port : undefined);// Fast path: when `--ui-port` is set (the worktree-preview recipe), a// live collab server already in this folder means we must NOT boot a second@@ -1306,6 +1415,27 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)}}+ // Remote mode serves the SPA from the same remote port (`/` = UI, `/mcp` =+ // MCP) so one tunnel covers both. Resolve the bundled shell the way `ok ui`+ // does; an explicit --react-shell-dist-dir still wins. Missing shell (rare:+ // source checkout without an app build) degrades to MCP/API-only with a+ // warning rather than failing the start. Passing reactShellDistDir also+ // suppresses the `ok ui` sibling spawn — one UI, one port, in remote mode.+ let reactShellDistDir = opts.reactShellDistDir;+ if (remoteEnabled && reactShellDistDir === undefined) {+ const cliDir = import.meta.dirname ?? new URL('.', import.meta.url).pathname;+ reactShellDistDir = [+ pathResolve(cliDir, 'public'), // npm install: dist/public/ (bundled)+ pathResolve(cliDir, '../../app/dist'), // monorepo dev from src/+ pathResolve(cliDir, '../../../app/dist'), // monorepo dev from dist/+ ].find((p) => fsExistsSync(p));+ if (reactShellDistDir === undefined) {+ console.warn(+ 'remote access: bundled web UI not found — serving /mcp and /api only over the tunnel.',+ );+ }+ }+let booted: BootedStartServer;try {booted = await bootStartServer({@@ -1317,9 +1447,10 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)...(opts.serveContentAssets !== undefined? { serveContentAssets: opts.serveContentAssets }: {}),- ...(opts.reactShellDistDir ? { reactShellDistDir: opts.reactShellDistDir } : {}),+ ...(reactShellDistDir ? { reactShellDistDir } : {}),...(opts.singleFile ? { singleFile: opts.singleFile } : {}),...(opts.projectDir ? { projectDir: opts.projectDir } : {}),+ ...(remoteEnabled ? { enableRemote: true } : {}),});} catch (err) {// Project not initialized — clean message, no stack trace.@@ -1340,6 +1471,13 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)process.exit(78);}+ // Unusable `remote:` config block (--remote without a url, a plain-http+ // url, …) — the error message is the fix instruction. EX_CONFIG.+ if (err instanceof serverModule.RemoteConfigError) {+ console.error(error(err.message));+ process.exit(78);+ }+// Single-file open target was rejected (missing / not a file / not// markdown). The thrown error carries a user-facing one-liner — surface it// cleanly instead of a stack trace, matching `ok <file>`'s own handling.@@ -1571,6 +1709,10 @@ export function startCommand(getConfig: () => Config): Command {'--project-dir <dir>','Throwaway project root for --single-file (where ephemeral .ok/ state lives)',)+ .option(+ '--remote [url]',+ 'Serve through a tunnel: admit requests carrying the tunnel Host with NO server-side auth (anyone who can reach the URL has full control — restrict access at the tunnel with edge auth). Bare --remote uses remote.url from .ok/config.yml; --remote <url> supplies it for this run.',+ ).action(async (opts: StartCommandOptions) => {const config = getConfig();diff --git a/packages/core/src/config/field-registry.test.ts b/packages/core/src/config/field-registry.test.tsindex 9e66027d5..fa365a0ce 100644--- a/packages/core/src/config/field-registry.test.ts+++ b/packages/core/src/config/field-registry.test.ts@@ -203,6 +203,11 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)'.filter((l) => getFieldMeta(l.schema)?.scope === 'project').map((l) => l.path.join('.')).sort();+ // `remote.*` is the project's remote-access posture — the tunnel URL the+ // Host allowlist admits (armed only by `ok start --remote`) and the stable+ // port the tunnel targets. Project scope (committed) and never+ // agent-settable: an agent setting these would be widening its own+ // network exposure.expect(projectStrict).toEqual(['autoSync.default','bridge.backgroundThrottle.enabled',@@ -218,6 +223,8 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)''contentRules.markdownlint.enabled','lossCapture.enabled','lossCapture.maxBytes',+ 'remote.port',+ 'remote.url','telemetry.localSink.attributeDenylist','telemetry.localSink.enabled','telemetry.localSink.logs.maxBytes',diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.tsindex d07ddc120..432d8781c 100644--- a/packages/core/src/config/schema.ts+++ b/packages/core/src/config/schema.ts@@ -974,6 +974,39 @@ export const ConfigSchema = z.looseObject({.default(true),}).default({ enabled: true }),+ // Remote access through any HTTPS tunnel. Config alone never enables it —+ // the `ok start --remote` flag does. Trust-the-tunnel: no server-side auth+ // and no access-level knob; restricting reach is the tunnel's job.+ // `agentSettable: false` everywhere so an agent can't self-expose the box.+ remote: z+ .looseObject({+ url: z+ .string()+ .register(fieldRegistry, {+ scope: 'project',+ agentSettable: false,+ defaultScope: 'project',+ description:+ 'Public URL your tunnel gives you, e.g. https://myproject.ngrok.app. Used only with `ok start --remote` (config alone never enables remote access); its host is admitted through the Host-header allowlist. There is no server-side auth, so restrict access at the tunnel (ngrok OAuth, Cloudflare Access, Tailscale ACLs).',+ })+ .optional(),+ port: z+ .number()+ .int()+ .min(1)+ .max(65535)+ .register(fieldRegistry, {+ scope: 'project',+ agentSettable: false,+ defaultScope: 'project',+ description:+ "TCP port the server binds when remote access is enabled (default 24550). Fixed so the tunnel's port mapping survives restarts. Set it only on a conflict. An explicit --port still wins; the PORT env var is ignored in remote mode.",+ })+ .default(24550),+ })+ .default({+ port: 24550,+ }),});export type Config = z.infer<typeof ConfigSchema>;diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 458262f76..dd66dc1a8 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -309,6 +309,7 @@ import { type NormalizedSummary, normalizeSummary } from './agent-write-summary.import { isAllowedApiOrigin } from './api-origin.ts';import { collectReferencedAssets, toContentRelativePath } from './asset-references.ts';import { assetContentTypeForPath } from './asset-serve-middleware.ts';+import { collabUrlFromRequestHeaders } from './collab-bootstrap-url.ts';import { getLocalDir } from './config/paths.ts';import { CONFIG_VALIDATION_REVERT_ORIGIN } from './config-edit-origin.ts';import { DocInConflictError, isDocInConflict, respondDocInConflict } from './conflict-errors.ts';@@ -583,7 +584,7 @@ import { buildLinkPreviewMetadata, type GuardedFetch } from './link-preview/metaimport { LinkPreviewCache, type LinkPreviewOutcome } from './link-preview/preview-cache.ts';import { classifyLinkPreviewRequest } from './link-preview/request-gate.ts';import {- checkLocalOpSecurity,+ checkLocalOpSecurity as checkLocalOpSecurityBase,createConcurrencyGuard,expandTilde,isAllowedGitUrl,@@ -599,7 +600,10 @@ import {runPatSubprocess,} from './local-ops/index.ts';import { getLogger } from './logger.ts';-import { isAllowedWorkspaceHostHeader, isLoopbackAddress } from './loopback.ts';+import {+ isAllowedWorkspaceHostHeader as isAllowedWorkspaceHostHeaderBase,+ isLoopbackAddress,+} from './loopback.ts';import {managedArtifactAbsPath,managedArtifactTimelinePaths,@@ -619,6 +623,7 @@ import {} from './metrics.ts';import { precomputeParse } from './parse-pool.ts';import { isWithinDir, toPosix } from './path-utils.ts';+import { hostHeaderMatchesPublicHost } from './remote-access.ts';import {appendRenameLogEntry,createAncestorShaSetCache,@@ -2651,6 +2656,14 @@ async function renameTrackedPathInGit(}export interface ApiExtensionOptions {+ /**+ * The tunnel's public host (from `ResolvedRemoteAccess.publicHost`) when the+ * server was started with remote access enabled. Widens the browser-Origin+ * allowlists (the `/api/*` CORS gate + the local-op checks) to admit the+ * remote SPA's origin. Undefined in local mode — allowlists stay+ * loopback-only.+ */+ remotePublicHost?: string;hocuspocus: Hocuspocus;durabilityState: DocumentDurabilityState;sessionManager: AgentSessionManager;@@ -3043,7 +3056,20 @@ function applyDiskEventToLiveAllFilesIndex(}export function createApiExtension(options: ApiExtensionOptions): Extension {- const { durabilityState } = options;+ const { durabilityState, remotePublicHost } = options;+ // Every local-op call site in this factory inherits the remote-origin+ // widening through this shadow — one choke point, zero per-site churn.+ const checkLocalOpSecurity = (+ req: IncomingMessage,+ res: ServerResponse,+ opts: { handler: string },+ ): boolean => checkLocalOpSecurityBase(req, res, { ...opts, remotePublicHost });+ // Same shadow for the route-level Host gates (principal, workspace, metrics,+ // the write-path gates): in remote mode the tunnel's public Host is as+ // legitimate as a loopback name — the mount's admit gate already vetted it.+ const isAllowedWorkspaceHostHeader = (host: string | undefined): boolean =>+ isAllowedWorkspaceHostHeaderBase(host) ||+ (remotePublicHost !== undefined && hostHeaderMatchesPublicHost(host, remotePublicHost));const {hocuspocus,sessionManager,@@ -19122,7 +19148,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {if (req.method === 'GET' || req.method === 'HEAD') {try {// Same-origin collab WS: the shell loaded from this server, so- // `ws://<host>/collab` reaches the same process the request arrived on.+ // `ws(s)://<host>/collab` reaches the same process the request arrived+ // on (scheme honors X-Forwarded-Proto — see collab-bootstrap-url.ts).// Avoids the cross-port WS attempt sandboxed preview panes refuse. The// Host value is the client's own header reflected back to itself (the// Origin CORS gate in `onRequest` already refused cross-origin@@ -19132,8 +19159,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {// canonical advertised port to substitute, and the client falls back// to a same-origin WS URL on a null. Node HTTP/1.1 always populates// Host, so the null path is a malformed-request floor, not a normal case.- const host = req.headers.host;- const collabUrl = host ? `ws://${host}/collab` : null;+ const collabUrl = collabUrlFromRequestHeaders(req.headers);const port = lockDir ? (readServerLock(lockDir)?.port ?? 0) : 0;// `singleFile` tells the React shell to drop project chrome for an// ephemeral single-file session (`ok <file>`).@@ -20618,7 +20644,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {// unit tests that stub only `writeHead` + `end`.if (url.startsWith('/api/')) {const origin = request.headers.origin;- if (origin !== undefined && !isAllowedApiOrigin(origin)) {+ if (origin !== undefined && !isAllowedApiOrigin(origin, remotePublicHost)) {// RFC 9457 problem+json. Tag the handler as `api-origin-gate` so// the `ok.api.error.count` counter distinguishes onRequest-level// CSRF rejections from per-handler emits. The cross-origin browserdiff --git a/packages/server/src/api-origin.test.ts b/packages/server/src/api-origin.test.tsindex 3ad5f8a2e..0fdbb36c2 100644--- a/packages/server/src/api-origin.test.ts+++ b/packages/server/src/api-origin.test.ts@@ -22,3 +22,19 @@ describe('API origin guards', () => {expect(isAllowedApiOrigin('file://evil.example')).toBe(false);});});++describe('isAllowedApiOrigin with a remote public host', () => {+ test('admits the https tunnel origin only when the host is supplied', () => {+ expect(isAllowedApiOrigin('https://myproject.ngrok.app', 'myproject.ngrok.app')).toBe(true);+ expect(isAllowedApiOrigin('https://myproject.ngrok.app')).toBe(false);+ });++ test('still refuses foreign and http origins with the host supplied', () => {+ expect(isAllowedApiOrigin('https://evil.example.com', 'myproject.ngrok.app')).toBe(false);+ expect(isAllowedApiOrigin('http://myproject.ngrok.app', 'myproject.ngrok.app')).toBe(false);+ });++ test('loopback origins keep working alongside the remote host', () => {+ expect(isAllowedApiOrigin('http://localhost:5173', 'myproject.ngrok.app')).toBe(true);+ });+});diff --git a/packages/server/src/api-origin.ts b/packages/server/src/api-origin.tsindex 39816dd29..95e18e96e 100644--- a/packages/server/src/api-origin.ts+++ b/packages/server/src/api-origin.ts@@ -8,8 +8,16 @@* allowing the other only breaks the desktop renderer's WS surfaces* (`/collab/thread`) while its HTTP calls sail through.*/-export function isAllowedApiOrigin(origin: string): boolean {+import { originMatchesPublicHost } from './remote-access.ts';++export function isAllowedApiOrigin(origin: string, remotePublicHost?: string): boolean {if (origin === 'null' || origin === 'file://') return true;+ // Remote mode: the SPA served through the tunnel fetches from its public+ // origin — admitted alongside the loopback set. Absent (local mode), the+ // allowlist stays loopback-only.+ if (remotePublicHost !== undefined && originMatchesPublicHost(origin, remotePublicHost)) {+ return true;+ }try {const { hostname } = new URL(origin);return (diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.tsindex fa13b9ac4..98519078e 100644--- a/packages/server/src/boot.ts+++ b/packages/server/src/boot.ts@@ -64,6 +64,7 @@ import { getLogger, loggerFactory, type PinoLogger } from './logger.ts';import { createMcpHttpHandler } from './mcp-http.ts';import { mountMcpAndApi } from './mcp-mount.ts';import { MissingOkConfigError } from './missing-ok-config-error.ts';+import { RemoteConfigError, resolveRemoteAccess } from './remote-access.ts';import { createServer, type ServerInstance, type ServerOptions } from './server-factory.ts';import { installServerMemoryGauge, installServerRuntimeGauges } from './server-memory-telemetry.ts';import { reconcileSkillInstalls } from './skill-reconcile.ts';@@ -232,6 +233,14 @@ export interface BootServerOptions* invoke UI-sibling spawn logic. Default false.*/skipAutoInit?: boolean;+ /**+ * Explicit remote-access opt-in (`ok start --remote`). Remote access is+ * NEVER armed from config alone — a `remote.url` left in `.ok/config.yml`+ * must not silently expose a server whose operator didn't ask for it this+ * run. Only the CLI passes true; the Electron utility and dev-server boot+ * paths never do. Default false.+ */+ enableRemote?: boolean;/*** Forwarded to the ACP thread manager — see* `AcpThreadManagerOptions.probeHarnessManagedMcpEntry`. `ok start` and the@@ -532,9 +541,25 @@ export async function bootServer(opts: BootServerOptions): Promise<BootedServer>async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {const skipAutoInit = opts.skipAutoInit ?? false;const attachUi = opts.attachUiSibling ?? true;- const idleMsOption = opts.idleShutdownMs;const log = opts.log ?? getLogger('boot');+ // Remote access (the `remote:` config block) — armed only on the explicit+ // `enableRemote` opt-in, never from config alone. Throws RemoteConfigError+ // on requested-but-unusable config — fail loud at boot rather than serving+ // a half-open remote surface. Ephemeral single-file mode never serves+ // remotely (it has no project, no MCP endpoint, and no consented root).+ const remoteAccess =+ opts.enableRemote === true && opts.ephemeral !== true ? resolveRemoteAccess(opts.config) : null;+ if (opts.enableRemote === true && opts.ephemeral !== true && remoteAccess === null) {+ throw new RemoteConfigError(+ 'remote access was requested but remote.url is not set — pass a url (`ok start --remote <url>`) or set remote.url in .ok/config.yml.',+ );+ }+ // Remote MCP sessions arrive over the tunnel as plain HTTP; the idle timer+ // counts /collab WS clients only and would tear the server down under a+ // live remote client. Keep it up in remote mode.+ const idleMsOption = remoteAccess !== null ? null : opts.idleShutdownMs;+// Lock-kind resolution. Explicit option wins over env. `OK_LOCK_KIND` is// the contract used by the MCP detach-spawn path in// `packages/cli/src/mcp/shim.ts` — direct callers (CLI `ok start`,@@ -663,6 +688,7 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {const serverInstance = createServer({contentDir: opts.contentDir,projectDir: opts.projectDir,+ remotePublicHost: remoteAccess?.publicHost,contentRoot: opts.contentRoot,port: opts.port,host: opts.host,@@ -859,10 +885,15 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {// mounts, so the first `list` already includes them.if (acpThreadManager !== null) await acpThreadManager.init();+ if (remoteAccess !== null) {+ log.info({ url: remoteAccess.url }, '[remote] remote access enabled (trust-the-tunnel)');+ }+const mount = mountMcpAndApi({httpServer,hocuspocus,mcpHttpHandler,+ remoteAccess,log,sessionManager,agentFocusBroadcaster,diff --git a/packages/server/src/collab-bootstrap-url.test.ts b/packages/server/src/collab-bootstrap-url.test.tsnew file mode 100644index 000000000..b5aba2adb--- /dev/null+++ b/packages/server/src/collab-bootstrap-url.test.ts@@ -0,0 +1,32 @@+import { describe, expect, test } from 'vitest';+import { collabUrlFromRequestHeaders } from './collab-bootstrap-url.ts';++describe('collabUrlFromRequestHeaders', () => {+ test('reflects the client Host over plain ws locally', () => {+ expect(collabUrlFromRequestHeaders({ host: 'localhost:24550' })).toBe(+ 'ws://localhost:24550/collab',+ );+ });++ test('upgrades to wss when the tunnel forwarded https', () => {+ expect(+ collabUrlFromRequestHeaders({+ host: 'myproject.ngrok.app',+ 'x-forwarded-proto': 'https',+ }),+ ).toBe('wss://myproject.ngrok.app/collab');+ });++ test('multi-valued forwarded-proto uses the first hop', () => {+ expect(+ collabUrlFromRequestHeaders({+ host: 'myproject.ngrok.app',+ 'x-forwarded-proto': ['https', 'http'] as unknown as string,+ }),+ ).toBe('wss://myproject.ngrok.app/collab');+ });++ test('missing Host yields null (malformed-request floor)', () => {+ expect(collabUrlFromRequestHeaders({})).toBeNull();+ });+});diff --git a/packages/server/src/collab-bootstrap-url.ts b/packages/server/src/collab-bootstrap-url.tsnew file mode 100644index 000000000..7acd55647--- /dev/null+++ b/packages/server/src/collab-bootstrap-url.ts@@ -0,0 +1,20 @@+/**+ * Same-origin collab WebSocket URL for the `/api/config` bootstrap payload.+ *+ * Host-reflecting by design: the shell loaded from this server, so+ * `ws(s)://<the client's own Host>/collab` reaches the same process the+ * request arrived on. The scheme honors `X-Forwarded-Proto` because tunnels+ * (ngrok, cloudflared, tailscale serve) terminate TLS at the edge and proxy+ * plain http inward — a browser on the https tunnel origin must be handed+ * `wss://`, or the mixed-content check blocks the socket outright.+ */++import type { IncomingMessage } from 'node:http';++export function collabUrlFromRequestHeaders(headers: IncomingMessage['headers']): string | null {+ const host = headers.host;+ if (!host) return null;+ const fwd = headers['x-forwarded-proto'];+ const proto = Array.isArray(fwd) ? fwd[0] : fwd;+ return `${proto === 'https' ? 'wss' : 'ws'}://${host}/collab`;+}diff --git a/packages/server/src/index.ts b/packages/server/src/index.tsindex 6e31a1569..0335d683f 100644--- a/packages/server/src/index.ts+++ b/packages/server/src/index.ts@@ -398,6 +398,13 @@ export {reconcile,splitMarkdownBlocks,} from './reconciliation.ts';+export {+ hasForwardingHeaders,+ isRemoteAdmitted,+ RemoteConfigError,+ type ResolvedRemoteAccess,+ resolveRemoteAccess,+} from './remote-access.ts';export { resolvePackageVersion } from './resolve-package-version.ts';// Seed scaffolder (`ok seed`) — shared module for the CLI Commander wrapper// and the Electron IPC handler. Deterministic plan/apply split; writes thediff --git a/packages/server/src/local-op-security.test.ts b/packages/server/src/local-op-security.test.tsindex 22777fb77..d112d026c 100644--- a/packages/server/src/local-op-security.test.ts+++ b/packages/server/src/local-op-security.test.ts@@ -712,3 +712,27 @@ describe('createConcurrencyGuard', () => {expect(() => guard.release('never-acquired')).not.toThrow();});});++describe('hasValidLocalOpOrigin with a remote public host', () => {+ const reqWithOrigin = (origin: string) =>+ ({ headers: { origin }, socket: { remoteAddress: '127.0.0.1' } }) as never;++ test('admits the https tunnel origin only when the host is supplied', () => {+ expect(+ hasValidLocalOpOrigin(reqWithOrigin('https://myproject.ngrok.app'), 'myproject.ngrok.app'),+ ).toBe(true);+ expect(hasValidLocalOpOrigin(reqWithOrigin('https://myproject.ngrok.app'))).toBe(false);+ });++ test('still refuses foreign origins with the host supplied', () => {+ expect(+ hasValidLocalOpOrigin(reqWithOrigin('https://evil.example.com'), 'myproject.ngrok.app'),+ ).toBe(false);+ });++ test('loopback origins keep working alongside the remote host', () => {+ expect(+ hasValidLocalOpOrigin(reqWithOrigin('http://localhost:5173'), 'myproject.ngrok.app'),+ ).toBe(true);+ });+});diff --git a/packages/server/src/local-op-security.ts b/packages/server/src/local-op-security.tsindex 13c6c2490..2dcf15274 100644--- a/packages/server/src/local-op-security.ts+++ b/packages/server/src/local-op-security.ts@@ -18,6 +18,7 @@ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:patimport { errorResponse } from './http/error-response.ts';import { errnoCode } from './http/handler-utils.ts';import { getLogger } from './logger.ts';+import { originMatchesPublicHost } from './remote-access.ts';const log = getLogger('local-op-security');@@ -232,9 +233,15 @@ export function isLoopbackRequest(req: IncomingMessage): boolean {* accept crafted origins like `http://127.0.0.1.evil.com` if DNS rebinding* ever lined up with the loopback socket check.*/-export function hasValidLocalOpOrigin(req: IncomingMessage): boolean {+export function hasValidLocalOpOrigin(req: IncomingMessage, remotePublicHost?: string): boolean {const origin = req.headers.origin;if (!origin) return true;+ // Remote mode: the SPA served through the tunnel fetches from its public+ // origin — admitted alongside the loopback set. Absent (local mode), the+ // allowlist stays loopback-only.+ if (remotePublicHost !== undefined && originMatchesPublicHost(origin, remotePublicHost)) {+ return true;+ }try {// WHATWG URL preserves the IPv6 brackets in `hostname` (e.g. `[::1]`), so// the comparison set includes the bracketed form alongside the literal.@@ -263,7 +270,7 @@ export function hasValidLocalOpOrigin(req: IncomingMessage): boolean {export function checkLocalOpSecurity(req: IncomingMessage,res: ServerResponse,- options: { handler: string },+ options: { handler: string; remotePublicHost?: string },): boolean {if (!isLoopbackRequest(req)) {errorResponse(@@ -275,7 +282,7 @@ export function checkLocalOpSecurity();return false;}- if (!hasValidLocalOpOrigin(req)) {+ if (!hasValidLocalOpOrigin(req, options.remotePublicHost)) {errorResponse(res,403,diff --git a/packages/server/src/mcp-mount.ts b/packages/server/src/mcp-mount.tsindex 671d8910b..0d1ec80c7 100644--- a/packages/server/src/mcp-mount.ts+++ b/packages/server/src/mcp-mount.ts@@ -46,6 +46,11 @@ import { isAllowedWorkspaceHostHeader, isLoopbackAddress } from './loopback.ts';import type { MaintenanceCoordinator } from './maintenance-coordinator.ts';import type { McpHttpHandler } from './mcp-http.ts';import { handleCollabSocketError, incrementCollabMessageTooLarge } from './metrics.ts';+import {+ hasForwardingHeaders,+ isRemoteAdmitted,+ type ResolvedRemoteAccess,+} from './remote-access.ts';const DEFAULT_KEEPALIVE_GRACE_MS = 10_000;const MAX_COLLAB_MESSAGE_BYTES = 1024 * 1024;@@ -136,6 +141,20 @@ export interface MountMcpAndApiOptions {* serving is unchanged.*/ephemeral?: boolean;+ /**+ * Resolved `remote:` config (null/undefined ⇒ remote access disabled).+ * When set, EVERY surface (`/mcp`, `/api/*`, `/collab`, content assets,+ * the SPA) admits requests whose Host is either a loopback name or the+ * tunnel's public host — the trust-the-tunnel model: OK does not+ * authenticate remote callers, the tunnel's edge does (see+ * `remote-access.ts`). Wrong-Host requests (DNS-rebound pages) are refused.+ * Local loopback behavior is byte-for-byte unchanged.+ *+ * When null/undefined, requests carrying proxy-forwarding headers are+ * refused with a hint — a tunnel pointed at a server that never opted in+ * must fail loud, not silently inherit full local trust.+ */+ remoteAccess?: ResolvedRemoteAccess | null;}export interface MountMcpAndApiHandle {@@ -182,6 +201,7 @@ export function mountMcpAndApi(opts: MountMcpAndApiOptions): MountMcpAndApiHandlreactShellMiddleware,ephemeral,} = opts;+ const remoteAccess = opts.remoteAccess ?? undefined;const keepaliveGraceMs = opts.keepaliveGraceMs ?? DEFAULT_KEEPALIVE_GRACE_MS;const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_COLLAB_MESSAGE_BYTES });@@ -208,24 +228,53 @@ export function mountMcpAndApi(opts: MountMcpAndApiOptions): MountMcpAndApiHandlconst onRequest = (req: IncomingMessage, res: ServerResponse): void => {const url = req.url?.split('?')[0];+ // Tripwire: proxy-forwarding headers on a server that never opted into+ // remote access mean a tunnel is pointed at us. Refuse with the fix+ // instruction — the alternative is silently serving a public tunnel with+ // full local trust, decided by whether the tunnel rewrites Host.+ if (remoteAccess === undefined && hasForwardingHeaders(req)) {+ errorResponse(+ res,+ 403,+ 'urn:ok:error:host-not-allowed',+ 'Proxied request refused: this server was not started for remote access. Restart with `ok start --remote` to serve through a tunnel.',+ { handler: 'mcp-mount' },+ );+ return;+ }+ // With remote access enabled, ONE admit decision covers every surface+ // (trust-the-tunnel — see remote-access.ts): loopback socket + Host on+ // the allowlist (loopback names or the tunnel's public host). Refusals+ // are wrong-Host callers (DNS-rebound pages), not auth failures.+ if (remoteAccess !== undefined && !isRemoteAdmitted(req, remoteAccess)) {+ errorResponse(res, 403, 'urn:ok:error:host-not-allowed', 'Host header not allowed.', {+ handler: 'mcp-mount',+ });+ return;+ }if (mcpHttpHandler !== undefined && url === '/mcp') {const origin = req.headers.origin;const sessionId = Array.isArray(req.headers['mcp-session-id'])? req.headers['mcp-session-id'][0]: req.headers['mcp-session-id'];- if (!isLoopbackAddress(req.socket.remoteAddress)) {- errorResponse(res, 403, 'urn:ok:error:loopback-required', 'Loopback access required.', {- handler: 'mcp',- });- return;- }- if (!isAllowedWorkspaceHostHeader(req.headers.host)) {- errorResponse(res, 403, 'urn:ok:error:host-not-allowed', 'Host header not allowed.', {- handler: 'mcp',- });- return;+ if (remoteAccess === undefined) {+ // The pre-remote gate pair, unchanged: loopback socket + loopback+ // Host. (With remote enabled the shared admit gate above already+ // enforced the superset.)+ if (!isLoopbackAddress(req.socket.remoteAddress)) {+ errorResponse(res, 403, 'urn:ok:error:loopback-required', 'Loopback access required.', {+ handler: 'mcp',+ });+ return;+ }+ if (!isAllowedWorkspaceHostHeader(req.headers.host)) {+ errorResponse(res, 403, 'urn:ok:error:host-not-allowed', 'Host header not allowed.', {+ handler: 'mcp',+ });+ return;+ }}- if (origin !== undefined && !isAllowedApiOrigin(origin)) {+ if (origin !== undefined && !isAllowedApiOrigin(origin, remoteAccess?.publicHost)) {errorResponse(res, 403, 'urn:ok:error:invalid-origin', 'Origin not allowed.', {handler: 'mcp',});@@ -399,19 +448,44 @@ export function mountMcpAndApi(opts: MountMcpAndApiOptions): MountMcpAndApiHandl};const onUpgrade = (req: IncomingMessage, socket: Duplex, head: Buffer): void => {+ // Same tripwire as the HTTP leg: a proxied upgrade on a server that never+ // opted into remote access is refused rather than trusted as local.+ if (remoteAccess === undefined && hasForwardingHeaders(req)) {+ log.warn(+ { url: req.url, host: req.headers.host },+ '[remote] refused proxied WS upgrade; start the server with `ok start --remote <url>`',+ );+ socket.destroy();+ return;+ }+ // Shared admit decision for the `/collab/thread` + `/collab/keepalive`+ // upgrades. Remote mode widens the Host allowlist to the tunnel's public+ // host through the `isRemoteAdmitted` choke point (tunnel traffic arrives+ // loopback-peer + public-Host); local mode keeps the loopback-peer ++ // workspace-Host gate. The bare `/collab` catch-all below relies on the+ // loopback bind in local mode, so it only consults `isRemoteAdmitted`.+ const collabUpgradeAdmitted = (): boolean =>+ remoteAccess !== undefined+ ? isRemoteAdmitted(req, remoteAccess)+ : isLoopbackAddress(req.socket.remoteAddress) &&+ isAllowedWorkspaceHostHeader(req.headers.host);if (req.url?.startsWith('/collab/thread')) {- // Same gate family as the mutating HTTP surface: loopback peer +- // workspace Host header, plus browser-Origin allowlist when an Origin- // is present (WS upgrades from pages always carry one; a DNS-rebound- // page fails the Host check, a foreign page fails the Origin check).+ // Admit via the shared `/collab` upgrade gate (remote-widened Host in+ // remote mode), plus the browser-Origin allowlist when an Origin is+ // present (WS upgrades from pages always carry one; a DNS-rebound page+ // fails the Host check, a foreign page fails the Origin check).const acp = opts.acpThreadManager;if (acp === undefined ||acp === null ||- !isLoopbackAddress(req.socket.remoteAddress) ||- !isAllowedWorkspaceHostHeader(req.headers.host) ||- (req.headers.origin !== undefined && !isAllowedApiOrigin(req.headers.origin))+ !collabUpgradeAdmitted() ||+ (req.headers.origin !== undefined &&+ !isAllowedApiOrigin(req.headers.origin, remoteAccess?.publicHost))) {+ log.debug(+ { url: req.url, host: req.headers.host, origin: req.headers.origin },+ '[collab] /collab/thread upgrade refused',+ );socket.destroy();return;}@@ -428,10 +502,11 @@ export function mountMcpAndApi(opts: MountMcpAndApiOptions): MountMcpAndApiHandl}if (req.url?.startsWith('/collab/keepalive')) {- if (- !isLoopbackAddress(req.socket.remoteAddress) ||- !isAllowedWorkspaceHostHeader(req.headers.host)- ) {+ if (!collabUpgradeAdmitted()) {+ log.debug(+ { url: req.url, host: req.headers.host },+ '[collab] /collab/keepalive upgrade refused',+ );socket.destroy();return;}@@ -588,6 +663,13 @@ export function mountMcpAndApi(opts: MountMcpAndApiOptions): MountMcpAndApiHandl}if (req.url?.startsWith('/collab')) {+ // Same admit gate as the HTTP legs: a wrong-Host upgrade never reaches+ // Hocuspocus (the CRDT write surface).+ if (remoteAccess !== undefined && !isRemoteAdmitted(req, remoteAccess)) {+ log.debug({ url: req.url, host: req.headers.host }, '[collab] /collab upgrade refused');+ socket.destroy();+ return;+ }socket.on('error', (err: NodeJS.ErrnoException) => {if (handleCollabSocketError(err)) return;log.error({ err }, 'Upgrade socket error');diff --git a/packages/server/src/remote-access.test.ts b/packages/server/src/remote-access.test.tsnew file mode 100644index 000000000..ef3932f11--- /dev/null+++ b/packages/server/src/remote-access.test.ts@@ -0,0 +1,134 @@+import { describe, expect, test } from 'vitest';+import { ConfigSchema } from './config/schema.ts';+import {+ hasForwardingHeaders,+ hostHeaderMatchesPublicHost,+ isRemoteAdmitted,+ originMatchesPublicHost,+ RemoteConfigError,+ type ResolvedRemoteAccess,+ resolveRemoteAccess,+} from './remote-access.ts';++function resolved(url: string): ResolvedRemoteAccess {+ const remote = resolveRemoteAccess(ConfigSchema.parse({ remote: { url } }));+ if (remote === null) throw new Error('expected resolved remote access');+ return remote;+}++interface FakeReq {+ headers: Record<string, string | string[] | undefined>;+ socket: { remoteAddress?: string | undefined };+}++function req(host: string | undefined, remoteAddress = '127.0.0.1'): FakeReq {+ return { headers: host === undefined ? {} : { host }, socket: { remoteAddress } };+}++describe('resolveRemoteAccess', () => {+ test('no url resolves to null — the caller decides whether that is fatal', () => {+ expect(resolveRemoteAccess(ConfigSchema.parse({}))).toBeNull();+ expect(resolveRemoteAccess(undefined)).toBeNull();+ });++ test('a non-URL url throws RemoteConfigError', () => {+ expect(() => resolveRemoteAccess(ConfigSchema.parse({ remote: { url: 'not a url' } }))).toThrow(+ RemoteConfigError,+ );+ });++ test('https url resolves with the default port', () => {+ const remote = resolved('https://myproject.ngrok.app');+ expect(remote.url).toBe('https://myproject.ngrok.app');+ expect(remote.publicHost).toBe('myproject.ngrok.app');+ expect(remote.port).toBe(24550);+ });++ test('plain-http url throws — the public tunnel URL is always https', () => {+ expect(() =>+ resolveRemoteAccess(ConfigSchema.parse({ remote: { url: 'http://myproject.ngrok.app' } })),+ ).toThrow(RemoteConfigError);+ });++ test('normalizes trailing slash and default-port host', () => {+ const remote = resolved('https://myproject.ngrok.app:443/');+ expect(remote.url).toBe('https://myproject.ngrok.app:443');+ expect(remote.publicHost).toBe('myproject.ngrok.app');+ });+});++describe('isRemoteAdmitted', () => {+ const remote = resolved('https://myproject.ngrok.app');++ test('loopback socket + loopback Host → admitted (local clients unchanged)', () => {+ expect(isRemoteAdmitted(req('127.0.0.1:24550'), remote)).toBe(true);+ expect(isRemoteAdmitted(req('localhost:24550'), remote)).toBe(true);+ });++ test('loopback socket + the tunnel public Host → admitted', () => {+ expect(isRemoteAdmitted(req('myproject.ngrok.app'), remote)).toBe(true);+ });++ test('default-port suffix on the public Host still matches', () => {+ expect(isRemoteAdmitted(req('myproject.ngrok.app:443'), remote)).toBe(true);+ });++ test('wrong Host → refused (DNS-rebinding shape)', () => {+ expect(isRemoteAdmitted(req('evil.example.com'), remote)).toBe(false);+ });++ test('missing Host → refused', () => {+ expect(isRemoteAdmitted(req(undefined), remote)).toBe(false);+ });++ test('non-loopback socket → refused even with the right Host (LAN peer)', () => {+ expect(isRemoteAdmitted(req('myproject.ngrok.app', '192.168.1.50'), remote)).toBe(false);+ expect(isRemoteAdmitted(req('127.0.0.1:24550', '192.168.1.50'), remote)).toBe(false);+ });+});++describe('hasForwardingHeaders', () => {+ test('detects each standard forwarding header', () => {+ expect(hasForwardingHeaders({ headers: { 'x-forwarded-for': '203.0.113.7' } })).toBe(true);+ expect(hasForwardingHeaders({ headers: { 'x-forwarded-proto': 'https' } })).toBe(true);+ expect(hasForwardingHeaders({ headers: { forwarded: 'for=203.0.113.7' } })).toBe(true);+ });++ test('plain local requests carry none', () => {+ expect(hasForwardingHeaders({ headers: { host: 'localhost:24550' } })).toBe(false);+ });+});++describe('originMatchesPublicHost', () => {+ test('https origin on the public host matches, with or without :443', () => {+ expect(originMatchesPublicHost('https://myproject.ngrok.app', 'myproject.ngrok.app')).toBe(+ true,+ );+ expect(originMatchesPublicHost('https://myproject.ngrok.app:443', 'myproject.ngrok.app')).toBe(+ true,+ );+ });++ test('http scheme, other hosts, and garbage never match', () => {+ expect(originMatchesPublicHost('http://myproject.ngrok.app', 'myproject.ngrok.app')).toBe(+ false,+ );+ expect(originMatchesPublicHost('https://evil.example.com', 'myproject.ngrok.app')).toBe(false);+ expect(originMatchesPublicHost('not-an-origin', 'myproject.ngrok.app')).toBe(false);+ });+});++describe('hostHeaderMatchesPublicHost', () => {+ test('matches the public host, with or without default-port suffix', () => {+ expect(hostHeaderMatchesPublicHost('myproject.ngrok.app', 'myproject.ngrok.app')).toBe(true);+ expect(hostHeaderMatchesPublicHost('myproject.ngrok.app:443', 'myproject.ngrok.app')).toBe(+ true,+ );+ expect(hostHeaderMatchesPublicHost('MyProject.NGROK.app', 'myproject.ngrok.app')).toBe(true);+ });++ test('refuses other hosts and missing Host', () => {+ expect(hostHeaderMatchesPublicHost('evil.example.com', 'myproject.ngrok.app')).toBe(false);+ expect(hostHeaderMatchesPublicHost(undefined, 'myproject.ngrok.app')).toBe(false);+ });+});diff --git a/packages/server/src/remote-access.ts b/packages/server/src/remote-access.tsnew file mode 100644index 000000000..14f1cebda--- /dev/null+++ b/packages/server/src/remote-access.ts@@ -0,0 +1,117 @@+/**+ * Remote access — trust-the-tunnel model.+ *+ * OK binds loopback; a tunnel (ngrok, cloudflared, tailscale, a reverse proxy)+ * terminates TLS and proxies in. OK does not authenticate remote callers, so+ * whoever reaches the tunnel gets the local-caller surface; restricting who+ * can reach it is the tunnel's job (edge auth). That is why remote access is+ * an explicit `ok start --remote` opt-in, never a config side effect.+ *+ * With remote enabled the server still requires a loopback socket (the tunnel+ * connects from loopback; the bind is loopback-only) and an allowlisted Host+ * (loopback names, or the `remote.url` host for tunnel clients) — the+ * DNS-rebinding defense, not authentication.+ *+ * `resolveRemoteAccess` (config → shape) and `isRemoteAdmitted` (request →+ * admit) are the two choke points every gate in `mcp-mount.ts` consumes.+ */++import type { IncomingMessage } from 'node:http';+import type { Config } from './config/schema.ts';+import { isAllowedWorkspaceHostHeader, isLoopbackAddress } from './loopback.ts';++export interface ResolvedRemoteAccess {+ /** Normalized public base URL (no trailing slash); always https. */+ url: string;+ /** `host[:port]` of `url` with any default-port suffix stripped — Host-header comparand. */+ publicHost: string;+ /** Fixed listen port from config (schema default 24550). */+ port: number;+}++export class RemoteConfigError extends Error {}++/**+ * Resolve the `remote:` config to runtime shape. `null` when `remote.url` is+ * unset (the caller decides if that is fine or fatal). Throws+ * `RemoteConfigError` on an unusable url so `ok start --remote` fails loud.+ */+export function resolveRemoteAccess(config: Config | undefined): ResolvedRemoteAccess | null {+ const remote = config?.remote;+ if (remote === undefined || remote.url === undefined || remote.url === '') return null;+ let parsed: URL;+ try {+ parsed = new URL(remote.url);+ } catch {+ throw new RemoteConfigError(`remote.url is not a valid URL: ${remote.url}`);+ }+ if (parsed.protocol !== 'https:') {+ // Tunnels serve https; plain http would be credentials-in-the-clear.+ throw new RemoteConfigError(+ `remote.url must be https — it is the public tunnel URL remote clients connect to (got: ${remote.url})`,+ );+ }+ return {+ url: remote.url.replace(/\/+$/, ''),+ publicHost: normalizeHostHeader(parsed.host),+ port: remote.port,+ };+}++function firstHeader(value: string | string[] | undefined): string | undefined {+ return Array.isArray(value) ? value[0] : value;+}++/** Strip a default-port suffix so `host:443`/`host:80` compare equal to `host`. */+function normalizeHostHeader(host: string): string {+ return host.replace(/:(443|80)$/, '').toLowerCase();+}++/** True when a raw `Host` names the tunnel's public host — for the route-level Host gates, in remote mode. */+export function hostHeaderMatchesPublicHost(host: string | undefined, publicHost: string): boolean {+ return host !== undefined && normalizeHostHeader(host) === publicHost;+}++/** True when a browser `Origin` names the tunnel's public host over https — extends the loopback-origin CSRF gates in remote mode. */+export function originMatchesPublicHost(origin: string, publicHost: string): boolean {+ try {+ const url = new URL(origin);+ return url.protocol === 'https:' && normalizeHostHeader(url.host) === publicHost;+ } catch {+ return false;+ }+}++/**+ * Admit decision when remote is enabled: a loopback socket AND an allowlisted+ * Host (loopback names, or the tunnel's public host). Refusals are wrong-Host+ * callers, not unauthenticated ones — there is no auth tier.+ */+export function isRemoteAdmitted(+ req: Pick<IncomingMessage, 'headers'> & { socket: { remoteAddress?: string | undefined } },+ remote: ResolvedRemoteAccess,+): boolean {+ if (!isLoopbackAddress(req.socket.remoteAddress)) return false;+ const host = firstHeader(req.headers.host);+ if (isAllowedWorkspaceHostHeader(host)) return true;+ return host !== undefined && normalizeHostHeader(host) === remote.publicHost;+}++/**+ * Proxy-forwarding headers (standard `X-Forwarded-*` / `Forwarded` plus common+ * vendor ones). Their presence while remote is DISABLED means a tunnel points+ * at a server that never opted in — mcp-mount's tripwire refuses with a hint.+ */+const FORWARDING_HEADERS = [+ 'x-forwarded-for',+ 'x-forwarded-proto',+ 'forwarded',+ 'x-real-ip',+ 'cf-connecting-ip',+ 'true-client-ip',+] as const;++/** True when the request carries any standard proxy-forwarding header. */+export function hasForwardingHeaders(req: Pick<IncomingMessage, 'headers'>): boolean {+ return FORWARDING_HEADERS.some((h) => req.headers[h] !== undefined);+}diff --git a/packages/server/src/remote-mcp.test.ts b/packages/server/src/remote-mcp.test.tsnew file mode 100644index 000000000..48eded014--- /dev/null+++ b/packages/server/src/remote-mcp.test.ts@@ -0,0 +1,503 @@+/**+ * Remote access — mount-level admission matrix for the trust-the-tunnel model.+ *+ * Boots the REAL `mountMcpAndApi` + `createMcpHttpHandler` on a loopback+ * port, then plays remote callers by shaping requests the way any tunnel's+ * local agent delivers them: loopback TCP peer + the tunnel's public Host+ * (+ the forwarding headers proxies inject). That is byte-for-byte what the+ * server sees behind a real ngrok / cloudflared / tailscale tunnel — the+ * transport itself is the only untested hop.+ *+ * With remote enabled there is ONE gate: Host on the allowlist (loopback+ * names or the tunnel's public host) over a loopback socket. Admitted+ * callers get the full surface; there is no per-origin tiering and no+ * server-side auth — restricting WHO can reach the tunnel is the tunnel's+ * job (edge auth). With remote disabled, proxied requests trip the+ * forwarding-header tripwire instead of inheriting local trust.+ */++import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import {+ createServer as createHttpServer,+ type Server as HttpServer,+ request as httpRequest,+} from 'node:http';+import { connect as createNetConnection } from 'node:net';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { Hocuspocus } from '@hocuspocus/server';+import { afterEach, describe, expect, test } from 'vitest';+import { ConfigSchema } from './config/schema.ts';+import { getFreeLoopbackPort } from './loopback-rig-test-helpers.ts';+import { createMcpHttpHandler, type McpHttpHandler } from './mcp-http.ts';+import { type MountMcpAndApiHandle, mountMcpAndApi } from './mcp-mount.ts';+import { resolveRemoteAccess } from './remote-access.ts';++const MCP_PROTOCOL_VERSION = '2025-06-18';+const PUBLIC_URL = 'https://myproject.ngrok.app';+const PUBLIC_HOST = 'myproject.ngrok.app';++/** What any tunnel's local agent delivers: public Host over a loopback socket. */+const TUNNEL_HEADERS = { host: PUBLIC_HOST };+/** Same, with the forwarding headers mainstream tunnels inject. */+const TUNNEL_FORWARDED_HEADERS = {+ host: PUBLIC_HOST,+ 'x-forwarded-for': '203.0.113.7',+ 'x-forwarded-proto': 'https',+};++const log = {+ error: () => {},+ warn: () => {},+ info: () => {},+ debug: () => {},+ child: () => log,+} as never;++const hocuspocus = {+ hooks: async () => {},+ handleConnection: () => ({ handleMessage: () => {}, handleClose: () => {} }),+} as unknown as Hocuspocus;++interface Rig {+ port: number;+ contentDir: string;+ cleanup: () => Promise<void>;+}++let rigs: Rig[] = [];++afterEach(async () => {+ await Promise.allSettled(rigs.map((r) => r.cleanup()));+ rigs = [];+});++interface RigExtras {+ reactShellMiddleware?: (+ req: import('node:http').IncomingMessage,+ res: import('node:http').ServerResponse,+ next: () => void,+ ) => void;+ /** Stub thread manager to exercise the `/collab/thread` admission gate. */+ acpThreadManager?: unknown;+}++async function bootRemoteRig(+ remote: Record<string, unknown>,+ extras: RigExtras = {},+): Promise<Rig> {+ const contentDir = mkdtempSync(join(tmpdir(), 'ok-remote-mcp-'));+ const localDir = join(contentDir, '.ok', 'local');+ mkdirSync(localDir, { recursive: true });+ const config = ConfigSchema.parse({ remote });+ const remoteAccess = resolveRemoteAccess(config);+ const port = await getFreeLoopbackPort();+ const handler: McpHttpHandler = createMcpHttpHandler({+ contentDir,+ projectDir: contentDir,+ config,+ getServerUrl: () => `http://127.0.0.1:${port}`,+ });+ const httpServer: HttpServer = createHttpServer();+ const mount: MountMcpAndApiHandle = mountMcpAndApi({+ httpServer,+ hocuspocus,+ mcpHttpHandler: handler,+ remoteAccess,+ ...(extras.reactShellMiddleware ? { reactShellMiddleware: extras.reactShellMiddleware } : {}),+ ...(extras.acpThreadManager !== undefined+ ? { acpThreadManager: extras.acpThreadManager as never }+ : {}),+ log,+ });+ await new Promise<void>((resolve) => httpServer.listen(port, '127.0.0.1', () => resolve()));+ const rig: Rig = {+ port,+ contentDir,+ cleanup: async () => {+ await handler.close();+ await mount.shutdown();+ await new Promise<void>((resolve) => {+ httpServer.close(() => resolve());+ });+ rmSync(contentDir, { recursive: true, force: true });+ },+ };+ rigs.push(rig);+ return rig;+}++interface RawResponse {+ status: number;+ headers: Record<string, string | string[] | undefined>;+ body: string;+}++/** Raw request with full Host-header control (fetch forbids overriding Host). */+function raw(+ port: number,+ opts: {+ method?: string;+ path: string;+ headers?: Record<string, string>;+ body?: string;+ },+): Promise<RawResponse> {+ return new Promise((resolve, reject) => {+ const req = httpRequest(+ {+ hostname: '127.0.0.1',+ port,+ path: opts.path,+ method: opts.method ?? 'GET',+ headers: opts.headers,+ },+ (res) => {+ const chunks: Buffer[] = [];+ res.on('data', (c) => chunks.push(Buffer.from(c)));+ res.on('end', () =>+ resolve({+ status: res.statusCode ?? 0,+ headers: res.headers,+ body: Buffer.concat(chunks).toString('utf8'),+ }),+ );+ },+ );+ req.on('error', reject);+ req.end(opts.body);+ });+}++/** Initialize an MCP session through the mount with the given gate headers. */+async function openSession(+ port: number,+ gateHeaders: Record<string, string>,+): Promise<{ sessionId: string }> {+ const init = await raw(port, {+ method: 'POST',+ path: '/mcp',+ headers: {+ ...gateHeaders,+ accept: 'application/json, text/event-stream',+ 'content-type': 'application/json',+ },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'initialize',+ params: {+ protocolVersion: MCP_PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: 'remote-mcp-test', version: '0.0.0' },+ },+ }),+ });+ expect(init.status).toBe(200);+ const sessionId = init.headers['mcp-session-id'];+ expect(typeof sessionId).toBe('string');+ const initialized = await raw(port, {+ method: 'POST',+ path: '/mcp',+ headers: {+ ...gateHeaders,+ accept: 'application/json, text/event-stream',+ 'content-type': 'application/json',+ 'mcp-session-id': sessionId as string,+ 'mcp-protocol-version': MCP_PROTOCOL_VERSION,+ },+ body: JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }),+ });+ expect(initialized.status).toBe(202);+ return { sessionId: sessionId as string };+}++async function listToolNames(port: number, gateHeaders: Record<string, string>): Promise<string[]> {+ const { sessionId } = await openSession(port, gateHeaders);+ const res = await raw(port, {+ method: 'POST',+ path: '/mcp',+ headers: {+ ...gateHeaders,+ accept: 'application/json, text/event-stream',+ 'content-type': 'application/json',+ 'mcp-session-id': sessionId,+ 'mcp-protocol-version': MCP_PROTOCOL_VERSION,+ },+ body: JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/list' }),+ });+ expect(res.status).toBe(200);+ const parsed = JSON.parse(res.body) as { result?: { tools?: Array<{ name: string }> } };+ const tools = parsed.result?.tools;+ expect(Array.isArray(tools)).toBe(true);+ return (tools ?? []).map((t) => t.name);+}++const WRITE_TOOLS = [+ 'write',+ 'edit',+ 'delete',+ 'move',+ 'install',+ 'checkpoint',+ 'restore_version',+ 'resolve_conflict',+];++/** Raw WS upgrade attempt; resolves 'upgraded' on a 101, 'closed' on drop. */+function attemptCollabUpgrade(+ port: number,+ headers: Record<string, string>,+ path = '/collab',+): Promise<string> {+ return new Promise<string>((resolve, reject) => {+ const socket = createNetConnection({ host: '127.0.0.1', port });+ const timer = setTimeout(() => {+ socket.destroy();+ reject(new Error('timed out waiting for /collab upgrade outcome'));+ }, 2000);+ const headerLines = Object.entries(headers).map(([k, v]) => `${k}: ${v}`);+ socket.on('connect', () => {+ socket.write(+ [+ `GET ${path} HTTP/1.1`,+ ...headerLines,+ 'Connection: Upgrade',+ 'Upgrade: websocket',+ 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==',+ 'Sec-WebSocket-Version: 13',+ '',+ '',+ ].join('\r\n'),+ );+ });+ socket.on('data', (chunk: Buffer) => {+ if (chunk.toString('utf8').includes('101 Switching Protocols')) {+ clearTimeout(timer);+ socket.destroy();+ resolve('upgraded');+ }+ });+ socket.on('close', () => {+ clearTimeout(timer);+ resolve('closed');+ });+ socket.on('error', () => {+ clearTimeout(timer);+ resolve('closed');+ });+ });+}++// ---------------------------------------------------------------------------++describe('remote enabled — trust-the-tunnel admission', () => {+ test('tunnel-Host /mcp is admitted with the full tool set (no server-side auth tier)', async () => {+ const rig = await bootRemoteRig({ url: PUBLIC_URL });+ const names = await listToolNames(rig.port, TUNNEL_HEADERS);+ expect(names).toContain('exec');+ expect(names).toContain('search');+ for (const tool of WRITE_TOOLS) expect(names).toContain(tool);+ });++ test('local loopback sessions keep the full tool set when remote is enabled', async () => {+ const rig = await bootRemoteRig({ url: PUBLIC_URL });+ const names = await listToolNames(rig.port, { host: `127.0.0.1:${rig.port}` });+ for (const tool of WRITE_TOOLS) expect(names).toContain(tool);+ });++ test('wrong Host is refused everywhere (DNS-rebinding shape)', async () => {+ const rig = await bootRemoteRig({ url: PUBLIC_URL });+ const mcp = await raw(rig.port, {+ method: 'POST',+ path: '/mcp',+ headers: { host: 'evil.example.com' },+ });+ expect(mcp.status).toBe(403);+ const api = await raw(rig.port, { path: '/api/pages', headers: { host: 'evil.example.com' } });+ expect(api.status).toBe(403);+ expect(api.body).toContain('urn:ok:error:host-not-allowed');+ });++ test('non-/mcp surfaces are reachable under the tunnel Host (one gate for everything)', async () => {+ const rig = await bootRemoteRig({ url: PUBLIC_URL });+ // The mocked hocuspocus answers nothing, so the mount's own 404 backstop+ // responding at all (vs a 403) proves admission.+ const api = await raw(rig.port, { path: '/api/pages', headers: TUNNEL_HEADERS });+ expect(api.status).toBe(404);+ const spa = await raw(rig.port, { path: '/', headers: TUNNEL_HEADERS });+ expect(spa.status).toBe(404);+ });++ test('forwarding headers are fine when remote is enabled (tunnels always inject them)', async () => {+ const rig = await bootRemoteRig({ url: PUBLIC_URL });+ const api = await raw(rig.port, { path: '/api/pages', headers: TUNNEL_FORWARDED_HEADERS });+ expect(api.status).toBe(404);+ });++ test('vendor identity/marker headers are inert — admission is Host-only', async () => {+ const rig = await bootRemoteRig({ url: PUBLIC_URL });+ // Pre-R0 these headers switched tiers (tailnet/funnel). Now they must+ // change nothing: same Host, same admission, same tool set.+ const names = await listToolNames(rig.port, {+ host: PUBLIC_HOST,+ 'tailscale-funnel-request': '?1',+ 'tailscale-user-login': 'someone@example',+ });+ for (const tool of WRITE_TOOLS) expect(names).toContain(tool);+ });++ test('/collab upgrade admits the tunnel Host and drops wrong Hosts', async () => {+ const rig = await bootRemoteRig({ url: PUBLIC_URL });+ await expect(attemptCollabUpgrade(rig.port, { Host: PUBLIC_HOST })).resolves.toBe('upgraded');+ await expect(attemptCollabUpgrade(rig.port, { Host: 'evil.example.com' })).resolves.toBe(+ 'closed',+ );+ });++ test('/collab/keepalive upgrade admits the tunnel Host and drops wrong Hosts', async () => {+ const rig = await bootRemoteRig({ url: PUBLIC_URL });+ await expect(+ attemptCollabUpgrade(rig.port, { Host: PUBLIC_HOST }, '/collab/keepalive'),+ ).resolves.toBe('upgraded');+ await expect(+ attemptCollabUpgrade(rig.port, { Host: 'evil.example.com' }, '/collab/keepalive'),+ ).resolves.toBe('closed');+ });++ test('/collab/thread upgrade admits the tunnel Host so Ask AI works over the tunnel', async () => {+ // The stub thread manager only clears the fail-closed `acp == null` guard;+ // the socket touches it solely when a client sends a frame (this raw+ // upgrade never does), so admission is the only thing under test.+ const rig = await bootRemoteRig(+ { url: PUBLIC_URL },+ { acpThreadManager: { listThreads: () => [] } },+ );+ await expect(+ attemptCollabUpgrade(rig.port, { Host: PUBLIC_HOST }, '/collab/thread'),+ ).resolves.toBe('upgraded');+ await expect(+ attemptCollabUpgrade(rig.port, { Host: 'evil.example.com' }, '/collab/thread'),+ ).resolves.toBe('closed');+ // A foreign browser Origin is refused even under the correct tunnel Host.+ await expect(+ attemptCollabUpgrade(+ rig.port,+ { Host: PUBLIC_HOST, Origin: 'https://evil.example.com' },+ '/collab/thread',+ ),+ ).resolves.toBe('closed');+ });++ test('default-port Host suffix still matches', async () => {+ const rig = await bootRemoteRig({ url: PUBLIC_URL });+ const api = await raw(rig.port, {+ path: '/api/pages',+ headers: { host: `${PUBLIC_HOST}:443` },+ });+ expect(api.status).toBe(404);+ });+});++describe('remote disabled — the forwarding-header tripwire', () => {+ test('proxied requests are refused with the --remote hint', async () => {+ const rig = await bootRemoteRig({});+ const res = await raw(rig.port, {+ path: '/api/pages',+ headers: { host: `127.0.0.1:${rig.port}`, 'x-forwarded-for': '203.0.113.7' },+ });+ expect(res.status).toBe(403);+ expect(res.body).toContain('ok start --remote');+ });++ test('vendor proxy headers (X-Real-IP, CF-Connecting-IP, True-Client-IP) also trip the wire', async () => {+ const rig = await bootRemoteRig({});+ for (const header of ['x-real-ip', 'cf-connecting-ip', 'true-client-ip']) {+ const res = await raw(rig.port, {+ path: '/api/pages',+ headers: { host: `127.0.0.1:${rig.port}`, [header]: '203.0.113.7' },+ });+ expect(res.status, `${header} should trip the wire`).toBe(403);+ expect(res.body).toContain('ok start --remote');+ }+ });++ test('unproxied local requests are served as always', async () => {+ const rig = await bootRemoteRig({});+ const api = await raw(rig.port, {+ path: '/api/pages',+ headers: { host: `127.0.0.1:${rig.port}` },+ });+ expect(api.status).toBe(404);+ const names = await listToolNames(rig.port, { host: `127.0.0.1:${rig.port}` });+ for (const tool of WRITE_TOOLS) expect(names).toContain(tool);+ });++ test('a proxied /collab upgrade is dropped', async () => {+ const rig = await bootRemoteRig({});+ await expect(+ attemptCollabUpgrade(rig.port, {+ Host: `127.0.0.1:${rig.port}`,+ 'X-Forwarded-For': '203.0.113.7',+ }),+ ).resolves.toBe('closed');+ });++ test('tunnel Host without remote enabled is refused (no forwarding headers needed)', async () => {+ const rig = await bootRemoteRig({});+ const res = await raw(rig.port, {+ method: 'POST',+ path: '/mcp',+ headers: { host: PUBLIC_HOST },+ });+ expect(res.status).toBe(403);+ });+});++describe('remote enabled — UI over the same port', () => {+ const shell = (+ req: import('node:http').IncomingMessage,+ res: import('node:http').ServerResponse,+ _next: () => void,+ ): void => {+ res.setHeader('Content-Type', 'text/html');+ res.end(`SHELL ${req.url ?? ''}`);+ };++ test('the shell serves at / and /assets/* under the tunnel Host', async () => {+ const rig = await bootRemoteRig({ url: PUBLIC_URL }, { reactShellMiddleware: shell });+ const root = await raw(rig.port, { path: '/', headers: TUNNEL_HEADERS });+ expect(root.status).toBe(200);+ expect(root.body).toContain('SHELL /');+ const asset = await raw(rig.port, { path: '/assets/app.js', headers: TUNNEL_HEADERS });+ expect(asset.status).toBe(200);+ // /mcp stays MCP — the shell never shadows it.+ const mcp = await raw(rig.port, { method: 'POST', path: '/mcp', headers: TUNNEL_HEADERS });+ expect(mcp.body).not.toContain('SHELL');+ });++ test('the shell is refused under a wrong Host', async () => {+ const rig = await bootRemoteRig({ url: PUBLIC_URL }, { reactShellMiddleware: shell });+ const res = await raw(rig.port, { path: '/', headers: { host: 'evil.example.com' } });+ expect(res.status).toBe(403);+ });++ test('a browser Origin from the tunnel host is admitted on /mcp', async () => {+ const rig = await bootRemoteRig({ url: PUBLIC_URL });+ const names = await listToolNames(rig.port, {+ host: PUBLIC_HOST,+ origin: `https://${PUBLIC_HOST}`,+ });+ expect(names).toContain('search');+ });++ test('a foreign browser Origin is still refused on /mcp', async () => {+ const rig = await bootRemoteRig({ url: PUBLIC_URL });+ const res = await raw(rig.port, {+ method: 'POST',+ path: '/mcp',+ headers: { host: PUBLIC_HOST, origin: 'https://evil.example.com' },+ });+ expect(res.status).toBe(403);+ });+});diff --git a/packages/server/src/server-factory.test.ts b/packages/server/src/server-factory.test.tsindex 00a67964b..17cffdacd 100644--- a/packages/server/src/server-factory.test.ts+++ b/packages/server/src/server-factory.test.ts@@ -1984,7 +1984,45 @@ describe('createServer() — config-doc admission guard', () => {thrown = err;}expect(thrown).not.toBeNull();- expect((thrown as Error).message).toContain('loopback Host header');+ expect((thrown as Error).message).toContain('loopback or remote Host header');+ } finally {+ await server.destroy();+ }+ });++ test('config doc admits the tunnel public Host when remote access is enabled', async () => {+ const server = createServer({+ contentDir: tmpDir,+ projectDir: tmpDir,+ quiet: true,+ remotePublicHost: 'myproject.ngrok.app',+ });+ try {+ await server.ready;+ const guard = getConfigDocAdmissionGuard(server);+ await expect(+ guard.onAuthenticate(+ makePayload({+ documentName: '__config__/project',+ peer: '127.0.0.1',+ host: 'myproject.ngrok.app',+ }),+ ),+ ).resolves.not.toThrow();+ // The attacker-domain rejection is unchanged with a remote host configured.+ let thrown: unknown = null;+ try {+ await guard.onAuthenticate(+ makePayload({+ documentName: '__config__/project',+ peer: '127.0.0.1',+ host: 'attacker.example.com',+ }),+ );+ } catch (err) {+ thrown = err;+ }+ expect(thrown).not.toBeNull();} finally {await server.destroy();}@@ -2004,7 +2042,7 @@ describe('createServer() — config-doc admission guard', () => {thrown = err;}expect(thrown).not.toBeNull();- expect((thrown as Error).message).toContain('loopback Host header');+ expect((thrown as Error).message).toContain('loopback or remote Host header');} finally {await server.destroy();}@@ -2049,7 +2087,7 @@ describe('createServer() — config-doc admission guard', () => {thrown = err;}expect(thrown).not.toBeNull();- expect((thrown as Error).message).toContain('loopback Host header');+ expect((thrown as Error).message).toContain('loopback or remote Host header');} finally {await server.destroy();}diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.tsindex 307bdf2a2..a7e18d759 100644--- a/packages/server/src/server-factory.ts+++ b/packages/server/src/server-factory.ts@@ -164,6 +164,7 @@ import {import { loadPrincipal } from './principal.ts';import { RecentlyRemovedDocs } from './recently-removed-docs.ts';import { reconcile } from './reconciliation.ts';+import { hostHeaderMatchesPublicHost } from './remote-access.ts';import { runRemovalRedirectGuard } from './removal-redirect-guard.ts';import { loadRemovedDocsJournal, saveRemovedDocsJournal } from './removed-docs-journal.ts';import {@@ -206,6 +207,12 @@ import { trustSystemCertificates } from './trust-system-ca.ts';import { cleanupOrphanUploadTempfiles } from './upload-streaming.ts';export interface ServerOptions {+ /**+ * The tunnel's public host when remote access is enabled — threaded into+ * the API extension so the browser-Origin allowlists admit the remote+ * SPA's origin. See `ApiExtensionOptions.remotePublicHost`.+ */+ remotePublicHost?: string;port?: number;host?: string;contentDir: string;@@ -1714,9 +1721,12 @@ export function createServer(options: ServerOptions): ServerInstance {(headersBag && typeof headersBag.get === 'function' ? headersBag.get('host') : null) ??req.headers?.host ??undefined;- if (!isAllowedWorkspaceHostHeader(host)) {+ const remoteHostOk =+ options.remotePublicHost !== undefined &&+ hostHeaderMatchesPublicHost(host, options.remotePublicHost);+ if (!isAllowedWorkspaceHostHeader(host) && !remoteHostOk) {throw new Error(- `config-doc admission requires loopback Host header (host=${host ?? '<absent>'}, doc=${payload.documentName})`,+ `config-doc admission requires a loopback or remote Host header (host=${host ?? '<absent>'}, doc=${payload.documentName})`,);}},@@ -1826,6 +1836,7 @@ export function createServer(options: ServerOptions): ServerInstance {const apiExtension = createApiExtension({hocuspocus,durabilityState,+ remotePublicHost: options.remotePublicHost,sessionManager,contentDir,contentFilter,