Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(ok): make --remote a thin alias over server.* keys (PRD-7902) (#3402)
omar-inkeep9c9030df75b8
diff --git a/.changeset/remote-alias-over-server-keys.md b/.changeset/remote-alias-over-server-keys.mdnew file mode 100644index 000000000..9b8af71d9--- /dev/null+++ b/.changeset/remote-alias-over-server-keys.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": minor+---++`ok start --remote <url>` is now a thin alias over the ratified `server.*` networking keys: it expands to `server.publicUrl` (the tunnel URL), `server.allowExternal` consent, and a loopback bind, flowing through the same resolution path every other exposure route uses — the dedicated remote-access machinery is gone. Behavior over the tunnel is unchanged (same Host/Origin admission, same stable port default, idle-shutdown stays off), with one improvement: issued URLs (MCP `serverUrl`, `preview_url`) now name the tunnel URL instead of an unreachable loopback address. The flag is deprecated and prints a notice pointing at its successors; a new `--public-url <url>` flag sets `server.publicUrl` for a single run. `--remote` and the `remote.*` config keys keep working for now and will be removed in a later release.diff --git a/docs/content/deploy/remote-access.mdx b/docs/content/deploy/remote-access.mdxindex bcbbe16d3..b5ffc4e7a 100644--- a/docs/content/deploy/remote-access.mdx+++ b/docs/content/deploy/remote-access.mdx@@ -5,6 +5,10 @@ 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.+<Callout type="warn">+`--remote` is deprecated. It still works exactly as documented below, but it is now an alias for the general networking keys: `OK_IDLE_SHUTDOWN=off OK_ALLOW_EXTERNAL=1 ok start --public-url <url>` is the equivalent invocation (or set `server.publicUrl`, `server.allowExternal`, and `server.idleShutdown: off` in config — without `idleShutdown: off` the server shuts down after 30 idle minutes even while remote agents are using it, because the idle timer only counts editor connections). Prefer that spelling for new setups — `--remote` will be removed in a later release.+</Callout>+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 machinediff --git a/docs/content/reference/cli.mdx b/docs/content/reference/cli.mdxindex 65292cc08..8da6af5a4 100644--- a/docs/content/reference/cli.mdx+++ b/docs/content/reference/cli.mdx@@ -118,7 +118,8 @@ Serve this project's web UI and `/mcp` endpoint to your other devices through an| 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` |+| `ok start --public-url <url>` | Declare the canonical external origin clients dial (sets `server.publicUrl` for this run) — its host joins the Host/Origin allowlists and issued URLs. External exposure additionally requires consent (`OK_ALLOW_EXTERNAL=1` or `server.allowExternal`). For remote MCP use also set `OK_IDLE_SHUTDOWN=off` — the idle timer only counts editor (WS) connections and would stop the server under a live remote agent |+| `ok start --remote [url]` | Deprecated alias for `--public-url <url>` plus `OK_ALLOW_EXTERNAL` consent on a loopback bind. Starts 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 commandsdiff --git a/docs/content/reference/configuration.mdx b/docs/content/reference/configuration.mdxindex 40389abac..ffbb3c9ad 100644--- a/docs/content/reference/configuration.mdx+++ b/docs/content/reference/configuration.mdx@@ -47,8 +47,13 @@ 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). |+| `server.bind` | list of addresses | `["127.0.0.1"]` | project | Addresses the server binds, e.g. `[127.0.0.1]` or `[0.0.0.0]`. The loopback default keeps everything off-machine out. A non-loopback bind additionally requires the `server.allowExternal` consent interlock. Lists replace, never merge. Env: `OK_BIND` (space-separated). Read at server start. |+| `server.port` | number | (unset) | project | TCP port the server listens on. Unset = a local start picks a free port dynamically (deployment platforms inject `PORT` instead). Supersedes `remote.port`, which is still read while this key is absent. Read at server start. |+| `server.publicUrl` | string | (unset) | project | Canonical external origin the server is reached at, e.g. `https://kb.example.com` — its host joins the Host/Origin allowlists and issued URLs. Setting it declares external exposure, which additionally requires the `server.allowExternal` consent interlock. Supersedes `remote.url` (still read while this key is absent). Env: `OK_PUBLIC_URL`; flag: `ok start --public-url <url>`. Read at server start. |+| `server.allowExternal` | boolean | `false` | project-local | Exposure consent interlock: a non-loopback `server.bind` (or external requests behind a proxy declared via `server.publicUrl`) is refused without it. Per-machine — consent never travels via git, clone, or share; containers consent via `OK_ALLOW_EXTERNAL=1` instead. There is no server-side auth: restrict who can reach the server at the edge. |+| `server.idleShutdown` | `"off"` or duration (`90s`, `30m`, `2h`) | derived: `30m` loopback-only, `off` otherwise | project-local | Shut the server down after this long with no connected editor (WebSocket) clients. Remote MCP sessions are plain HTTP the timer cannot see — set `off` (or `OK_IDLE_SHUTDOWN=off`) when remote agents use the server, or it tears down under them mid-session. |+| `remote.url` | string | (unset) | project | Superseded by `server.publicUrl` (read only while that key is absent). 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 the deprecated `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 | Superseded by `server.port` (read only while that key is absent). 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. || `editor.previewTabs` | boolean | `true` | user | Reuse one replaceable preview tab for single clicks in the Files tree and Skills sidebar, so browsing does not accumulate tabs. Double-click the tab title, pin it, or choose **Keep open** from its context menu to make it permanent. Set `false` to open every click in its own tab. Rename transitions still reuse the current tab; back/forward navigation focuses the target's existing tab, or opens a permanent one when it is no longer open. A personal preference; toggle it from **Settings → Preferences → Preview tabs**. || `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"**. |diff --git a/packages/cli/src/commands/start.test.ts b/packages/cli/src/commands/start.test.tsindex 7eb600531..35670bc66 100644--- a/packages/cli/src/commands/start.test.ts+++ b/packages/cli/src/commands/start.test.ts@@ -5,9 +5,16 @@ import { request as httpRequest } from 'node:http';import { hostname, tmpdir } from 'node:os';import { join, resolve } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';-import { idleShutdownToMs, LOCAL_DIR } from '@inkeep/open-knowledge-core';+import {+ applyConfigOverlay,+ idleShutdownToMs,+ LOCAL_DIR,+ requiresExternalConsent,+ resolveEnvConfigLayer,+ resolveServerRuntimeConfig,+} from '@inkeep/open-knowledge-core';import { type Config, ConfigSchema } from '@inkeep/open-knowledge-server';-import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import {awaitUiSiblingPort,type BootedStartServer,@@ -18,6 +25,7 @@ import {connectUiSibling,decideUiSpawn,deriveServerProcessTitle,+ expandRemoteAlias,formatServerReuseNotice,formatShutdownNotice,isLoopbackHost,@@ -25,12 +33,14 @@ import {OkDirMissingError,parseIdleShutdownFlag,parseOnlyModule,+ parsePublicUrlFlag,resolveBundledReactShellDir,resolveCollabPort,resolveHost,resolveServerReuse,resolveStartConsoleLevel,resolveStartShellDir,+ scopeRemoteAliasConsentToBind,shouldConnectToExistingServer,shouldOpenBrowser,shouldWarnHostOverridesMultiBind,@@ -93,6 +103,134 @@ describe('coerceRemoteBindHost', () => {});});+describe('expandRemoteAlias — --remote is a thin alias over the server.* keys', () => {+ const TUNNEL_URL = 'https://myproject.ngrok.app';++ /** Narrow to the ok:true arm or fail the test with a useful message. */+ function expectExpanded(alias: ReturnType<typeof expandRemoteAlias>) {+ if (alias === null || !alias.ok) {+ throw new Error(`expected a successful expansion, got ${JSON.stringify(alias)}`);+ }+ return alias;+ }++ test('expands to exactly the ratified keys — publicUrl + allowExternal + idleShutdown off', () => {+ expect(expandRemoteAlias(TUNNEL_URL, undefined)).toEqual({+ ok: true,+ url: TUNNEL_URL,+ serverOverlay: { publicUrl: TUNNEL_URL, allowExternal: true, idleShutdown: 'off' },+ });+ });++ test('resolves an identical server runtime to the equivalent --public-url invocation', () => {+ const config = makeTestConfig();+ const alias = expectExpanded(expandRemoteAlias(TUNNEL_URL, undefined));+ // What runStartCommand overlays for `ok start --remote <url>` …+ const aliasRuntime = resolveServerRuntimeConfig(+ applyConfigOverlay(config, {+ server: { bind: ['127.0.0.1'], ...alias.serverOverlay },+ }) as Config,+ );+ // … versus the ratified spelling of the same deployment:+ // `OK_ALLOW_EXTERNAL=1 OK_IDLE_SHUTDOWN=off ok start --public-url <url> --bind 127.0.0.1`.+ const env = resolveEnvConfigLayer({ OK_ALLOW_EXTERNAL: '1', OK_IDLE_SHUTDOWN: 'off' });+ const explicitRuntime = resolveServerRuntimeConfig(+ applyConfigOverlay(applyConfigOverlay(config, env.layer), {+ server: { bind: ['127.0.0.1'], publicUrl: TUNNEL_URL },+ }) as Config,+ );+ expect(aliasRuntime).toEqual(explicitRuntime);+ // The load-bearing shape: successor-key publicUrl (drives the ingress+ // policy + issued URLs), consent armed, loopback-only bind.+ expect(aliasRuntime.publicUrlSource).toBe('server');+ expect(aliasRuntime.allowExternal).toBe(true);+ expect(aliasRuntime.loopbackOnly).toBe(true);+ expect(aliasRuntime.idleShutdown).toBe('off');+ });++ test('a dormant remote.url in config does NOT arm anything without the flag', () => {+ expect(expandRemoteAlias(undefined, TUNNEL_URL)).toBeNull();+ expect(expandRemoteAlias(false, TUNNEL_URL)).toBeNull();+ });++ test('bare --remote pulls the url from config; an inline url wins over config', () => {+ expect(expectExpanded(expandRemoteAlias(true, TUNNEL_URL)).url).toBe(TUNNEL_URL);+ expect(expectExpanded(expandRemoteAlias('https://inline.example.com', TUNNEL_URL)).url).toBe(+ 'https://inline.example.com',+ );+ });++ test('trailing slashes are stripped, matching the legacy resolver', () => {+ const alias = expectExpanded(expandRemoteAlias(`${TUNNEL_URL}/`, undefined));+ expect(alias.url).toBe(TUNNEL_URL);+ expect(alias.serverOverlay.publicUrl).toBe(TUNNEL_URL);+ });++ test('missing url anywhere refuses with the fix instruction', () => {+ const alias = expandRemoteAlias(true, undefined);+ expect(alias?.ok).toBe(false);+ if (alias === null || alias.ok) throw new Error('expected refusal');+ expect(alias.errorMessage).toContain('--remote requires a public tunnel URL');+ });++ test('non-URL and plain-http urls refuse — the legacy https-only rule is preserved', () => {+ const garbage = expandRemoteAlias('not a url', undefined);+ if (garbage === null || garbage.ok) throw new Error('expected refusal');+ expect(garbage.errorMessage).toContain('not a valid URL');+ const http = expandRemoteAlias('http://myproject.ngrok.app', undefined);+ if (http === null || http.ok) throw new Error('expected refusal');+ expect(http.errorMessage).toContain('must be https');+ });+});++describe('scopeRemoteAliasConsentToBind — self-consent is loopback-scoped', () => {+ const overlay = {+ publicUrl: 'https://myproject.ngrok.app',+ allowExternal: true,+ idleShutdown: 'off',+ } as const;++ test('a loopback bind keeps the alias self-consent', () => {+ expect(scopeRemoteAliasConsentToBind(overlay, ['127.0.0.1'])).toEqual(overlay);+ expect(scopeRemoteAliasConsentToBind(overlay, ['::1'])).toEqual(overlay);+ });++ test('a non-loopback bind drops allowExternal so the interlock refuses as it did pre-alias', () => {+ // `ok start --remote <url>` on a project with `server.bind: [<lan-ip>]`+ // exited 78 before the alias (the flag never consented to a bind that is+ // reachable AROUND the tunnel). The scoped overlay must not smuggle that+ // consent in.+ const scoped = scopeRemoteAliasConsentToBind(overlay, ['192.168.1.5']);+ expect('allowExternal' in scoped).toBe(false);+ expect(scoped.publicUrl).toBe(overlay.publicUrl);+ const runtime = resolveServerRuntimeConfig(+ applyConfigOverlay(makeTestConfig(), {+ server: { bind: ['192.168.1.5'], ...scoped },+ }) as Config,+ );+ expect(runtime.allowExternal).toBe(false);+ expect(requiresExternalConsent(runtime)).toBe(true);+ });++ test('a mixed loopback + non-loopback bind list also drops allowExternal (every, not some)', () => {+ expect(+ 'allowExternal' in scopeRemoteAliasConsentToBind(overlay, ['127.0.0.1', '192.168.1.5']),+ ).toBe(false);+ });+});++describe('parsePublicUrlFlag', () => {+ test('accepts http and https origins (http covers tailnet/LAN deployments)', () => {+ expect(parsePublicUrlFlag('https://kb.example.com')).toBe('https://kb.example.com');+ expect(parsePublicUrlFlag('http://laptop.tail:55222')).toBe('http://laptop.tail:55222');+ });++ test('rejects garbage and non-http(s) schemes', () => {+ expect(() => parsePublicUrlFlag('not a url')).toThrow(/not a valid URL/);+ expect(() => parsePublicUrlFlag('ftp://kb.example.com')).toThrow(/http\(s\) origin/);+ });+});+describe('formatShutdownNotice', () => {test('SIGINT includes the headline, the wait notice, and the force-quit hint', () => {const lines = formatShutdownNotice('SIGINT');@@ -2775,4 +2913,72 @@ describe('startCommand — flag-conflict guards (exit 2)', () => {expect(code).toBe(2);expect(stderr).toContain('--remote');});++ test('--single-file + --remote exits 2 (no consented root to expose)', async () => {+ const { code, stderr } = await captureGuard([+ '--single-file',+ '/tmp/note.md',+ '--remote',+ 'https://tunnel.example.com',+ ]);+ expect(code).toBe(2);+ expect(stderr).toContain('--single-file');+ });++ test('--remote + --public-url exits 2 (the alias IS a public-url; one must win)', async () => {+ const { code, stderr } = await captureGuard([+ '--remote',+ 'https://tunnel.example.com',+ '--public-url',+ 'https://kb.example.com',+ ]);+ expect(code).toBe(2);+ expect(stderr).toContain('--public-url');+ });++ /**+ * The pre-boot `--remote` refusals print via console.warn/console.error+ * (vitest intercepts the console, so `captureGuard`'s stderr stub never+ * sees them) — collect both streams via spies alongside the exit code.+ */+ async function captureRemoteRefusal(+ argv: string[],+ ): Promise<{ code: number | undefined; output: string }> {+ const lines: string[] = [];+ const record = (...args: unknown[]) => {+ lines.push(args.map(String).join(' '));+ };+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(record);+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(record);+ try {+ const { code, stderr } = await captureGuard(argv);+ return { code, output: `${stderr}\n${lines.join('\n')}` };+ } finally {+ warnSpy.mockRestore();+ errorSpy.mockRestore();+ }+ }++ test('--remote without a url anywhere exits 78 and names the successor keys in the deprecation notice', async () => {+ const { code, output } = await captureRemoteRefusal(['--remote']);+ expect(code).toBe(78);+ expect(output).toContain('--remote requires a public tunnel URL');+ // The deprecation notice fires even on the refusal path — EXACTLY once —+ // and names every key the alias pins (--public-url / --bind /+ // OK_ALLOW_EXTERNAL / OK_IDLE_SHUTDOWN=off), so an operator learns the+ // full ratified spelling from the same run that errors. Omitting the+ // idle-shutdown key would hand migrators a server that tears itself down+ // after 30 idle minutes under a live remote MCP client.+ expect(output.split('--remote is deprecated').length - 1).toBe(1);+ expect(output).toContain('--public-url');+ expect(output).toContain('--bind');+ expect(output).toContain('OK_ALLOW_EXTERNAL');+ expect(output).toContain('OK_IDLE_SHUTDOWN=off');+ });++ test('--remote with a plain-http url exits 78 (legacy https-only rule preserved)', async () => {+ const { code, output } = await captureRemoteRefusal(['--remote', 'http://tunnel.example.com']);+ expect(code).toBe(78);+ expect(output).toContain('must be https');+ });});diff --git a/packages/cli/src/commands/start.ts b/packages/cli/src/commands/start.tsindex b1e393a02..faa568afe 100644--- a/packages/cli/src/commands/start.ts+++ b/packages/cli/src/commands/start.ts@@ -41,6 +41,7 @@ import {EnvVarError,IDLE_SHUTDOWN_DURATION_RE,idleShutdownToMs,+ isLoopbackOnlyBind,resolveEnvConfigLayer,resolveServerRuntimeConfig,type ServerRuntimeConfig,@@ -255,6 +256,105 @@ export function coerceRemoteBindHost(return { host, coerced: false };}+/** The `server.*` keys `--remote` expands into — nothing beyond the ratified surface. */+interface RemoteAliasServerOverlay {+ publicUrl: string;+ allowExternal: true;+ idleShutdown: 'off';+}++export type RemoteAliasExpansion =+ | { ok: true; url: string; serverOverlay: RemoteAliasServerOverlay }+ | { ok: false; errorMessage: string };++/**+ * Scope the alias's self-consent to the topology it promises: a loopback+ * bind where the tunnel's edge auth is the only ingress. A non-loopback bind+ * (a tailnet/LAN address from `server.bind`, `OK_BIND`, `HOST`, or a `--bind`+ * shape `coerceRemoteBindHost` does not recognize) is reachable AROUND the+ * tunnel, so `--remote` must not consent to it on the operator's behalf —+ * without this, the exposure interlock that refused `--remote` + a+ * non-loopback bind before the alias would be silently satisfied. Dropping+ * `allowExternal` here lets the interlock refuse exactly as before;+ * `OK_ALLOW_EXTERNAL=1` remains the sanctioned override.+ */+export function scopeRemoteAliasConsentToBind(+ serverOverlay: RemoteAliasServerOverlay,+ bindList: readonly string[],+): { publicUrl: string; idleShutdown: 'off'; allowExternal?: true } {+ if (isLoopbackOnlyBind(bindList)) return serverOverlay;+ return { publicUrl: serverOverlay.publicUrl, idleShutdown: serverOverlay.idleShutdown };+}++/**+ * `--remote [url]` is a deprecated thin alias over the ratified `server.*`+ * networking keys: it expands to `server.publicUrl` = the tunnel url (its+ * host joins the Host/Origin allowlists), a loopback bind (tunnels proxy to+ * `127.0.0.1` — the deployer's tunnel agent covers ingress, see+ * `coerceRemoteBindHost`), and `server.allowExternal` consent, which+ * satisfies the exposure interlock and the forwarded-header tripwire. Plus+ * `server.idleShutdown: 'off'`: remote MCP sessions arrive as plain HTTP,+ * and the idle timer counts /collab WS clients only — it would tear the+ * server down under a live remote client. Networking-only — the alias+ * carries no auth semantics; restricting who reaches the URL stays the+ * tunnel's job (edge auth).+ *+ * Returns `null` when the flag is absent. `ok: false` carries the exit-78+ * message: a missing url is unusable, and the legacy https-only rule is kept+ * through the deprecation window (a tunnel URL over plain http would be+ * credentials-in-the-clear).+ */+export function expandRemoteAlias(+ remoteFlag: string | boolean | undefined,+ configRemoteUrl: string | undefined,+): RemoteAliasExpansion | null {+ if (remoteFlag === undefined || remoteFlag === false) return null;+ const url = typeof remoteFlag === 'string' ? remoteFlag : configRemoteUrl;+ if (url === undefined || url === '') {+ return {+ ok: false,+ errorMessage:+ '--remote requires a public tunnel URL — pass it (`ok start --remote https://<your-tunnel-host>`) or set remote.url in .ok/config.yml.',+ };+ }+ let parsed: URL;+ try {+ parsed = new URL(url);+ } catch {+ return { ok: false, errorMessage: `remote.url is not a valid URL: ${url}` };+ }+ if (parsed.protocol !== 'https:') {+ return {+ ok: false,+ errorMessage: `remote.url must be https — it is the public tunnel URL remote clients connect to (got: ${url})`,+ };+ }+ const normalizedUrl = url.replace(/\/+$/, '');+ return {+ ok: true,+ url: normalizedUrl,+ serverOverlay: { publicUrl: normalizedUrl, allowExternal: true, idleShutdown: 'off' },+ };+}++/**+ * Validator for Commander's `--public-url` parser — the flag-layer setter for+ * `server.publicUrl`, matching the schema leaf's http(s)-origin shape so a+ * flag value can never smuggle in what the config file would reject.+ */+export function parsePublicUrlFlag(value: string): string {+ let parsed: URL;+ try {+ parsed = new URL(value);+ } catch {+ throw new InvalidArgumentError(`--public-url is not a valid URL: ${value}`);+ }+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {+ throw new InvalidArgumentError(`--public-url must be an http(s) origin (got: ${value})`);+ }+ return value;+}+/** Hard cap on the project-name suffix in `process.title` to keep `ps`/Activity Monitor lines readable. */const PROCESS_TITLE_PROJECT_NAME_MAX = 64;@@ -963,11 +1063,6 @@ 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 {@@ -1251,7 +1346,6 @@ 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,@@ -1424,12 +1518,15 @@ interface StartCommandOptions {* 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.+ * From `--remote [url]`: deprecated alias over the `server.*` keys — see+ * `expandRemoteAlias`. `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;+ /** From `--public-url <url>`: flag-layer `server.publicUrl` for this run. */+ publicUrl?: string;}/**@@ -1521,13 +1618,9 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)// 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;+ // for this run without persisting. The flag is a deprecated thin alias over+ // the ratified `server.*` keys — `expandRemoteAlias` holds the expansion.+ const remoteFlagSet = opts.remote !== undefined && opts.remote !== false;// Set the process title as early as possible so Activity Monitor and// `ps -ax | grep open-knowledge-server` show each running server by@@ -1536,31 +1629,38 @@ 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.',+ // Deprecation notice first, even when the expansion below refuses — the+ // operator should learn the successor spelling from the same run that+ // errors. Networking-only alias; removal ships separately after a soak.+ if (remoteFlagSet) {+ console.warn(+ warning(+ '--remote is deprecated — use `OK_IDLE_SHUTDOWN=off OK_ALLOW_EXTERNAL=1 ok start --public-url <url>` instead (add --bind to serve a non-loopback address; keep OK_IDLE_SHUTDOWN=off — the idle timer only counts WS clients and would tear the server down under a live remote MCP client). The flag now just expands to those server.* keys and will be removed in a later release.',),);+ }++ // Fail loud BEFORE booting: --remote with no url anywhere (or a non-https+ // url) is unusable, and the error message is the fix instruction.+ const aliasResult = expandRemoteAlias(opts.remote, config.remote?.url);+ if (aliasResult !== null && !aliasResult.ok) {+ console.error(error(aliasResult.errorMessage));process.exit(78);}+ const remoteAlias = aliasResult?.ok ? aliasResult : null;+ const remoteEnabled = remoteAlias !== null;// 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) {+ if (remoteAlias !== null) {console.warn(warning(['','⚠ REMOTE ACCESS ENABLED — no server-side authentication.',- ` Anyone who can reach ${activeConfig.remote?.url} has FULL control of this`,+ ` Anyone who can reach ${remoteAlias.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.',@@ -1586,7 +1686,7 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)for (const diag of envLayer.diagnostics) {console.warn(warning(`[config] ${diag.message}`));}- const envConfig = applyConfigOverlay(activeConfig, envLayer.layer) as Config;+ const envConfig = applyConfigOverlay(config, envLayer.layer) as Config;// Bind precedence: --bind / deprecated --host flags > ratified OK_BIND >// legacy HOST env > server.bind file layer > loopback default. The resolved@@ -1641,8 +1741,31 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)// request. Without this, `HOST=0.0.0.0 ok start --remote` coerces to// loopback yet still trips ExposureConsentError off the uncoerced list.const bindList = remoteEnabled ? [host] : requestedBind;+ // The flag-layer overlay, applied ABOVE the env layer: the resolved bind+ // list, the `--remote` alias expansion (publicUrl + allowExternal ++ // idleShutdown 'off' — the SAME server.* resolution path any other exposure+ // route uses), and `--public-url`. Nothing here is remote-specific+ // machinery; the alias is only these keys. Self-consent is loopback-scoped+ // (see scopeRemoteAliasConsentToBind) — a non-loopback bind under --remote+ // still needs explicit consent, so the interlock refusal below matches the+ // pre-alias behavior.+ const aliasOverlay =+ remoteAlias !== null ? scopeRemoteAliasConsentToBind(remoteAlias.serverOverlay, bindList) : {};+ if (remoteAlias !== null && !('allowExternal' in aliasOverlay)) {+ console.warn(+ warning(+ `--remote does not consent to exposing a non-loopback bind (${bindList.join(', ')}) — the tunnel is the only ingress the alias vouches for. Consent explicitly with OK_ALLOW_EXTERNAL=1 (or server.allowExternal in .ok/local/config.yml), or drop the non-loopback bind.`,+ ),+ );+ }const runtime: ServerRuntimeConfig = resolveServerRuntimeConfig(- applyConfigOverlay(envConfig, { server: { bind: bindList } }) as Config,+ applyConfigOverlay(envConfig, {+ server: {+ bind: bindList,+ ...aliasOverlay,+ ...(opts.publicUrl !== undefined ? { publicUrl: opts.publicUrl } : {}),+ },+ }) as Config,);// The consent warning, sibling to the --remote banner above. `allowExternal`@@ -1694,8 +1817,8 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)// inherit a dormant `remote.port` (set long ago for tunnel use); doing so// pins every local boot to that fixed port instead of a free dynamic one,// and two projects both carrying `remote.port` could never run at once.- const remotePort = resolveServerRuntimeConfig(activeConfig).port;- const localPort = activeConfig.server?.port;+ const remotePort = resolveServerRuntimeConfig(config).port;+ const localPort = config.server?.port;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 (${remotePort ?? DEFAULT_REMOTE_PORT}). Pass --port to override deliberately.`,@@ -1748,7 +1871,7 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)let booted: BootedStartServer;try {booted = await bootStartServer({- config: activeConfig,+ config,cwd,host,port,@@ -1769,12 +1892,16 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)// the resolver's covers OK_IDLE_SHUTDOWN, the config leaf, and the// bind-derived default ('30m' loopback-only, 'off' exposed). Converted to// ms (null for 'off') at this single boundary. The flag stays a string- // through Commander on purpose — see parseIdleShutdownFlag.- idleThresholdMs: idleShutdownToMs(opts.idleShutdown ?? runtime.idleShutdown),+ // through Commander on purpose — see parseIdleShutdownFlag. Under+ // --remote the alias overlay pins 'off' and the flag is ignored — the+ // legacy remote flow always disabled the idle timer, and a remote MCP+ // client is plain HTTP the /collab-counting timer can't see.+ idleThresholdMs: idleShutdownToMs(+ (remoteEnabled ? undefined : opts.idleShutdown) ?? runtime.idleShutdown,+ ),serverRuntime: runtime,...(opts.singleFile ? { singleFile: opts.singleFile } : {}),...(opts.projectDir ? { projectDir: opts.projectDir } : {}),- ...(remoteEnabled ? { enableRemote: true } : {}),});} catch (err) {// Project not initialized — clean message, no stack trace.@@ -1795,16 +1922,9 @@ 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);- }-// Exposure without consent (non-loopback bind or publicUrl set while// server.allowExternal is off) — the interlock's message IS the one-line- // fix. EX_CONFIG, same contract as RemoteConfigError.+ // fix. EX_CONFIG, same contract as the other config-shaped boot errors.if (err instanceof serverModule.ExposureConsentError) {console.error(error(err.message));process.exit(78);@@ -2227,9 +2347,14 @@ export function startCommand(getConfig: () => Config): Command {'--project-dir <dir>','Throwaway project root for --single-file (where ephemeral .ok/ state lives)',)+ .option(+ '--public-url <url>',+ 'Canonical external origin clients dial (sets server.publicUrl for this run) — its host joins the Host/Origin allowlists and issued URLs. External exposure additionally requires consent (OK_ALLOW_EXTERNAL=1 or server.allowExternal).',+ parsePublicUrlFlag,+ ).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.',+ 'Deprecated alias: expands to --public-url <url> + OK_ALLOW_EXTERNAL consent on a loopback bind. Serves through a tunnel 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();@@ -2240,6 +2365,27 @@ export function startCommand(getConfig: () => Config): Command {process.exit(2);}+ // `--remote` IS a `--public-url` (plus consent) — combining them would+ // make one silently win. Fail loud; pass one.+ if (opts.publicUrl !== undefined && opts.remote !== undefined && opts.remote !== false) {+ process.stderr.write(+ "error: option '--remote' cannot be combined with '--public-url' (--remote is a deprecated alias that sets server.publicUrl)\n",+ );+ process.exit(2);+ }++ // Ephemeral single-file mode has no project and no consented root — the+ // legacy remote flow refused to arm there (while still printing an+ // "enabled" banner). Now that --remote expands into real exposure+ // consent, refuse the combination loudly instead of exposing a+ // throwaway root.+ if (opts.singleFile !== undefined && opts.remote !== undefined && opts.remote !== false) {+ process.stderr.write(+ "error: option '--single-file' cannot be combined with '--remote' — ephemeral single-file mode has no project and no consented root to serve remotely\n",+ );+ process.exit(2);+ }+// `--only server` promises "no UI module" — an explicit shell dir// contradicts it. Fail loud rather than pick a winner silently.if (opts.only === 'server' && opts.reactShellDistDir !== undefined) {@@ -2312,6 +2458,8 @@ export function startCommand(getConfig: () => Config): Command {if (opts.serverUrl !== undefined) ignored.push('--server-url');if (opts.idleShutdown !== undefined) ignored.push('--idle-shutdown');if (opts.openBrowser === false) ignored.push('--no-open-browser');+ if (opts.publicUrl !== undefined) ignored.push('--public-url');+ if (opts.remote !== undefined && opts.remote !== false) ignored.push('--remote');if (ignored.length > 0) {// Debug-level surface; reuse the existing program log-level// gate (--log-level=debug). Inline check to avoid a logger dep.diff --git a/packages/core/src/config/resolve-server-config.ts b/packages/core/src/config/resolve-server-config.tsindex 5c755a588..7580d4114 100644--- a/packages/core/src/config/resolve-server-config.ts+++ b/packages/core/src/config/resolve-server-config.ts@@ -143,7 +143,7 @@ export function resolveServerRuntimeConfig(config: Config | undefined): ServerRuconst loopbackOnly = isLoopbackOnlyBind(bind);// Alias-reads: the successor key wins whenever present; an empty-string- // `remote.url` reads as unset (matching `resolveRemoteAccess`).+ // `remote.url` reads as unset (matching the CLI's `expandRemoteAlias`).const port = server?.port ?? remote?.port;const legacyUrl = remote?.url === '' ? undefined : remote?.url;const publicUrl = server?.publicUrl ?? legacyUrl;diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.tsindex 60db87fe0..1d4c4e61c 100644--- a/packages/core/src/config/schema.ts+++ b/packages/core/src/config/schema.ts@@ -103,8 +103,8 @@ const HTTP_URL_SCHEME_RE = /^https?:\/\//;/*** Fallback listen port when remote access is enabled but `remote.port` is- * unset. Lives in the READERS (`resolveRemoteAccess`, the CLI port- * resolution), not as a zod `.default()` — the successor `server.port` is+ * unset. Lives in the READER (the CLI's remote-mode port resolution), not as+ * a zod `.default()` — the successor `server.port` is* alias-read from `remote.port` only when unset, and a schema-baked default* would make "unset" undetectable in a parsed config.*/diff --git a/packages/server/src/api-origin.test.ts b/packages/server/src/api-origin.test.tsindex 0fdbb36c2..b96742011 100644--- a/packages/server/src/api-origin.test.ts+++ b/packages/server/src/api-origin.test.ts@@ -23,18 +23,12 @@ describe('API origin guards', () => {});});-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);+// Tunnel/public origins are an ingress-policy concern now — `isOriginAdmitted`+// admits the declared `server.publicUrl` origin (see ingress-policy.test.ts);+// this helper stays loopback-only.+describe('isAllowedApiOrigin stays loopback-only', () => {+ test('refuses a tunnel origin — publicUrl admission lives in the ingress policy', () => {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);+ expect(isAllowedApiOrigin('http://localhost:5173')).toBe(true);});});diff --git a/packages/server/src/api-origin.ts b/packages/server/src/api-origin.tsindex 95e18e96e..39816dd29 100644--- a/packages/server/src/api-origin.ts+++ b/packages/server/src/api-origin.ts@@ -8,16 +8,8 @@* allowing the other only breaks the desktop renderer's WS surfaces* (`/collab/thread`) while its HTTP calls sail through.*/-import { originMatchesPublicHost } from './remote-access.ts';--export function isAllowedApiOrigin(origin: string, remotePublicHost?: string): boolean {+export function isAllowedApiOrigin(origin: 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.test.ts b/packages/server/src/boot.test.tsindex f9ca8426a..7759df06a 100644--- a/packages/server/src/boot.test.ts+++ b/packages/server/src/boot.test.ts@@ -1207,6 +1207,18 @@ describeEvenOnCI('bootServer — exposure consent interlock', () => {expect((err as Error | null)?.constructor.name).not.toBe('ExposureConsentError');});+ test('the --remote alias shape (publicUrl + consent on a loopback bind) boots outright', async () => {+ // `ok start --remote <url>` expands to exactly this runtime with NO+ // OK_ALLOW_EXTERNAL in the environment — the alias carries its own+ // consent. Historically the flag WAS the consent; if this shape ever+ // trips the interlock, every existing --remote user breaks at boot.+ const err = await tryBoot(+ { publicUrl: 'https://myproject.ngrok.app', allowExternal: true },+ true,+ );+ expect(err).toBeNull();+ });+test('an explicit (scope-correct) serverRuntime with consent admits a non-loopback bind', async () => {// The CLI path: consent resolved over all three layers and passed as an// explicit serverRuntime. Only this path can arm exposure for adiff --git a/packages/server/src/boot.ts b/packages/server/src/boot.tsindex 223fc3d53..1c5285fe9 100644--- a/packages/server/src/boot.ts+++ b/packages/server/src/boot.ts@@ -72,7 +72,6 @@ import { createMcpHttpHandler } from './mcp-http.ts';import { mountMcpAndApi, type ReadinessState } from './mcp-mount.ts';import { MissingOkConfigError } from './missing-ok-config-error.ts';import { createProjectRuntime, type ProjectRuntime } from './project-runtime.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 {@@ -246,14 +245,6 @@ 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;/*** The resolved `server.*` runtime (bind list, publicUrl, consent, derived* defaults). The CLI passes the fully-layered resolution (flags > env >@@ -580,23 +571,6 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {const attachUi = opts.attachUiSibling ?? true;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;-// The resolved server.* runtime. The CLI passes its fully-layered// resolution (flags > env > project-local > project > user). Direct// embedders (desktop utility, dev-server plugin, tests) fall back to a@@ -655,7 +629,8 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {// ONE ingress policy for the whole listener — HTTP gates, WS upgrade// admission, config-doc admission, and the local-op checks all consult this// object. Built from the resolved server.* runtime (consent, declared bind- // literals, publicUrl) plus the legacy remote shape.+ // literals, publicUrl); `ok start --remote` reaches here through the same+ // runtime, expanded by the CLI into these keys.//// The policy's admitted Host names come from `serverRuntime.bind` — the// DECLARED bind (which Host headers to accept) — NOT the physical@@ -668,7 +643,7 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {// `effectiveBindAddresses`. Different questions, deliberately different// sources; do NOT unify them (doing so drops declared-but-not-physically-// bound Hosts from the allowlist → spurious 403s).- const ingressPolicy = buildIngressPolicy({ serverRuntime, remoteAccess });+ const ingressPolicy = buildIngressPolicy({ serverRuntime });if (serverRuntime.allowExternal &&!serverRuntime.loopbackOnly &&@@ -874,10 +849,10 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {// Issued URLs (MCP serverUrl → preview_url, ACP thread bootstrap) name the// declared public origin when one is configured via the successor key —// that is the name clients actually type, and a loopback URL handed to a- // remote agent is unreachable. The remote-alias source stays with the- // legacy --remote flow (which never rewrote issued URLs), and the- // server.lock URL stays loopback below: the lock is same-machine discovery- // by contract.+ // remote agent is unreachable. The remote-alias source (a dormant+ // `remote.url` left in config with no `--remote` flag) never rewrites+ // issued URLs, and the server.lock URL stays loopback below: the lock is+ // same-machine discovery by contract.const issuedBaseUrl = (): string =>serverRuntime.publicUrlSource === 'server' && serverRuntime.publicUrl !== undefined? serverRuntime.publicUrl.replace(/\/+$/, '')@@ -1055,10 +1030,6 @@ 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)');- }-// Readiness snapshot for /readyz. Both callbacks handle the promise so a// failed async init cannot surface as an unhandled rejection here (the// caller still owns `ready` and observes the real error there).@@ -1119,8 +1090,8 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {// after 30 min of zero WS clients; the Electron utility disables it because// window-close IS the shutdown trigger.let idleHandle: IdleShutdownHandle | null = null;- if (idleMsOption !== null) {- const idleMs = idleMsOption ?? DEFAULT_IDLE_THRESHOLD_MS;+ if (opts.idleShutdownMs !== null) {+ const idleMs = opts.idleShutdownMs ?? DEFAULT_IDLE_THRESHOLD_MS;const idleHandler =opts.idleShutdownHandler ??((destroyFn) => async () => {diff --git a/packages/server/src/collaboration-host.test.ts b/packages/server/src/collaboration-host.test.tsindex 934e6183c..c8812282b 100644--- a/packages/server/src/collaboration-host.test.ts+++ b/packages/server/src/collaboration-host.test.ts@@ -177,17 +177,24 @@ describe('createCollaborationHost', () => {);});- test('uses remote access admission for bare collaboration upgrades', () => {+ test('uses the tunnel-shape admission (publicUrl + consent) for bare collaboration upgrades', () => {const log = createLog();const hocuspocus = createHocuspocus();const host = createCollaborationHost({hocuspocus,log,+ // The `ok start --remote` alias shape: declared public origin + consent+ // on a loopback bind.ingressPolicy: buildIngressPolicy({- remoteAccess: {- url: 'https://myproject.ngrok.app',- publicHost: 'myproject.ngrok.app',- port: 24_550,+ serverRuntime: {+ port: undefined,+ bind: ['127.0.0.1'],+ publicUrl: 'https://myproject.ngrok.app',+ publicUrlSource: 'server',+ allowExternal: true,+ openBrowser: false,+ idleShutdown: 'off',+ loopbackOnly: true,},}),});diff --git a/packages/server/src/collaboration-host.ts b/packages/server/src/collaboration-host.tsindex 06df8d8aa..818fc228f 100644--- a/packages/server/src/collaboration-host.ts+++ b/packages/server/src/collaboration-host.ts@@ -329,19 +329,20 @@ export function createCollaborationHost(options: CollaborationHostOptions): Coll// modes. A missing Origin (native / server-to-server clients) is// admitted — those are not CSWSH vectors and legitimately carry none.//- // (2) Peer + Host admission (`admitted()`) — only when EXPOSED (legacy- // `--remote` OR `allowExternal`). Pure-local keeps its historical- // ungated posture on this axis — a deliberate carve-out from the- // read-posture hardening that Host-gates `/api` reads and content-- // asset serving in every mode: WS upgrades are not reachable from a- // rebound page without an Origin header, and axis (1) refuses the- // foreign-Origin shape unconditionally. Under consent the loopback- // bind no longer implies a loopback peer, so `admitted()` (loopback +- // bind literals + publicUrl, identical to the HTTP API gate) keeps- // direct-IP access matching what `/api` accepts.+ // (2) Peer + Host admission (`admitted()`) — only when EXPOSED+ // (`allowExternal` consent, which `ok start --remote` expands into).+ // Pure-local keeps its historical ungated posture on this axis — a+ // deliberate carve-out from the read-posture hardening that+ // Host-gates `/api` reads and content-asset serving in every mode: WS+ // upgrades are not reachable from a rebound page without an Origin+ // header, and axis (1) refuses the foreign-Origin shape+ // unconditionally. Under consent the loopback bind no longer implies+ // a loopback peer, so `admitted()` (loopback + bind literals ++ // publicUrl, identical to the HTTP API gate) keeps direct-IP access+ // matching what `/api` accepts.const foreignOrigin =req.headers.origin !== undefined && !isOriginAdmitted(req.headers.origin, ingressPolicy);- const exposed = ingressPolicy.legacyRemote !== undefined || ingressPolicy.allowExternal;+ const exposed = ingressPolicy.allowExternal;if (foreignOrigin || (exposed && !admitted(req))) {log.debug({ url: req.url, host: req.headers.host, origin: req.headers.origin },diff --git a/packages/server/src/http/http-app.ts b/packages/server/src/http/http-app.tsindex e684f9c97..ad146a5c5 100644--- a/packages/server/src/http/http-app.ts+++ b/packages/server/src/http/http-app.ts@@ -66,10 +66,10 @@ export interface NativeApiHandle {* public tunnel with full local trust, decided by whether the tunnel* rewrites Host.*- * Gate 2 — with the legacy `--remote` flow armed, ONE admit decision covers- * every surface (trust-the-tunnel — see remote-access.ts): loopback socket +- * Host on the allowlist. Refusals are wrong-Host callers (DNS-rebound- * pages), not auth failures.+ * Gate 2 — with the surface EXPOSED (`server.allowExternal` consent, which+ * `ok start --remote` also expands into), ONE admit decision covers every+ * surface: an admitted peer + Host on the allowlist. Refusals are wrong-Host+ * callers (DNS-rebound pages), not auth failures.** `handler` is the caller's tag on the `ok.api.error.count` counter for* rejections ('mcp-mount' for the legacy dispatch, 'native-api-surface' for@@ -92,18 +92,18 @@ export function admitRequestSurface();return false;}- // Gate 2 runs whenever the surface is EXPOSED — legacy `--remote` OR- // `allowExternal` consent. This covers every surface the prelude fronts:- // `/mcp`, `/api/*`, the static shell, and project-mode content assets. The- // predicate is the consolidated one (loopback + bind literals + publicUrl),- // identical to the `/api` pipeline gate, so direct-IP access to the shell/- // content matches what the API admits. Pure-local (no exposure) skips this- // SURFACE-wide gate on purpose — the read-sensitive legs behind it carry- // their own always-on Host gates (the `/api` pipeline read gate, the- // content-serve gate in `asset-serve-middleware.ts`, the unconditional- // `/mcp` gate), while the SPA shell stays deliberately ungated: it is- // public bundle code, and a rebound attacker serves their own page anyway.- if (policy.legacyRemote !== undefined || policy.allowExternal) {+ // Gate 2 runs whenever the surface is EXPOSED (`allowExternal` consent).+ // This covers every surface the prelude fronts: `/mcp`, `/api/*`, the+ // static shell, and project-mode content assets. The predicate is the+ // consolidated one (loopback + bind literals + publicUrl), identical to the+ // `/api` pipeline gate, so direct-IP access to the shell/content matches+ // what the API admits. Pure-local (no exposure) skips this SURFACE-wide+ // gate on purpose — the read-sensitive legs behind it carry their own+ // always-on Host gates (the `/api` pipeline read gate, the content-serve+ // gate in `asset-serve-middleware.ts`, the unconditional `/mcp` gate),+ // while the SPA shell stays deliberately ungated: it is public bundle+ // code, and a rebound attacker serves their own page anyway.+ if (policy.allowExternal) {const host = Array.isArray(req.headers.host) ? req.headers.host[0] : req.headers.host;if (!isPeerAdmitted(req.socket.remoteAddress, policy) || !isHostAdmitted(host, policy)) {errorResponse(res, 403, 'urn:ok:error:host-not-allowed', 'Host header not allowed.', {diff --git a/packages/server/src/index.ts b/packages/server/src/index.tsindex ac6053b03..e9d0e5054 100644--- a/packages/server/src/index.ts+++ b/packages/server/src/index.ts@@ -239,6 +239,7 @@ export {buildIngressPolicy,ExposureConsentError,getIngressContext,+ hasForwardingHeaders,type IngressPolicy,type IngressRequestContext,isHostAdmitted,@@ -415,13 +416,6 @@ 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/ingress-policy.test.ts b/packages/server/src/ingress-policy.test.tsindex d55710867..225ace2e2 100644--- a/packages/server/src/ingress-policy.test.ts+++ b/packages/server/src/ingress-policy.test.ts@@ -3,9 +3,12 @@ import { describe, expect, test } from 'vitest';import {buildIngressPolicy,getIngressContext,+ hasForwardingHeaders,+ hostHeaderMatchesPublicHost,isHostAdmitted,isOriginAdmitted,isPeerAdmitted,+ normalizeHostHeader,stampIngressContext,tripsForwardedHeaderTripwire,} from './ingress-policy.ts';@@ -24,10 +27,16 @@ function runtime(overrides: Partial<ServerRuntimeConfig> = {}): ServerRuntimeCon};}-const LEGACY_REMOTE = {- url: 'https://myproject.ngrok.app',- publicHost: 'myproject.ngrok.app',- port: 24_550,+/**+ * The runtime shape `ok start --remote <url>` expands to: declared public+ * origin + consent on a loopback bind — no dedicated tunnel shape.+ */+const REMOTE_ALIAS_RUNTIME: Partial<ServerRuntimeConfig> = {+ publicUrl: 'https://myproject.ngrok.app',+ publicUrlSource: 'server',+ allowExternal: true,+ idleShutdown: 'off',+ openBrowser: false,};describe('buildIngressPolicy', () => {@@ -36,7 +45,6 @@ describe('buildIngressPolicy', () => {expect(policy.allowExternal).toBe(false);expect(policy.bindLiterals).toEqual([]);expect(policy.publicOrigin).toBeUndefined();- expect(policy.legacyRemote).toBeUndefined();expect(policy.tolerateForwardedHeaders).toBe(false);});@@ -67,8 +75,11 @@ describe('buildIngressPolicy', () => {expect(aliased.publicOrigin).toBeUndefined();});- test('forwarded headers are tolerated only under legacy remote, or consent + declared publicUrl', () => {- expect(buildIngressPolicy({ remoteAccess: LEGACY_REMOTE }).tolerateForwardedHeaders).toBe(true);+ test('forwarded headers are tolerated only under consent + declared publicUrl', () => {+ // The --remote alias lands exactly here: its expansion carries both keys.+ expect(+ buildIngressPolicy({ serverRuntime: runtime(REMOTE_ALIAS_RUNTIME) }).tolerateForwardedHeaders,+ ).toBe(true);expect(buildIngressPolicy({serverRuntime: runtime({@@ -229,6 +240,58 @@ describe('isOriginAdmitted — if present, must match; scheme-matched for public});});+describe('the --remote alias shape — tunnel admission via the ratified keys', () => {+ // Behavior-preservation pins for the legacy `--remote` contract, expressed+ // through the ONE policy: the tunnel's public Host is admitted, its https+ // origin is admitted, foreign names stay refused.+ const tunnel = buildIngressPolicy({ serverRuntime: runtime(REMOTE_ALIAS_RUNTIME) });++ test('the tunnel public Host is admitted, with or without default-port suffix', () => {+ expect(isHostAdmitted('myproject.ngrok.app', tunnel)).toBe(true);+ expect(isHostAdmitted('myproject.ngrok.app:443', tunnel)).toBe(true);+ expect(isHostAdmitted('127.0.0.1:24550', tunnel)).toBe(true);+ expect(isHostAdmitted('evil.example.com', tunnel)).toBe(false);+ expect(isHostAdmitted(undefined, tunnel)).toBe(false);+ });++ test('the https tunnel origin is admitted; http and foreign origins are not', () => {+ expect(isOriginAdmitted('https://myproject.ngrok.app', tunnel)).toBe(true);+ expect(isOriginAdmitted('http://myproject.ngrok.app', tunnel)).toBe(false);+ expect(isOriginAdmitted('https://evil.example.com', tunnel)).toBe(false);+ });++ test('forwarding headers (tunnels always inject them) do not trip the wire', () => {+ expect(+ tripsForwardedHeaderTripwire({ headers: { 'x-forwarded-for': '203.0.113.7' } }, tunnel),+ ).toBe(false);+ });+});++describe('normalizeHostHeader / hostHeaderMatchesPublicHost', () => {+ test('matches the public host, with or without default-port suffix, case-insensitively', () => {+ expect(normalizeHostHeader('MyProject.NGROK.app:443')).toBe('myproject.ngrok.app');+ expect(normalizeHostHeader('host.example:8080')).toBe('host.example:8080');+ 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);+ });+});++describe('hasForwardingHeaders', () => {+ test('detects standard forwarding headers; plain local requests carry none', () => {+ expect(hasForwardingHeaders({ headers: { 'x-forwarded-for': '203.0.113.7' } })).toBe(true);+ expect(hasForwardingHeaders({ headers: { forwarded: 'for=203.0.113.7' } })).toBe(true);+ expect(hasForwardingHeaders({ headers: { host: 'localhost:24550' } })).toBe(false);+ });+});+describe('tripsForwardedHeaderTripwire', () => {test('fires on forwarding headers unless the policy tolerates them', () => {const local = buildIngressPolicy({});diff --git a/packages/server/src/ingress-policy.ts b/packages/server/src/ingress-policy.tsindex 53812c60a..842e6e92b 100644--- a/packages/server/src/ingress-policy.ts+++ b/packages/server/src/ingress-policy.ts@@ -1,12 +1,15 @@/*** One ingress policy for every admission gate — HTTP requests AND WebSocket- * upgrades. Built once at boot from the resolved `server.*` runtime plus the- * legacy `--remote` shape, then threaded to every gate site: the surface- * admission prelude (`admitRequestSurface`), the `/api/*` pipeline gates, the- * `/mcp` gates, the collaboration host's upgrade admission, the config-doc- * admission, and the local-op security checks. One policy, one set of- * predicates — the HTTP and WS halves of the server can never disagree about- * who is admitted.+ * upgrades. Built once at boot from the resolved `server.*` runtime, then+ * threaded to every gate site: the surface admission prelude+ * (`admitRequestSurface`), the `/api/*` pipeline gates, the `/mcp` gates, the+ * collaboration host's upgrade admission, the config-doc admission, and the+ * local-op security checks. One policy, one set of predicates — the HTTP and+ * WS halves of the server can never disagree about who is admitted.+ *+ * The `ok start --remote <url>` flag is CLI sugar over the same keys (it+ * expands to `server.publicUrl` + loopback `server.bind` ++ * `server.allowExternal`) — there is no separate tunnel policy shape.** The three predicates and what governs each:*@@ -17,9 +20,9 @@* - HOST (`isHostAdmitted`) — the name the client dialed (DNS-rebinding* defense). Always validates, in every mode, against loopback names + the* non-loopback bind-address literals + the declared `server.publicUrl`- * host + the legacy tunnel host. Consent does NOT widen this set: an- * unconfigured name stays refused, so a rebound page presenting the- * attacker's domain is refused no matter what the peer looks like.+ * host. Consent does NOT widen this set: an unconfigured name stays+ * refused, so a rebound page presenting the attacker's domain is refused+ * no matter what the peer looks like.* - ORIGIN (`isOriginAdmitted`) — browser CSRF defense; "if present, must* match" (curl and MCP clients send none). Admits the loopback set, the* null/file:// Electron shapes, the bind literals, and the declared@@ -34,12 +37,40 @@ import type { IncomingMessage } from 'node:http';import type { ServerRuntimeConfig } from '@inkeep/open-knowledge-core';import { isAllowedApiOrigin } from './api-origin.ts';import { isAllowedWorkspaceHostHeader, isLoopbackAddress } from './loopback.ts';-import {- hasForwardingHeaders,- hostHeaderMatchesPublicHost,- normalizeHostHeader,- type ResolvedRemoteAccess,-} from './remote-access.ts';++/** Strip a default-port suffix so `host:443`/`host:80` compare equal to `host`. */+export function normalizeHostHeader(host: string): string {+ return host.replace(/:(443|80)$/, '').toLowerCase();+}++/** True when a raw `Host` names the declared public host — for the Host gates. */+export function hostHeaderMatchesPublicHost(host: string | undefined, publicHost: string): boolean {+ return host !== undefined && normalizeHostHeader(host) === publicHost;+}++/**+ * Proxy-forwarding headers (standard `X-Forwarded-*` / `Forwarded` plus common+ * vendor ones). Their presence while the policy does not tolerate them means+ * a tunnel/proxy points at a server that never opted into exposure — the+ * tripwire refuses with a hint.+ */+const FORWARDING_HEADERS = [+ 'x-forwarded-for',+ 'x-forwarded-proto',+ 'x-forwarded-host',+ 'forwarded',+ 'x-real-ip',+ 'x-client-ip',+ 'x-cluster-client-ip',+ 'cf-connecting-ip',+ 'fastly-client-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);+}/*** Remediation detail for a `host-not-allowed` refusal. The read gate now fires@@ -73,13 +104,11 @@ export interface IngressPolicy {* Origin checks since the key admits http for tailnet/LAN deployments.*/publicOrigin: { host: string; protocol: string } | undefined;- /** The legacy `ok start --remote` shape (tunnel publicHost; https-only). */- legacyRemote: ResolvedRemoteAccess | undefined;/*** Proxy-forwarding headers tolerated (never trusted — addressing and- * identity stay socket/config-derived). True under the legacy remote flow- * or under consent with a declared public origin; otherwise their presence- * trips the proxied-request tripwire.+ * identity stay socket/config-derived). True under consent with a declared+ * public origin; otherwise their presence trips the proxied-request+ * tripwire.*/tolerateForwardedHeaders: boolean;}@@ -98,8 +127,6 @@ export interface BuildIngressPolicyInput {* loopback-only default (test rigs, legacy construction sites).*/serverRuntime?: ServerRuntimeConfig | undefined;- /** Legacy `--remote` resolution; undefined when remote is not armed. */- remoteAccess?: ResolvedRemoteAccess | null | undefined;}/** Loopback / wildcard shapes that never contribute an admissible Host name. */@@ -112,7 +139,6 @@ function normalizeBindLiteral(address: string): string {export function buildIngressPolicy(input: BuildIngressPolicyInput): IngressPolicy {const runtime = input.serverRuntime;- const legacyRemote = input.remoteAccess ?? undefined;const bindLiterals =runtime === undefined@@ -134,9 +160,7 @@ export function buildIngressPolicy(input: BuildIngressPolicyInput): IngressPolicallowExternal,bindLiterals,publicOrigin,- legacyRemote,- tolerateForwardedHeaders:- legacyRemote !== undefined || (allowExternal && publicOrigin !== undefined),+ tolerateForwardedHeaders: allowExternal && publicOrigin !== undefined,};}@@ -162,9 +186,9 @@ function hostnameOfHostHeader(host: string): string | null {}/**- * HOST gate: loopback names, the bind literals (any port), the declared- * `publicUrl` host (exact host[:port] after default-port normalization), and- * the legacy tunnel host. Never widened by consent.+ * HOST gate: loopback names, the bind literals (any port), and the declared+ * `publicUrl` host (exact host[:port] after default-port normalization).+ * Never widened by consent.*/export function isHostAdmitted(host: string | undefined, policy: IngressPolicy): boolean {if (isAllowedWorkspaceHostHeader(host)) return true;@@ -173,26 +197,19 @@ export function isHostAdmitted(host: string | undefined, policy: IngressPolicy):const hostname = hostnameOfHostHeader(host);if (hostname !== null && policy.bindLiterals.includes(hostname)) return true;}- if (- policy.publicOrigin !== undefined &&- hostHeaderMatchesPublicHost(host, policy.publicOrigin.host)- ) {- return true;- }return (- policy.legacyRemote !== undefined &&- hostHeaderMatchesPublicHost(host, policy.legacyRemote.publicHost)+ policy.publicOrigin !== undefined && hostHeaderMatchesPublicHost(host, policy.publicOrigin.host));}/*** ORIGIN gate ("if present, must match" — callers skip when absent): the- * loopback/null/file:// set, the legacy tunnel origin (https), the declared- * public origin (scheme-matched against `publicUrl`'s own scheme), and the- * bind literals over http or https.+ * loopback/null/file:// set, the declared public origin (scheme-matched+ * against `publicUrl`'s own scheme), and the bind literals over http or+ * https.*/export function isOriginAdmitted(origin: string, policy: IngressPolicy): boolean {- if (isAllowedApiOrigin(origin, policy.legacyRemote?.publicHost)) return true;+ if (isAllowedApiOrigin(origin)) return true;let parsed: URL;try {parsed = new URL(origin);diff --git a/packages/server/src/local-op-security.test.ts b/packages/server/src/local-op-security.test.tsindex bd2d6b047..f4421be07 100644--- a/packages/server/src/local-op-security.test.ts+++ b/packages/server/src/local-op-security.test.ts@@ -719,12 +719,19 @@ describe('hasValidLocalOpOrigin with a remote public host', () => {const reqWithOrigin = (origin: string) =>({ headers: { origin }, socket: { remoteAddress: '127.0.0.1' } }) as never;+ // The `ok start --remote` alias shape: declared public origin + consent on+ // a loopback bind.const tunnelPolicy = () =>buildIngressPolicy({- remoteAccess: {- url: 'https://myproject.ngrok.app',- publicHost: 'myproject.ngrok.app',- port: 24_550,+ serverRuntime: {+ port: undefined,+ bind: ['127.0.0.1'],+ publicUrl: 'https://myproject.ngrok.app',+ publicUrlSource: 'server',+ allowExternal: true,+ openBrowser: false,+ idleShutdown: 'off',+ loopbackOnly: true,},});diff --git a/packages/server/src/local-op-security.ts b/packages/server/src/local-op-security.tsindex cc016feba..05c540fe3 100644--- a/packages/server/src/local-op-security.ts+++ b/packages/server/src/local-op-security.ts@@ -20,7 +20,6 @@ import { errorResponse } from './http/error-response.ts';import { errnoCode } from './http/handler-utils.ts';import { buildIngressPolicy, type IngressPolicy, isPeerAdmitted } from './ingress-policy.ts';import { getLogger } from './logger.ts';-import { originMatchesPublicHost } from './remote-access.ts';const log = getLogger('local-op-security');@@ -228,9 +227,9 @@ export function isLoopbackRequest(req: IncomingMessage): boolean {* Returns true if the Origin header (when present) is admitted. Absent Origin* header is allowed (same-origin browser requests / CLI tools).*- * The admitted set beyond loopback comes from the ingress policy: the legacy- * tunnel origin, the declared `publicUrl` origin (scheme-matched), and the- * bind literals — an empty policy keeps the historical loopback-only set.+ * The admitted set beyond loopback comes from the ingress policy: the+ * declared `publicUrl` origin (scheme-matched) and the bind literals — an+ * empty policy keeps the historical loopback-only set.** Parses the URL and compares hostname exactly; a raw `startsWith` would* accept crafted origins like `http://127.0.0.1.evil.com` if DNS rebinding@@ -239,10 +238,6 @@ export function isLoopbackRequest(req: IncomingMessage): boolean {export function hasValidLocalOpOrigin(req: IncomingMessage, policy?: IngressPolicy): boolean {const origin = req.headers.origin;if (!origin) return true;- const legacyHost = policy?.legacyRemote?.publicHost;- if (legacyHost !== undefined && originMatchesPublicHost(origin, legacyHost)) {- 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.@@ -277,7 +272,7 @@ export function hasValidLocalOpOrigin(req: IncomingMessage, policy?: IngressPoli}}-/** Strip a default-port suffix — mirrors `normalizeHostHeader` in remote-access.ts. */+/** Strip a default-port suffix — mirrors `normalizeHostHeader` in ingress-policy.ts. */function normalizeOriginHost(host: string): string {return host.replace(/:(443|80)$/, '').toLowerCase();}diff --git a/packages/server/src/mcp-mount.ts b/packages/server/src/mcp-mount.tsindex f7632263d..afc69cc8b 100644--- a/packages/server/src/mcp-mount.ts+++ b/packages/server/src/mcp-mount.ts@@ -227,7 +227,7 @@ export function mountMcpAndApi(opts: MountMcpAndApiOptions): MountMcpAndApiHandlconst onRequest = (req: IncomingMessage, res: ServerResponse): void => {const url = req.url?.split('?')[0];// Surface-wide admission prelude — the proxied-request tripwire plus the- // remote-access admit decision. Shared with the natively-mounted /api/*+ // exposure admit decision. Shared with the natively-mounted /api/*// routes (`admitRequestSurface` in http-app.ts), which sit above the// strangler catch-all and would otherwise bypass it.if (!admitRequestSurface(req, res, ingressPolicy, 'mcp-mount')) return;@@ -236,22 +236,19 @@ export function mountMcpAndApi(opts: MountMcpAndApiOptions): MountMcpAndApiHandlconst sessionId = Array.isArray(req.headers['mcp-session-id'])? req.headers['mcp-session-id'][0]: req.headers['mcp-session-id'];- if (ingressPolicy.legacyRemote === undefined) {- // The policy's peer + Host gate pair. (With legacy remote armed the- // shared admit gate above already enforced the superset.)- if (!isPeerAdmitted(req.socket.remoteAddress, ingressPolicy)) {- errorResponse(res, 403, 'urn:ok:error:loopback-required', 'Loopback required.', {- handler: 'mcp',- });- return;- }- if (!isHostAdmitted(req.headers.host, ingressPolicy)) {- errorResponse(res, 403, 'urn:ok:error:host-not-allowed', 'Host header not allowed.', {- handler: 'mcp',- detail: HOST_NOT_ADMITTED_REMEDIATION,- });- return;- }+ // The policy's peer + Host gate pair.+ if (!isPeerAdmitted(req.socket.remoteAddress, ingressPolicy)) {+ errorResponse(res, 403, 'urn:ok:error:loopback-required', 'Loopback required.', {+ handler: 'mcp',+ });+ return;+ }+ if (!isHostAdmitted(req.headers.host, ingressPolicy)) {+ errorResponse(res, 403, 'urn:ok:error:host-not-allowed', 'Host header not allowed.', {+ handler: 'mcp',+ detail: HOST_NOT_ADMITTED_REMEDIATION,+ });+ return;}if (origin !== undefined && !isOriginAdmitted(origin, ingressPolicy)) {errorResponse(res, 403, 'urn:ok:error:invalid-origin', 'Origin not allowed.', {diff --git a/packages/server/src/remote-access.test.ts b/packages/server/src/remote-access.test.tsdeleted file mode 100644index ef3932f11..000000000--- a/packages/server/src/remote-access.test.ts+++ /dev/null@@ -1,134 +0,0 @@-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.tsdeleted file mode 100644index 00e438fcc..000000000--- a/packages/server/src/remote-access.ts+++ /dev/null@@ -1,122 +0,0 @@-/**- * 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 { DEFAULT_REMOTE_PORT } from '@inkeep/open-knowledge-core';-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 (`remote.port`, falling back to 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 ?? DEFAULT_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`. */-export 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',- 'x-forwarded-host',- 'forwarded',- 'x-real-ip',- 'x-client-ip',- 'x-cluster-client-ip',- 'cf-connecting-ip',- 'fastly-client-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.tsindex b6ad5d822..8b1d45577 100644--- a/packages/server/src/remote-mcp.test.ts+++ b/packages/server/src/remote-mcp.test.ts@@ -8,12 +8,16 @@* 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.+ * The ingress policy is built from the SAME `server.*` runtime shape the+ * `ok start --remote <url>` alias expands to (`server.publicUrl` + consent+ * on a loopback bind); these tests are the behavior-preservation pins for+ * the legacy tunnel contract now that the dedicated remote topology is+ * gone. With the tunnel shape armed there is ONE gate: Host on the+ * allowlist (loopback names or the tunnel's public host). 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). Without the shape, proxied requests trip the forwarding-header+ * tripwire instead of inheriting local trust.*/import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';@@ -26,13 +30,13 @@ import { connect as createNetConnection } from 'node:net';import { tmpdir } from 'node:os';import { join } from 'node:path';import type { Hocuspocus } from '@hocuspocus/server';+import { resolveServerRuntimeConfig } from '@inkeep/open-knowledge-core';import { afterEach, describe, expect, test } from 'vitest';import { ConfigSchema } from './config/schema.ts';import { buildIngressPolicy } from './ingress-policy.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';@@ -83,15 +87,16 @@ interface RigExtras {acpThreadManager?: unknown;}-async function bootRemoteRig(- remote: Record<string, unknown>,- extras: RigExtras = {},-): Promise<Rig> {+async function bootRemoteRig(publicUrl: string | null, 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);+ // Exactly the keys `ok start --remote <url>` expands to: declared public+ // origin + consent; the rig's listener stays loopback like the coerced+ // remote bind.+ const config = ConfigSchema.parse(+ publicUrl === null ? {} : { server: { publicUrl, allowExternal: true } },+ );const port = await getFreeLoopbackPort();const handler: McpHttpHandler = createMcpHttpHandler({contentDir,@@ -105,7 +110,7 @@ async function bootRemoteRig(nativeApi: undefined,hocuspocus,mcpHttpHandler: handler,- ingressPolicy: buildIngressPolicy({ remoteAccess }),+ ingressPolicy: buildIngressPolicy({ serverRuntime: resolveServerRuntimeConfig(config) }),...(extras.reactShellMiddleware ? { reactShellMiddleware: extras.reactShellMiddleware } : {}),...(extras.acpThreadManager !== undefined? { acpThreadManager: extras.acpThreadManager as never }@@ -295,7 +300,7 @@ function attemptCollabUpgrade(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 rig = await bootRemoteRig(PUBLIC_URL);const names = await listToolNames(rig.port, TUNNEL_HEADERS);expect(names).toContain('exec');expect(names).toContain('search');@@ -303,13 +308,13 @@ describe('remote enabled — trust-the-tunnel admission', () => {});test('local loopback sessions keep the full tool set when remote is enabled', async () => {- const rig = await bootRemoteRig({ url: PUBLIC_URL });+ const rig = await bootRemoteRig(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 rig = await bootRemoteRig(PUBLIC_URL);const mcp = await raw(rig.port, {method: 'POST',path: '/mcp',@@ -322,7 +327,7 @@ describe('remote enabled — trust-the-tunnel admission', () => {});test('non-/mcp surfaces are reachable under the tunnel Host (one gate for everything)', async () => {- const rig = await bootRemoteRig({ url: PUBLIC_URL });+ const rig = await bootRemoteRig(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 });@@ -332,13 +337,13 @@ describe('remote enabled — trust-the-tunnel admission', () => {});test('forwarding headers are fine when remote is enabled (tunnels always inject them)', async () => {- const rig = await bootRemoteRig({ url: PUBLIC_URL });+ const rig = await bootRemoteRig(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 });+ const rig = await bootRemoteRig(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, {@@ -350,7 +355,7 @@ describe('remote enabled — trust-the-tunnel admission', () => {});test('/collab upgrade admits the tunnel Host and drops wrong Hosts', async () => {- const rig = await bootRemoteRig({ url: PUBLIC_URL });+ const rig = await bootRemoteRig(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',@@ -358,7 +363,7 @@ describe('remote enabled — trust-the-tunnel admission', () => {});test('/collab/keepalive upgrade admits the tunnel Host and drops wrong Hosts', async () => {- const rig = await bootRemoteRig({ url: PUBLIC_URL });+ const rig = await bootRemoteRig(PUBLIC_URL);await expect(attemptCollabUpgrade(rig.port, { Host: PUBLIC_HOST }, '/collab/keepalive'),).resolves.toBe('upgraded');@@ -371,10 +376,7 @@ describe('remote enabled — trust-the-tunnel admission', () => {// 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: () => [] } },- );+ const rig = await bootRemoteRig(PUBLIC_URL, { acpThreadManager: { listThreads: () => [] } });await expect(attemptCollabUpgrade(rig.port, { Host: PUBLIC_HOST }, '/collab/thread'),).resolves.toBe('upgraded');@@ -392,7 +394,7 @@ describe('remote enabled — trust-the-tunnel admission', () => {});test('default-port Host suffix still matches', async () => {- const rig = await bootRemoteRig({ url: PUBLIC_URL });+ const rig = await bootRemoteRig(PUBLIC_URL);const api = await raw(rig.port, {path: '/api/pages',headers: { host: `${PUBLIC_HOST}:443` },@@ -403,7 +405,7 @@ describe('remote enabled — trust-the-tunnel admission', () => {describe('remote disabled — the forwarding-header tripwire', () => {test('proxied requests are refused with the --remote hint', async () => {- const rig = await bootRemoteRig({});+ const rig = await bootRemoteRig(null);const res = await raw(rig.port, {path: '/api/pages',headers: { host: `127.0.0.1:${rig.port}`, 'x-forwarded-for': '203.0.113.7' },@@ -413,7 +415,7 @@ describe('remote disabled — the forwarding-header tripwire', () => {});test('vendor proxy headers (X-Real-IP, CF-Connecting-IP, True-Client-IP) also trip the wire', async () => {- const rig = await bootRemoteRig({});+ const rig = await bootRemoteRig(null);for (const header of ['x-real-ip', 'cf-connecting-ip', 'true-client-ip']) {const res = await raw(rig.port, {path: '/api/pages',@@ -425,7 +427,7 @@ describe('remote disabled — the forwarding-header tripwire', () => {});test('unproxied local requests are served as always', async () => {- const rig = await bootRemoteRig({});+ const rig = await bootRemoteRig(null);const api = await raw(rig.port, {path: '/api/pages',headers: { host: `127.0.0.1:${rig.port}` },@@ -436,7 +438,7 @@ describe('remote disabled — the forwarding-header tripwire', () => {});test('a proxied /collab upgrade is dropped', async () => {- const rig = await bootRemoteRig({});+ const rig = await bootRemoteRig(null);await expect(attemptCollabUpgrade(rig.port, {Host: `127.0.0.1:${rig.port}`,@@ -446,7 +448,7 @@ describe('remote disabled — the forwarding-header tripwire', () => {});test('tunnel Host without remote enabled is refused (no forwarding headers needed)', async () => {- const rig = await bootRemoteRig({});+ const rig = await bootRemoteRig(null);const res = await raw(rig.port, {method: 'POST',path: '/mcp',@@ -467,7 +469,7 @@ describe('remote enabled — UI over the same port', () => {};test('the shell serves at / and /assets/* under the tunnel Host', async () => {- const rig = await bootRemoteRig({ url: PUBLIC_URL }, { reactShellMiddleware: shell });+ const rig = await bootRemoteRig(PUBLIC_URL, { reactShellMiddleware: shell });const root = await raw(rig.port, { path: '/', headers: TUNNEL_HEADERS });expect(root.status).toBe(200);expect(root.body).toContain('SHELL /');@@ -479,13 +481,13 @@ describe('remote enabled — UI over the same port', () => {});test('the shell is refused under a wrong Host', async () => {- const rig = await bootRemoteRig({ url: PUBLIC_URL }, { reactShellMiddleware: shell });+ const rig = await bootRemoteRig(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 rig = await bootRemoteRig(PUBLIC_URL);const names = await listToolNames(rig.port, {host: PUBLIC_HOST,origin: `https://${PUBLIC_HOST}`,@@ -494,7 +496,7 @@ describe('remote enabled — UI over the same port', () => {});test('a foreign browser Origin is still refused on /mcp', async () => {- const rig = await bootRemoteRig({ url: PUBLIC_URL });+ const rig = await bootRemoteRig(PUBLIC_URL);const res = await raw(rig.port, {method: 'POST',path: '/mcp',diff --git a/packages/server/src/server-factory.test.ts b/packages/server/src/server-factory.test.tsindex cdd499a62..19f94c444 100644--- a/packages/server/src/server-factory.test.ts+++ b/packages/server/src/server-factory.test.ts@@ -2726,11 +2726,18 @@ describe('createServer() — config-doc admission guard', () => {contentDir: tmpDir,projectDir: tmpDir,quiet: true,+ // The `ok start --remote` alias shape: declared public origin + consent+ // on a loopback bind.ingressPolicy: buildIngressPolicy({- remoteAccess: {- url: 'https://myproject.ngrok.app',- publicHost: 'myproject.ngrok.app',- port: 24_550,+ serverRuntime: {+ port: undefined,+ bind: ['127.0.0.1'],+ publicUrl: 'https://myproject.ngrok.app',+ publicUrlSource: 'server',+ allowExternal: true,+ openBrowser: false,+ idleShutdown: 'off',+ loopbackOnly: true,},}),});